hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
listlengths
5
5
{ "id": 6, "code_window": [ "\n", "from flask import Markup, flash, redirect\n", "from flask_appbuilder import CompactCRUDMixin, expose\n", "from flask_appbuilder.models.sqla.interface import SQLAInterface\n", "import sqlalchemy as sa\n", "\n", "from flask_babel import lazy_gettext as _\n", "from flask_babel import gettext as __\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "superset/connectors/sqla/views.py", "type": "replace", "edit_start_line_idx": 7 }
import React from 'react'; import configureStore from 'redux-mock-store'; import thunk from 'redux-thunk'; import URI from 'urijs'; import { Tab } from 'react-bootstrap'; import { shallow, mount } from 'enzyme'; import { describe, it } from 'mocha'; import { expect } from 'chai'; import sinon from 'sinon'; import { table, initialState } from './fixtures'; import TabbedSqlEditors from '../../../javascripts/SqlLab/components/TabbedSqlEditors'; import SqlEditor from '../../../javascripts/SqlLab/components/SqlEditor'; describe('TabbedSqlEditors', () => { const middlewares = [thunk]; const mockStore = configureStore(middlewares); const store = mockStore(initialState); const tabHistory = [ 'dfsadfs', 'newEditorId', ]; const tables = [Object.assign({}, table[0], { dataPreviewQueryId: 'B1-VQU1zW', queryEditorId: 'newEditorId', })]; const queryEditors = [{ autorun: false, dbId: 1, id: 'newEditorId', latestQueryId: 'B1-VQU1zW', schema: null, selectedText: null, sql: 'SELECT ds...', title: 'Untitled Query', }]; const queries = { 'B1-VQU1zW': { id: 'B1-VQU1zW', sqlEditorId: 'newEditorId', }, }; const mockedProps = { actions: {}, databases: {}, tables: [], queries: {}, queryEditors: initialState.queryEditors, tabHistory: initialState.tabHistory, editorHeight: '', }; const getWrapper = () => ( shallow(<TabbedSqlEditors {...mockedProps} />, { context: { store }, }).dive()); let wrapper; it('is valid', () => { expect( React.isValidElement(<TabbedSqlEditors {...mockedProps} />), ).to.equal(true); }); describe('componentDidMount', () => { let uriStub; beforeEach(() => { sinon.stub(window.history, 'replaceState'); sinon.spy(TabbedSqlEditors.prototype, 'componentDidMount'); uriStub = sinon.stub(URI.prototype, 'search'); }); afterEach(() => { window.history.replaceState.restore(); TabbedSqlEditors.prototype.componentDidMount.restore(); uriStub.restore(); }); it('should handle id', () => { uriStub.returns({ id: 1 }); wrapper = mount(<TabbedSqlEditors {...mockedProps} />, { context: { store }, }); expect(TabbedSqlEditors.prototype.componentDidMount.calledOnce).to.equal(true); expect(window.history.replaceState.getCall(0).args[2]) .to.equal('/superset/sqllab'); }); it('should handle savedQueryId', () => { uriStub.returns({ savedQueryId: 1 }); wrapper = mount(<TabbedSqlEditors {...mockedProps} />, { context: { store }, }); expect(TabbedSqlEditors.prototype.componentDidMount.calledOnce).to.equal(true); expect(window.history.replaceState.getCall(0).args[2]) .to.equal('/superset/sqllab'); }); it('should handle sql', () => { uriStub.returns({ sql: 1, dbid: 1 }); wrapper = mount(<TabbedSqlEditors {...mockedProps} />, { context: { store }, }); expect(TabbedSqlEditors.prototype.componentDidMount.calledOnce).to.equal(true); expect(window.history.replaceState.getCall(0).args[2]) .to.equal('/superset/sqllab'); }); }); describe('componentWillReceiveProps', () => { let spy; beforeEach(() => { wrapper = getWrapper(); spy = sinon.spy(TabbedSqlEditors.prototype, 'componentWillReceiveProps'); wrapper.setProps({ queryEditors, queries, tabHistory, tables }); }); afterEach(() => { spy.restore(); }); it('should update queriesArray and dataPreviewQueries', () => { expect(wrapper.state().queriesArray.slice(-1)[0]).to.equal(queries['B1-VQU1zW']); expect(wrapper.state().dataPreviewQueries.slice(-1)[0]).to.equal(queries['B1-VQU1zW']); }); }); it('should rename Tab', () => { global.prompt = () => ('new title'); wrapper = getWrapper(); sinon.stub(wrapper.instance().props.actions, 'queryEditorSetTitle'); wrapper.instance().renameTab(queryEditors[0]); expect(wrapper.instance().props.actions.queryEditorSetTitle.getCall(0).args[1]).to.equal('new title'); delete global.prompt; }); it('should removeQueryEditor', () => { wrapper = getWrapper(); sinon.stub(wrapper.instance().props.actions, 'removeQueryEditor'); wrapper.instance().removeQueryEditor(queryEditors[0]); expect(wrapper.instance().props.actions.removeQueryEditor.getCall(0).args[0]) .to.equal(queryEditors[0]); }); it('should add new query editor', () => { wrapper = getWrapper(); sinon.stub(wrapper.instance().props.actions, 'addQueryEditor'); wrapper.instance().newQueryEditor(); expect(wrapper.instance().props.actions.addQueryEditor.getCall(0).args[0].title) .to.contain('Untitled Query'); }); it('should handle select', () => { wrapper = getWrapper(); sinon.spy(wrapper.instance(), 'newQueryEditor'); sinon.stub(wrapper.instance().props.actions, 'setActiveQueryEditor'); wrapper.instance().handleSelect('add_tab'); expect(wrapper.instance().newQueryEditor.callCount).to.equal(1); wrapper.instance().handleSelect('123'); expect(wrapper.instance().props.actions.setActiveQueryEditor.getCall(0).args[0].id) .to.contain(123); wrapper.instance().newQueryEditor.restore(); }); it('should render', () => { wrapper = getWrapper(); wrapper.setState({ hideLeftBar: true }); const firstTab = wrapper.find(Tab).first(); expect(firstTab.props().eventKey).to.contain(initialState.queryEditors[0].id); expect(firstTab.find(SqlEditor)).to.have.length(1); const lastTab = wrapper.find(Tab).last(); expect(lastTab.props().eventKey).to.contain('add_tab'); }); });
superset/assets/spec/javascripts/sqllab/TabbedSqlEditors_spec.jsx
0
https://github.com/apache/superset/commit/64ef8b14b4f7b7917a8bab4d22e21106b91b7262
[ 0.0001748863433022052, 0.00017087970627471805, 0.00016548021812923253, 0.00017107540043070912, 0.000002684986839085468 ]
{ "id": 6, "code_window": [ "\n", "from flask import Markup, flash, redirect\n", "from flask_appbuilder import CompactCRUDMixin, expose\n", "from flask_appbuilder.models.sqla.interface import SQLAInterface\n", "import sqlalchemy as sa\n", "\n", "from flask_babel import lazy_gettext as _\n", "from flask_babel import gettext as __\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "superset/connectors/sqla/views.py", "type": "replace", "edit_start_line_idx": 7 }
import React from 'react'; import { expect } from 'chai'; import { describe, it } from 'mocha'; import { shallow, mount } from 'enzyme'; import { OverlayTrigger } from 'react-bootstrap'; import EmbedCodeButton from '../../../../javascripts/explore/components/EmbedCodeButton'; describe('EmbedCodeButton', () => { const defaultProps = { slice: { data: { standalone_endpoint: 'endpoint_url', }, }, }; it('renders', () => { expect(React.isValidElement(<EmbedCodeButton {...defaultProps} />)).to.equal(true); }); it('renders overlay trigger', () => { const wrapper = shallow(<EmbedCodeButton {...defaultProps} />); expect(wrapper.find(OverlayTrigger)).to.have.length(1); }); it('returns correct embed code', () => { const wrapper = mount(<EmbedCodeButton {...defaultProps} />); wrapper.setState({ height: '1000', width: '2000', srcLink: 'http://localhost/endpoint_url', }); const embedHTML = ( '<iframe\n' + ' width="2000"\n' + ' height="1000"\n' + ' seamless\n' + ' frameBorder="0"\n' + ' scrolling="no"\n' + ' src="nullendpoint_url&height=1000"\n' + '>\n' + '</iframe>' ); expect(wrapper.instance().generateEmbedHTML()).to.equal(embedHTML); }); });
superset/assets/spec/javascripts/explore/components/EmbedCodeButton_spec.jsx
0
https://github.com/apache/superset/commit/64ef8b14b4f7b7917a8bab4d22e21106b91b7262
[ 0.00017412559827789664, 0.00017076829681172967, 0.00016784451145213097, 0.00017000705702230334, 0.0000021129280867171474 ]
{ "id": 1, "code_window": [ "\n", "\t\tif (!isMouseRightClick(e.browserEvent)) {\n", "\t\t\tthis.list.setSelection([focus], e.browserEvent);\n", "\t\t}\n", "\n", "\t\tthis._onPointer.fire(e);\n", "\t}\n", "\n", "\tprotected onDoubleClick(e: IListMouseEvent<T>): void {\n", "\t\tif (isInputElement(e.browserEvent.target as HTMLElement) || isMonacoEditor(e.browserEvent.target as HTMLElement)) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\te.browserEvent.preventDefault();\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "add", "edit_start_line_idx": 711 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IDragAndDropData } from 'vs/base/browser/dnd'; import { createStyleSheet, Dimension, EventHelper } from 'vs/base/browser/dom'; import { DomEmitter } from 'vs/base/browser/event'; import { IKeyboardEvent, StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { Gesture } from 'vs/base/browser/touch'; import { alert, AriaRole } from 'vs/base/browser/ui/aria/aria'; import { CombinedSpliceable } from 'vs/base/browser/ui/list/splice'; import { ScrollableElementChangeOptions } from 'vs/base/browser/ui/scrollbar/scrollableElementOptions'; import { binarySearch, firstOrDefault, range } from 'vs/base/common/arrays'; import { timeout } from 'vs/base/common/async'; import { Color } from 'vs/base/common/color'; import { memoize } from 'vs/base/common/decorators'; import { Emitter, Event, EventBufferer } from 'vs/base/common/event'; import { matchesPrefix } from 'vs/base/common/filters'; import { KeyCode } from 'vs/base/common/keyCodes'; import { DisposableStore, dispose, IDisposable } from 'vs/base/common/lifecycle'; import { clamp } from 'vs/base/common/numbers'; import { mixin } from 'vs/base/common/objects'; import * as platform from 'vs/base/common/platform'; import { ScrollbarVisibility, ScrollEvent } from 'vs/base/common/scrollable'; import { ISpliceable } from 'vs/base/common/sequence'; import { IThemable } from 'vs/base/common/styler'; import { isNumber } from 'vs/base/common/types'; import 'vs/css!./list'; import { IIdentityProvider, IKeyboardNavigationDelegate, IKeyboardNavigationLabelProvider, IListContextMenuEvent, IListDragAndDrop, IListDragOverReaction, IListEvent, IListGestureEvent, IListMouseEvent, IListRenderer, IListTouchEvent, IListVirtualDelegate, ListError } from './list'; import { IListViewAccessibilityProvider, IListViewDragAndDrop, IListViewOptions, IListViewOptionsUpdate, ListView } from './listView'; interface ITraitChangeEvent { indexes: number[]; browserEvent?: UIEvent; } type ITraitTemplateData = HTMLElement; interface IRenderedContainer { templateData: ITraitTemplateData; index: number; } class TraitRenderer<T> implements IListRenderer<T, ITraitTemplateData> { private renderedElements: IRenderedContainer[] = []; constructor(private trait: Trait<T>) { } get templateId(): string { return `template:${this.trait.name}`; } renderTemplate(container: HTMLElement): ITraitTemplateData { return container; } renderElement(element: T, index: number, templateData: ITraitTemplateData): void { const renderedElementIndex = this.renderedElements.findIndex(el => el.templateData === templateData); if (renderedElementIndex >= 0) { const rendered = this.renderedElements[renderedElementIndex]; this.trait.unrender(templateData); rendered.index = index; } else { const rendered = { index, templateData }; this.renderedElements.push(rendered); } this.trait.renderIndex(index, templateData); } splice(start: number, deleteCount: number, insertCount: number): void { const rendered: IRenderedContainer[] = []; for (const renderedElement of this.renderedElements) { if (renderedElement.index < start) { rendered.push(renderedElement); } else if (renderedElement.index >= start + deleteCount) { rendered.push({ index: renderedElement.index + insertCount - deleteCount, templateData: renderedElement.templateData }); } } this.renderedElements = rendered; } renderIndexes(indexes: number[]): void { for (const { index, templateData } of this.renderedElements) { if (indexes.indexOf(index) > -1) { this.trait.renderIndex(index, templateData); } } } disposeTemplate(templateData: ITraitTemplateData): void { const index = this.renderedElements.findIndex(el => el.templateData === templateData); if (index < 0) { return; } this.renderedElements.splice(index, 1); } } class Trait<T> implements ISpliceable<boolean>, IDisposable { private length = 0; private indexes: number[] = []; private sortedIndexes: number[] = []; private readonly _onChange = new Emitter<ITraitChangeEvent>(); readonly onChange: Event<ITraitChangeEvent> = this._onChange.event; get name(): string { return this._trait; } @memoize get renderer(): TraitRenderer<T> { return new TraitRenderer<T>(this); } constructor(private _trait: string) { } splice(start: number, deleteCount: number, elements: boolean[]): void { deleteCount = Math.max(0, Math.min(deleteCount, this.length - start)); const diff = elements.length - deleteCount; const end = start + deleteCount; const sortedIndexes = [ ...this.sortedIndexes.filter(i => i < start), ...elements.map((hasTrait, i) => hasTrait ? i + start : -1).filter(i => i !== -1), ...this.sortedIndexes.filter(i => i >= end).map(i => i + diff) ]; const length = this.length + diff; if (this.sortedIndexes.length > 0 && sortedIndexes.length === 0 && length > 0) { const first = this.sortedIndexes.find(index => index >= start) ?? length - 1; sortedIndexes.push(Math.min(first, length - 1)); } this.renderer.splice(start, deleteCount, elements.length); this._set(sortedIndexes, sortedIndexes); this.length = length; } renderIndex(index: number, container: HTMLElement): void { container.classList.toggle(this._trait, this.contains(index)); } unrender(container: HTMLElement): void { container.classList.remove(this._trait); } /** * Sets the indexes which should have this trait. * * @param indexes Indexes which should have this trait. * @return The old indexes which had this trait. */ set(indexes: number[], browserEvent?: UIEvent): number[] { return this._set(indexes, [...indexes].sort(numericSort), browserEvent); } private _set(indexes: number[], sortedIndexes: number[], browserEvent?: UIEvent): number[] { const result = this.indexes; const sortedResult = this.sortedIndexes; this.indexes = indexes; this.sortedIndexes = sortedIndexes; const toRender = disjunction(sortedResult, indexes); this.renderer.renderIndexes(toRender); this._onChange.fire({ indexes, browserEvent }); return result; } get(): number[] { return this.indexes; } contains(index: number): boolean { return binarySearch(this.sortedIndexes, index, numericSort) >= 0; } dispose() { dispose(this._onChange); } } class SelectionTrait<T> extends Trait<T> { constructor(private setAriaSelected: boolean) { super('selected'); } override renderIndex(index: number, container: HTMLElement): void { super.renderIndex(index, container); if (this.setAriaSelected) { if (this.contains(index)) { container.setAttribute('aria-selected', 'true'); } else { container.setAttribute('aria-selected', 'false'); } } } } /** * The TraitSpliceable is used as a util class to be able * to preserve traits across splice calls, given an identity * provider. */ class TraitSpliceable<T> implements ISpliceable<T> { constructor( private trait: Trait<T>, private view: ListView<T>, private identityProvider?: IIdentityProvider<T> ) { } splice(start: number, deleteCount: number, elements: T[]): void { if (!this.identityProvider) { return this.trait.splice(start, deleteCount, elements.map(() => false)); } const pastElementsWithTrait = this.trait.get().map(i => this.identityProvider!.getId(this.view.element(i)).toString()); const elementsWithTrait = elements.map(e => pastElementsWithTrait.indexOf(this.identityProvider!.getId(e).toString()) > -1); this.trait.splice(start, deleteCount, elementsWithTrait); } } export function isInputElement(e: HTMLElement): boolean { return e.tagName === 'INPUT' || e.tagName === 'TEXTAREA'; } export function isMonacoEditor(e: HTMLElement): boolean { if (e.classList.contains('monaco-editor')) { return true; } if (e.classList.contains('monaco-list')) { return false; } if (!e.parentElement) { return false; } return isMonacoEditor(e.parentElement); } export function isButton(e: HTMLElement): boolean { if ((e.tagName === 'A' && e.classList.contains('monaco-button')) || (e.tagName === 'DIV' && e.classList.contains('monaco-button-dropdown'))) { return true; } if (e.classList.contains('monaco-list')) { return false; } if (!e.parentElement) { return false; } return isButton(e.parentElement); } class KeyboardController<T> implements IDisposable { private readonly disposables = new DisposableStore(); private readonly multipleSelectionDisposables = new DisposableStore(); @memoize private get onKeyDown(): Event.IChainableEvent<StandardKeyboardEvent> { return this.disposables.add(Event.chain(this.disposables.add(new DomEmitter(this.view.domNode, 'keydown')).event) .filter(e => !isInputElement(e.target as HTMLElement)) .map(e => new StandardKeyboardEvent(e))); } constructor( private list: List<T>, private view: ListView<T>, options: IListOptions<T> ) { this.onKeyDown.filter(e => e.keyCode === KeyCode.Enter).on(this.onEnter, this, this.disposables); this.onKeyDown.filter(e => e.keyCode === KeyCode.UpArrow).on(this.onUpArrow, this, this.disposables); this.onKeyDown.filter(e => e.keyCode === KeyCode.DownArrow).on(this.onDownArrow, this, this.disposables); this.onKeyDown.filter(e => e.keyCode === KeyCode.PageUp).on(this.onPageUpArrow, this, this.disposables); this.onKeyDown.filter(e => e.keyCode === KeyCode.PageDown).on(this.onPageDownArrow, this, this.disposables); this.onKeyDown.filter(e => e.keyCode === KeyCode.Escape).on(this.onEscape, this, this.disposables); if (options.multipleSelectionSupport !== false) { this.onKeyDown.filter(e => (platform.isMacintosh ? e.metaKey : e.ctrlKey) && e.keyCode === KeyCode.KeyA).on(this.onCtrlA, this, this.multipleSelectionDisposables); } } updateOptions(optionsUpdate: IListOptionsUpdate): void { if (optionsUpdate.multipleSelectionSupport !== undefined) { this.multipleSelectionDisposables.clear(); if (optionsUpdate.multipleSelectionSupport) { this.onKeyDown.filter(e => (platform.isMacintosh ? e.metaKey : e.ctrlKey) && e.keyCode === KeyCode.KeyA).on(this.onCtrlA, this, this.multipleSelectionDisposables); } } } private onEnter(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.setSelection(this.list.getFocus(), e.browserEvent); } private onUpArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusPrevious(1, false, e.browserEvent); const el = this.list.getFocus()[0]; this.list.setAnchor(el); this.list.reveal(el); this.view.domNode.focus(); } private onDownArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusNext(1, false, e.browserEvent); const el = this.list.getFocus()[0]; this.list.setAnchor(el); this.list.reveal(el); this.view.domNode.focus(); } private onPageUpArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusPreviousPage(e.browserEvent); const el = this.list.getFocus()[0]; this.list.setAnchor(el); this.list.reveal(el); this.view.domNode.focus(); } private onPageDownArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusNextPage(e.browserEvent); const el = this.list.getFocus()[0]; this.list.setAnchor(el); this.list.reveal(el); this.view.domNode.focus(); } private onCtrlA(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.setSelection(range(this.list.length), e.browserEvent); this.list.setAnchor(undefined); this.view.domNode.focus(); } private onEscape(e: StandardKeyboardEvent): void { if (this.list.getSelection().length) { e.preventDefault(); e.stopPropagation(); this.list.setSelection([], e.browserEvent); this.list.setAnchor(undefined); this.view.domNode.focus(); } } dispose() { this.disposables.dispose(); this.multipleSelectionDisposables.dispose(); } } export enum TypeNavigationMode { Automatic, Trigger } enum TypeNavigationControllerState { Idle, Typing } export const DefaultKeyboardNavigationDelegate = new class implements IKeyboardNavigationDelegate { mightProducePrintableCharacter(event: IKeyboardEvent): boolean { if (event.ctrlKey || event.metaKey || event.altKey) { return false; } return (event.keyCode >= KeyCode.KeyA && event.keyCode <= KeyCode.KeyZ) || (event.keyCode >= KeyCode.Digit0 && event.keyCode <= KeyCode.Digit9) || (event.keyCode >= KeyCode.Numpad0 && event.keyCode <= KeyCode.Numpad9) || (event.keyCode >= KeyCode.Semicolon && event.keyCode <= KeyCode.Quote); } }; class TypeNavigationController<T> implements IDisposable { private enabled = false; private state: TypeNavigationControllerState = TypeNavigationControllerState.Idle; private mode = TypeNavigationMode.Automatic; private triggered = false; private previouslyFocused = -1; private readonly enabledDisposables = new DisposableStore(); private readonly disposables = new DisposableStore(); constructor( private list: List<T>, private view: ListView<T>, private keyboardNavigationLabelProvider: IKeyboardNavigationLabelProvider<T>, private keyboardNavigationEventFilter: IKeyboardNavigationEventFilter, private delegate: IKeyboardNavigationDelegate ) { this.updateOptions(list.options); } updateOptions(options: IListOptions<T>): void { if (options.typeNavigationEnabled ?? true) { this.enable(); } else { this.disable(); } this.mode = options.typeNavigationMode ?? TypeNavigationMode.Automatic; } trigger(): void { this.triggered = !this.triggered; } private enable(): void { if (this.enabled) { return; } let typing = false; const onChar = this.enabledDisposables.add(Event.chain(this.enabledDisposables.add(new DomEmitter(this.view.domNode, 'keydown')).event)) .filter(e => !isInputElement(e.target as HTMLElement)) .filter(() => this.mode === TypeNavigationMode.Automatic || this.triggered) .map(event => new StandardKeyboardEvent(event)) .filter(e => typing || this.keyboardNavigationEventFilter(e)) .filter(e => this.delegate.mightProducePrintableCharacter(e)) .forEach(e => EventHelper.stop(e, true)) .map(event => event.browserEvent.key) .event; const onClear = Event.debounce<string, null>(onChar, () => null, 800, undefined, undefined, this.enabledDisposables); const onInput = Event.reduce<string | null, string | null>(Event.any(onChar, onClear), (r, i) => i === null ? null : ((r || '') + i), undefined, this.enabledDisposables); onInput(this.onInput, this, this.enabledDisposables); onClear(this.onClear, this, this.enabledDisposables); onChar(() => typing = true, undefined, this.enabledDisposables); onClear(() => typing = false, undefined, this.enabledDisposables); this.enabled = true; this.triggered = false; } private disable(): void { if (!this.enabled) { return; } this.enabledDisposables.clear(); this.enabled = false; this.triggered = false; } private onClear(): void { const focus = this.list.getFocus(); if (focus.length > 0 && focus[0] === this.previouslyFocused) { // List: re-announce element on typing end since typed keys will interrupt aria label of focused element // Do not announce if there was a focus change at the end to prevent duplication https://github.com/microsoft/vscode/issues/95961 const ariaLabel = this.list.options.accessibilityProvider?.getAriaLabel(this.list.element(focus[0])); if (ariaLabel) { alert(ariaLabel); } } this.previouslyFocused = -1; } private onInput(word: string | null): void { if (!word) { this.state = TypeNavigationControllerState.Idle; this.triggered = false; return; } const focus = this.list.getFocus(); const start = focus.length > 0 ? focus[0] : 0; const delta = this.state === TypeNavigationControllerState.Idle ? 1 : 0; this.state = TypeNavigationControllerState.Typing; for (let i = 0; i < this.list.length; i++) { const index = (start + i + delta) % this.list.length; const label = this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(this.view.element(index)); const labelStr = label && label.toString(); if (typeof labelStr === 'undefined' || matchesPrefix(word, labelStr)) { this.previouslyFocused = start; this.list.setFocus([index]); this.list.reveal(index); return; } } } dispose() { this.disable(); this.enabledDisposables.dispose(); this.disposables.dispose(); } } class DOMFocusController<T> implements IDisposable { private readonly disposables = new DisposableStore(); constructor( private list: List<T>, private view: ListView<T> ) { const onKeyDown = this.disposables.add(Event.chain(this.disposables.add(new DomEmitter(view.domNode, 'keydown')).event)) .filter(e => !isInputElement(e.target as HTMLElement)) .map(e => new StandardKeyboardEvent(e)); onKeyDown.filter(e => e.keyCode === KeyCode.Tab && !e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey) .on(this.onTab, this, this.disposables); } private onTab(e: StandardKeyboardEvent): void { if (e.target !== this.view.domNode) { return; } const focus = this.list.getFocus(); if (focus.length === 0) { return; } const focusedDomElement = this.view.domElement(focus[0]); if (!focusedDomElement) { return; } const tabIndexElement = focusedDomElement.querySelector('[tabIndex]'); if (!tabIndexElement || !(tabIndexElement instanceof HTMLElement) || tabIndexElement.tabIndex === -1) { return; } const style = window.getComputedStyle(tabIndexElement); if (style.visibility === 'hidden' || style.display === 'none') { return; } e.preventDefault(); e.stopPropagation(); tabIndexElement.focus(); } dispose() { this.disposables.dispose(); } } export function isSelectionSingleChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return platform.isMacintosh ? event.browserEvent.metaKey : event.browserEvent.ctrlKey; } export function isSelectionRangeChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return event.browserEvent.shiftKey; } function isMouseRightClick(event: UIEvent): boolean { return event instanceof MouseEvent && event.button === 2; } const DefaultMultipleSelectionController = { isSelectionSingleChangeEvent, isSelectionRangeChangeEvent }; export class MouseController<T> implements IDisposable { private multipleSelectionController: IMultipleSelectionController<T> | undefined; private mouseSupport: boolean; private readonly disposables = new DisposableStore(); private _onPointer = new Emitter<IListMouseEvent<T>>(); readonly onPointer: Event<IListMouseEvent<T>> = this._onPointer.event; constructor(protected list: List<T>) { if (list.options.multipleSelectionSupport !== false) { this.multipleSelectionController = this.list.options.multipleSelectionController || DefaultMultipleSelectionController; } this.mouseSupport = typeof list.options.mouseSupport === 'undefined' || !!list.options.mouseSupport; if (this.mouseSupport) { list.onMouseDown(this.onMouseDown, this, this.disposables); list.onContextMenu(this.onContextMenu, this, this.disposables); list.onMouseDblClick(this.onDoubleClick, this, this.disposables); list.onTouchStart(this.onMouseDown, this, this.disposables); this.disposables.add(Gesture.addTarget(list.getHTMLElement())); } Event.any(list.onMouseClick, list.onMouseMiddleClick, list.onTap)(this.onViewPointer, this, this.disposables); } updateOptions(optionsUpdate: IListOptionsUpdate): void { if (optionsUpdate.multipleSelectionSupport !== undefined) { this.multipleSelectionController = undefined; if (optionsUpdate.multipleSelectionSupport) { this.multipleSelectionController = this.list.options.multipleSelectionController || DefaultMultipleSelectionController; } } } protected isSelectionSingleChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { if (!this.multipleSelectionController) { return false; } return this.multipleSelectionController.isSelectionSingleChangeEvent(event); } protected isSelectionRangeChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { if (!this.multipleSelectionController) { return false; } return this.multipleSelectionController.isSelectionRangeChangeEvent(event); } private isSelectionChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return this.isSelectionSingleChangeEvent(event) || this.isSelectionRangeChangeEvent(event); } private onMouseDown(e: IListMouseEvent<T> | IListTouchEvent<T>): void { if (isMonacoEditor(e.browserEvent.target as HTMLElement)) { return; } if (document.activeElement !== e.browserEvent.target) { this.list.domFocus(); } } private onContextMenu(e: IListContextMenuEvent<T>): void { if (isInputElement(e.browserEvent.target as HTMLElement) || isMonacoEditor(e.browserEvent.target as HTMLElement)) { return; } const focus = typeof e.index === 'undefined' ? [] : [e.index]; this.list.setFocus(focus, e.browserEvent); } protected onViewPointer(e: IListMouseEvent<T>): void { if (!this.mouseSupport) { return; } if (isInputElement(e.browserEvent.target as HTMLElement) || isMonacoEditor(e.browserEvent.target as HTMLElement)) { return; } const focus = e.index; if (typeof focus === 'undefined') { this.list.setFocus([], e.browserEvent); this.list.setSelection([], e.browserEvent); this.list.setAnchor(undefined); return; } if (this.isSelectionRangeChangeEvent(e)) { return this.changeSelection(e); } if (this.isSelectionChangeEvent(e)) { return this.changeSelection(e); } this.list.setFocus([focus], e.browserEvent); this.list.setAnchor(focus); if (!isMouseRightClick(e.browserEvent)) { this.list.setSelection([focus], e.browserEvent); } this._onPointer.fire(e); } protected onDoubleClick(e: IListMouseEvent<T>): void { if (isInputElement(e.browserEvent.target as HTMLElement) || isMonacoEditor(e.browserEvent.target as HTMLElement)) { return; } if (this.isSelectionChangeEvent(e)) { return; } const focus = this.list.getFocus(); this.list.setSelection(focus, e.browserEvent); } private changeSelection(e: IListMouseEvent<T> | IListTouchEvent<T>): void { const focus = e.index!; let anchor = this.list.getAnchor(); if (this.isSelectionRangeChangeEvent(e)) { if (typeof anchor === 'undefined') { const currentFocus = this.list.getFocus()[0]; anchor = currentFocus ?? focus; this.list.setAnchor(anchor); } const min = Math.min(anchor, focus); const max = Math.max(anchor, focus); const rangeSelection = range(min, max + 1); const selection = this.list.getSelection(); const contiguousRange = getContiguousRangeContaining(disjunction(selection, [anchor]), anchor); if (contiguousRange.length === 0) { return; } const newSelection = disjunction(rangeSelection, relativeComplement(selection, contiguousRange)); this.list.setSelection(newSelection, e.browserEvent); this.list.setFocus([focus], e.browserEvent); } else if (this.isSelectionSingleChangeEvent(e)) { const selection = this.list.getSelection(); const newSelection = selection.filter(i => i !== focus); this.list.setFocus([focus]); this.list.setAnchor(focus); if (selection.length === newSelection.length) { this.list.setSelection([...newSelection, focus], e.browserEvent); } else { this.list.setSelection(newSelection, e.browserEvent); } } } dispose() { this.disposables.dispose(); } } export interface IMultipleSelectionController<T> { isSelectionSingleChangeEvent(event: IListMouseEvent<T> | IListTouchEvent<T>): boolean; isSelectionRangeChangeEvent(event: IListMouseEvent<T> | IListTouchEvent<T>): boolean; } export interface IStyleController { style(styles: IListStyles): void; } export interface IListAccessibilityProvider<T> extends IListViewAccessibilityProvider<T> { getAriaLabel(element: T): string | null; getWidgetAriaLabel(): string; getWidgetRole?(): AriaRole; getAriaLevel?(element: T): number | undefined; onDidChangeActiveDescendant?: Event<void>; getActiveDescendantId?(element: T): string | undefined; } export class DefaultStyleController implements IStyleController { constructor(private styleElement: HTMLStyleElement, private selectorSuffix: string) { } style(styles: IListStyles): void { const suffix = this.selectorSuffix && `.${this.selectorSuffix}`; const content: string[] = []; if (styles.listBackground) { if (styles.listBackground.isOpaque()) { content.push(`.monaco-list${suffix} .monaco-list-rows { background: ${styles.listBackground}; }`); } else if (!platform.isMacintosh) { // subpixel AA doesn't exist in macOS console.warn(`List with id '${this.selectorSuffix}' was styled with a non-opaque background color. This will break sub-pixel antialiasing.`); } } if (styles.listFocusBackground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { background-color: ${styles.listFocusBackground}; }`); content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused:hover { background-color: ${styles.listFocusBackground}; }`); // overwrite :hover style in this case! } if (styles.listFocusForeground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { color: ${styles.listFocusForeground}; }`); } if (styles.listActiveSelectionBackground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { background-color: ${styles.listActiveSelectionBackground}; }`); content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected:hover { background-color: ${styles.listActiveSelectionBackground}; }`); // overwrite :hover style in this case! } if (styles.listActiveSelectionForeground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { color: ${styles.listActiveSelectionForeground}; }`); } if (styles.listActiveSelectionIconForeground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected .codicon { color: ${styles.listActiveSelectionIconForeground}; }`); } if (styles.listFocusAndSelectionOutline) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { outline-color: ${styles.listFocusAndSelectionOutline} !important; }`); } if (styles.listFocusAndSelectionBackground) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.selected.focused { background-color: ${styles.listFocusAndSelectionBackground}; } `); } if (styles.listFocusAndSelectionForeground) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.selected.focused { color: ${styles.listFocusAndSelectionForeground}; } `); } if (styles.listInactiveFocusForeground) { content.push(`.monaco-list${suffix} .monaco-list-row.focused { color: ${styles.listInactiveFocusForeground}; }`); content.push(`.monaco-list${suffix} .monaco-list-row.focused:hover { color: ${styles.listInactiveFocusForeground}; }`); // overwrite :hover style in this case! } if (styles.listInactiveSelectionIconForeground) { content.push(`.monaco-list${suffix} .monaco-list-row.focused .codicon { color: ${styles.listInactiveSelectionIconForeground}; }`); } if (styles.listInactiveFocusBackground) { content.push(`.monaco-list${suffix} .monaco-list-row.focused { background-color: ${styles.listInactiveFocusBackground}; }`); content.push(`.monaco-list${suffix} .monaco-list-row.focused:hover { background-color: ${styles.listInactiveFocusBackground}; }`); // overwrite :hover style in this case! } if (styles.listInactiveSelectionBackground) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { background-color: ${styles.listInactiveSelectionBackground}; }`); content.push(`.monaco-list${suffix} .monaco-list-row.selected:hover { background-color: ${styles.listInactiveSelectionBackground}; }`); // overwrite :hover style in this case! } if (styles.listInactiveSelectionForeground) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { color: ${styles.listInactiveSelectionForeground}; }`); } if (styles.listHoverBackground) { content.push(`.monaco-list${suffix}:not(.drop-target):not(.dragging) .monaco-list-row:hover:not(.selected):not(.focused) { background-color: ${styles.listHoverBackground}; }`); } if (styles.listHoverForeground) { content.push(`.monaco-list${suffix}:not(.drop-target):not(.dragging) .monaco-list-row:hover:not(.selected):not(.focused) { color: ${styles.listHoverForeground}; }`); } if (styles.listSelectionOutline) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { outline: 1px dotted ${styles.listSelectionOutline}; outline-offset: -1px; }`); } if (styles.listFocusOutline) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; } .monaco-workbench.context-menu-visible .monaco-list${suffix}.last-focused .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; } `); } if (styles.listInactiveFocusOutline) { content.push(`.monaco-list${suffix} .monaco-list-row.focused { outline: 1px dotted ${styles.listInactiveFocusOutline}; outline-offset: -1px; }`); } if (styles.listHoverOutline) { content.push(`.monaco-list${suffix} .monaco-list-row:hover { outline: 1px dashed ${styles.listHoverOutline}; outline-offset: -1px; }`); } if (styles.listDropBackground) { content.push(` .monaco-list${suffix}.drop-target, .monaco-list${suffix} .monaco-list-rows.drop-target, .monaco-list${suffix} .monaco-list-row.drop-target { background-color: ${styles.listDropBackground} !important; color: inherit !important; } `); } if (styles.tableColumnsBorder) { content.push(` .monaco-table > .monaco-split-view2, .monaco-table > .monaco-split-view2 .monaco-sash.vertical::before, .monaco-workbench:not(.reduce-motion) .monaco-table:hover > .monaco-split-view2, .monaco-workbench:not(.reduce-motion) .monaco-table:hover > .monaco-split-view2 .monaco-sash.vertical::before { border-color: ${styles.tableColumnsBorder}; } .monaco-workbench:not(.reduce-motion) .monaco-table > .monaco-split-view2, .monaco-workbench:not(.reduce-motion) .monaco-table > .monaco-split-view2 .monaco-sash.vertical::before { border-color: transparent; } `); } if (styles.tableOddRowsBackgroundColor) { content.push(` .monaco-table .monaco-list-row[data-parity=odd]:not(.focused):not(.selected):not(:hover) .monaco-table-tr, .monaco-table .monaco-list:not(:focus) .monaco-list-row[data-parity=odd].focused:not(.selected):not(:hover) .monaco-table-tr, .monaco-table .monaco-list:not(.focused) .monaco-list-row[data-parity=odd].focused:not(.selected):not(:hover) .monaco-table-tr { background-color: ${styles.tableOddRowsBackgroundColor}; } `); } this.styleElement.textContent = content.join('\n'); } } export interface IKeyboardNavigationEventFilter { (e: StandardKeyboardEvent): boolean; } export interface IListOptionsUpdate extends IListViewOptionsUpdate { readonly typeNavigationEnabled?: boolean; readonly typeNavigationMode?: TypeNavigationMode; readonly multipleSelectionSupport?: boolean; } export interface IListOptions<T> extends IListOptionsUpdate { readonly identityProvider?: IIdentityProvider<T>; readonly dnd?: IListDragAndDrop<T>; readonly keyboardNavigationLabelProvider?: IKeyboardNavigationLabelProvider<T>; readonly keyboardNavigationDelegate?: IKeyboardNavigationDelegate; readonly keyboardSupport?: boolean; readonly multipleSelectionController?: IMultipleSelectionController<T>; readonly styleController?: (suffix: string) => IStyleController; readonly accessibilityProvider?: IListAccessibilityProvider<T>; readonly keyboardNavigationEventFilter?: IKeyboardNavigationEventFilter; // list view options readonly useShadows?: boolean; readonly verticalScrollMode?: ScrollbarVisibility; readonly setRowLineHeight?: boolean; readonly setRowHeight?: boolean; readonly supportDynamicHeights?: boolean; readonly mouseSupport?: boolean; readonly horizontalScrolling?: boolean; readonly scrollByPage?: boolean; readonly additionalScrollHeight?: number; readonly transformOptimization?: boolean; readonly smoothScrolling?: boolean; readonly scrollableElementChangeOptions?: ScrollableElementChangeOptions; readonly alwaysConsumeMouseWheel?: boolean; readonly initialSize?: Dimension; } export interface IListStyles { listBackground?: Color; listFocusBackground?: Color; listFocusForeground?: Color; listActiveSelectionBackground?: Color; listActiveSelectionForeground?: Color; listActiveSelectionIconForeground?: Color; listFocusAndSelectionOutline?: Color; listFocusAndSelectionBackground?: Color; listFocusAndSelectionForeground?: Color; listInactiveSelectionBackground?: Color; listInactiveSelectionIconForeground?: Color; listInactiveSelectionForeground?: Color; listInactiveFocusForeground?: Color; listInactiveFocusBackground?: Color; listHoverBackground?: Color; listHoverForeground?: Color; listDropBackground?: Color; listFocusOutline?: Color; listInactiveFocusOutline?: Color; listSelectionOutline?: Color; listHoverOutline?: Color; treeIndentGuidesStroke?: Color; tableColumnsBorder?: Color; tableOddRowsBackgroundColor?: Color; } const defaultStyles: IListStyles = { listFocusBackground: Color.fromHex('#7FB0D0'), listActiveSelectionBackground: Color.fromHex('#0E639C'), listActiveSelectionForeground: Color.fromHex('#FFFFFF'), listActiveSelectionIconForeground: Color.fromHex('#FFFFFF'), listFocusAndSelectionOutline: Color.fromHex('#90C2F9'), listFocusAndSelectionBackground: Color.fromHex('#094771'), listFocusAndSelectionForeground: Color.fromHex('#FFFFFF'), listInactiveSelectionBackground: Color.fromHex('#3F3F46'), listInactiveSelectionIconForeground: Color.fromHex('#FFFFFF'), listHoverBackground: Color.fromHex('#2A2D2E'), listDropBackground: Color.fromHex('#383B3D'), treeIndentGuidesStroke: Color.fromHex('#a9a9a9'), tableColumnsBorder: Color.fromHex('#cccccc').transparent(0.2), tableOddRowsBackgroundColor: Color.fromHex('#cccccc').transparent(0.04) }; const DefaultOptions: IListOptions<any> = { keyboardSupport: true, mouseSupport: true, multipleSelectionSupport: true, dnd: { getDragURI() { return null; }, onDragStart(): void { }, onDragOver() { return false; }, drop() { } } }; // TODO@Joao: move these utils into a SortedArray class function getContiguousRangeContaining(range: number[], value: number): number[] { const index = range.indexOf(value); if (index === -1) { return []; } const result: number[] = []; let i = index - 1; while (i >= 0 && range[i] === value - (index - i)) { result.push(range[i--]); } result.reverse(); i = index; while (i < range.length && range[i] === value + (i - index)) { result.push(range[i++]); } return result; } /** * Given two sorted collections of numbers, returns the intersection * between them (OR). */ function disjunction(one: number[], other: number[]): number[] { const result: number[] = []; let i = 0, j = 0; while (i < one.length || j < other.length) { if (i >= one.length) { result.push(other[j++]); } else if (j >= other.length) { result.push(one[i++]); } else if (one[i] === other[j]) { result.push(one[i]); i++; j++; continue; } else if (one[i] < other[j]) { result.push(one[i++]); } else { result.push(other[j++]); } } return result; } /** * Given two sorted collections of numbers, returns the relative * complement between them (XOR). */ function relativeComplement(one: number[], other: number[]): number[] { const result: number[] = []; let i = 0, j = 0; while (i < one.length || j < other.length) { if (i >= one.length) { result.push(other[j++]); } else if (j >= other.length) { result.push(one[i++]); } else if (one[i] === other[j]) { i++; j++; continue; } else if (one[i] < other[j]) { result.push(one[i++]); } else { j++; } } return result; } const numericSort = (a: number, b: number) => a - b; class PipelineRenderer<T> implements IListRenderer<T, any> { constructor( private _templateId: string, private renderers: IListRenderer<any /* TODO@joao */, any>[] ) { } get templateId(): string { return this._templateId; } renderTemplate(container: HTMLElement): any[] { return this.renderers.map(r => r.renderTemplate(container)); } renderElement(element: T, index: number, templateData: any[], height: number | undefined): void { let i = 0; for (const renderer of this.renderers) { renderer.renderElement(element, index, templateData[i++], height); } } disposeElement(element: T, index: number, templateData: any[], height: number | undefined): void { let i = 0; for (const renderer of this.renderers) { renderer.disposeElement?.(element, index, templateData[i], height); i += 1; } } disposeTemplate(templateData: any[]): void { let i = 0; for (const renderer of this.renderers) { renderer.disposeTemplate(templateData[i++]); } } } class AccessibiltyRenderer<T> implements IListRenderer<T, HTMLElement> { templateId: string = 'a18n'; constructor(private accessibilityProvider: IListAccessibilityProvider<T>) { } renderTemplate(container: HTMLElement): HTMLElement { return container; } renderElement(element: T, index: number, container: HTMLElement): void { const ariaLabel = this.accessibilityProvider.getAriaLabel(element); if (ariaLabel) { container.setAttribute('aria-label', ariaLabel); } else { container.removeAttribute('aria-label'); } const ariaLevel = this.accessibilityProvider.getAriaLevel && this.accessibilityProvider.getAriaLevel(element); if (typeof ariaLevel === 'number') { container.setAttribute('aria-level', `${ariaLevel}`); } else { container.removeAttribute('aria-level'); } } disposeTemplate(templateData: any): void { // noop } } class ListViewDragAndDrop<T> implements IListViewDragAndDrop<T> { constructor(private list: List<T>, private dnd: IListDragAndDrop<T>) { } getDragElements(element: T): T[] { const selection = this.list.getSelectedElements(); const elements = selection.indexOf(element) > -1 ? selection : [element]; return elements; } getDragURI(element: T): string | null { return this.dnd.getDragURI(element); } getDragLabel?(elements: T[], originalEvent: DragEvent): string | undefined { if (this.dnd.getDragLabel) { return this.dnd.getDragLabel(elements, originalEvent); } return undefined; } onDragStart(data: IDragAndDropData, originalEvent: DragEvent): void { this.dnd.onDragStart?.(data, originalEvent); } onDragOver(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): boolean | IListDragOverReaction { return this.dnd.onDragOver(data, targetElement, targetIndex, originalEvent); } onDragLeave(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): void { this.dnd.onDragLeave?.(data, targetElement, targetIndex, originalEvent); } onDragEnd(originalEvent: DragEvent): void { this.dnd.onDragEnd?.(originalEvent); } drop(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): void { this.dnd.drop(data, targetElement, targetIndex, originalEvent); } } /** * The {@link List} is a virtual scrolling widget, built on top of the {@link ListView} * widget. * * Features: * - Customizable keyboard and mouse support * - Element traits: focus, selection, achor * - Accessibility support * - Touch support * - Performant template-based rendering * - Horizontal scrolling * - Variable element height support * - Dynamic element height support * - Drag-and-drop support */ export class List<T> implements ISpliceable<T>, IThemable, IDisposable { private focus = new Trait<T>('focused'); private selection: Trait<T>; private anchor = new Trait<T>('anchor'); private eventBufferer = new EventBufferer(); protected view: ListView<T>; private spliceable: ISpliceable<T>; private styleController: IStyleController; private typeNavigationController?: TypeNavigationController<T>; private accessibilityProvider?: IListAccessibilityProvider<T>; private keyboardController: KeyboardController<T> | undefined; private mouseController: MouseController<T>; private _ariaLabel: string = ''; protected readonly disposables = new DisposableStore(); @memoize get onDidChangeFocus(): Event<IListEvent<T>> { return Event.map(this.eventBufferer.wrapEvent(this.focus.onChange), e => this.toListEvent(e), this.disposables); } @memoize get onDidChangeSelection(): Event<IListEvent<T>> { return Event.map(this.eventBufferer.wrapEvent(this.selection.onChange), e => this.toListEvent(e), this.disposables); } get domId(): string { return this.view.domId; } get onDidScroll(): Event<ScrollEvent> { return this.view.onDidScroll; } get onMouseClick(): Event<IListMouseEvent<T>> { return this.view.onMouseClick; } get onMouseDblClick(): Event<IListMouseEvent<T>> { return this.view.onMouseDblClick; } get onMouseMiddleClick(): Event<IListMouseEvent<T>> { return this.view.onMouseMiddleClick; } get onPointer(): Event<IListMouseEvent<T>> { return this.mouseController.onPointer; } get onMouseUp(): Event<IListMouseEvent<T>> { return this.view.onMouseUp; } get onMouseDown(): Event<IListMouseEvent<T>> { return this.view.onMouseDown; } get onMouseOver(): Event<IListMouseEvent<T>> { return this.view.onMouseOver; } get onMouseMove(): Event<IListMouseEvent<T>> { return this.view.onMouseMove; } get onMouseOut(): Event<IListMouseEvent<T>> { return this.view.onMouseOut; } get onTouchStart(): Event<IListTouchEvent<T>> { return this.view.onTouchStart; } get onTap(): Event<IListGestureEvent<T>> { return this.view.onTap; } /** * Possible context menu trigger events: * - ContextMenu key * - Shift F10 * - Ctrl Option Shift M (macOS with VoiceOver) * - Mouse right click */ @memoize get onContextMenu(): Event<IListContextMenuEvent<T>> { let didJustPressContextMenuKey = false; const fromKeyDown = this.disposables.add(Event.chain(this.disposables.add(new DomEmitter(this.view.domNode, 'keydown')).event)) .map(e => new StandardKeyboardEvent(e)) .filter(e => didJustPressContextMenuKey = e.keyCode === KeyCode.ContextMenu || (e.shiftKey && e.keyCode === KeyCode.F10)) .map(e => EventHelper.stop(e, true)) .filter(() => false) .event as Event<any>; const fromKeyUp = this.disposables.add(Event.chain(this.disposables.add(new DomEmitter(this.view.domNode, 'keyup')).event)) .forEach(() => didJustPressContextMenuKey = false) .map(e => new StandardKeyboardEvent(e)) .filter(e => e.keyCode === KeyCode.ContextMenu || (e.shiftKey && e.keyCode === KeyCode.F10)) .map(e => EventHelper.stop(e, true)) .map(({ browserEvent }) => { const focus = this.getFocus(); const index = focus.length ? focus[0] : undefined; const element = typeof index !== 'undefined' ? this.view.element(index) : undefined; const anchor = typeof index !== 'undefined' ? this.view.domElement(index) as HTMLElement : this.view.domNode; return { index, element, anchor, browserEvent }; }) .event; const fromMouse = this.disposables.add(Event.chain(this.view.onContextMenu)) .filter(_ => !didJustPressContextMenuKey) .map(({ element, index, browserEvent }) => ({ element, index, anchor: { x: browserEvent.pageX + 1, y: browserEvent.pageY }, browserEvent })) .event; return Event.any<IListContextMenuEvent<T>>(fromKeyDown, fromKeyUp, fromMouse); } @memoize get onKeyDown(): Event<KeyboardEvent> { return this.disposables.add(new DomEmitter(this.view.domNode, 'keydown')).event; } @memoize get onKeyUp(): Event<KeyboardEvent> { return this.disposables.add(new DomEmitter(this.view.domNode, 'keyup')).event; } @memoize get onKeyPress(): Event<KeyboardEvent> { return this.disposables.add(new DomEmitter(this.view.domNode, 'keypress')).event; } @memoize get onDidFocus(): Event<void> { return Event.signal(this.disposables.add(new DomEmitter(this.view.domNode, 'focus', true)).event); } @memoize get onDidBlur(): Event<void> { return Event.signal(this.disposables.add(new DomEmitter(this.view.domNode, 'blur', true)).event); } private readonly _onDidDispose = new Emitter<void>(); readonly onDidDispose: Event<void> = this._onDidDispose.event; constructor( private user: string, container: HTMLElement, virtualDelegate: IListVirtualDelegate<T>, renderers: IListRenderer<any /* TODO@joao */, any>[], private _options: IListOptions<T> = DefaultOptions ) { const role = this._options.accessibilityProvider && this._options.accessibilityProvider.getWidgetRole ? this._options.accessibilityProvider?.getWidgetRole() : 'list'; this.selection = new SelectionTrait(role !== 'listbox'); mixin(_options, defaultStyles, false); const baseRenderers: IListRenderer<T, ITraitTemplateData>[] = [this.focus.renderer, this.selection.renderer]; this.accessibilityProvider = _options.accessibilityProvider; if (this.accessibilityProvider) { baseRenderers.push(new AccessibiltyRenderer<T>(this.accessibilityProvider)); this.accessibilityProvider.onDidChangeActiveDescendant?.(this.onDidChangeActiveDescendant, this, this.disposables); } renderers = renderers.map(r => new PipelineRenderer(r.templateId, [...baseRenderers, r])); const viewOptions: IListViewOptions<T> = { ..._options, dnd: _options.dnd && new ListViewDragAndDrop(this, _options.dnd) }; this.view = new ListView(container, virtualDelegate, renderers, viewOptions); this.view.domNode.setAttribute('role', role); if (_options.styleController) { this.styleController = _options.styleController(this.view.domId); } else { const styleElement = createStyleSheet(this.view.domNode); this.styleController = new DefaultStyleController(styleElement, this.view.domId); } this.spliceable = new CombinedSpliceable([ new TraitSpliceable(this.focus, this.view, _options.identityProvider), new TraitSpliceable(this.selection, this.view, _options.identityProvider), new TraitSpliceable(this.anchor, this.view, _options.identityProvider), this.view ]); this.disposables.add(this.focus); this.disposables.add(this.selection); this.disposables.add(this.anchor); this.disposables.add(this.view); this.disposables.add(this._onDidDispose); this.disposables.add(new DOMFocusController(this, this.view)); if (typeof _options.keyboardSupport !== 'boolean' || _options.keyboardSupport) { this.keyboardController = new KeyboardController(this, this.view, _options); this.disposables.add(this.keyboardController); } if (_options.keyboardNavigationLabelProvider) { const delegate = _options.keyboardNavigationDelegate || DefaultKeyboardNavigationDelegate; this.typeNavigationController = new TypeNavigationController(this, this.view, _options.keyboardNavigationLabelProvider, _options.keyboardNavigationEventFilter ?? (() => true), delegate); this.disposables.add(this.typeNavigationController); } this.mouseController = this.createMouseController(_options); this.disposables.add(this.mouseController); this.onDidChangeFocus(this._onFocusChange, this, this.disposables); this.onDidChangeSelection(this._onSelectionChange, this, this.disposables); if (this.accessibilityProvider) { this.ariaLabel = this.accessibilityProvider.getWidgetAriaLabel(); } if (this._options.multipleSelectionSupport !== false) { this.view.domNode.setAttribute('aria-multiselectable', 'true'); } } protected createMouseController(options: IListOptions<T>): MouseController<T> { return new MouseController(this); } updateOptions(optionsUpdate: IListOptionsUpdate = {}): void { this._options = { ...this._options, ...optionsUpdate }; this.typeNavigationController?.updateOptions(this._options); if (this._options.multipleSelectionController !== undefined) { if (this._options.multipleSelectionSupport) { this.view.domNode.setAttribute('aria-multiselectable', 'true'); } else { this.view.domNode.removeAttribute('aria-multiselectable'); } } this.mouseController.updateOptions(optionsUpdate); this.keyboardController?.updateOptions(optionsUpdate); this.view.updateOptions(optionsUpdate); } get options(): IListOptions<T> { return this._options; } splice(start: number, deleteCount: number, elements: readonly T[] = []): void { if (start < 0 || start > this.view.length) { throw new ListError(this.user, `Invalid start index: ${start}`); } if (deleteCount < 0) { throw new ListError(this.user, `Invalid delete count: ${deleteCount}`); } if (deleteCount === 0 && elements.length === 0) { return; } this.eventBufferer.bufferEvents(() => this.spliceable.splice(start, deleteCount, elements)); } updateWidth(index: number): void { this.view.updateWidth(index); } updateElementHeight(index: number, size: number): void { this.view.updateElementHeight(index, size, null); } rerender(): void { this.view.rerender(); } element(index: number): T { return this.view.element(index); } indexOf(element: T): number { return this.view.indexOf(element); } get length(): number { return this.view.length; } get contentHeight(): number { return this.view.contentHeight; } get onDidChangeContentHeight(): Event<number> { return this.view.onDidChangeContentHeight; } get scrollTop(): number { return this.view.getScrollTop(); } set scrollTop(scrollTop: number) { this.view.setScrollTop(scrollTop); } get scrollLeft(): number { return this.view.getScrollLeft(); } set scrollLeft(scrollLeft: number) { this.view.setScrollLeft(scrollLeft); } get scrollHeight(): number { return this.view.scrollHeight; } get renderHeight(): number { return this.view.renderHeight; } get firstVisibleIndex(): number { return this.view.firstVisibleIndex; } get lastVisibleIndex(): number { return this.view.lastVisibleIndex; } get ariaLabel(): string { return this._ariaLabel; } set ariaLabel(value: string) { this._ariaLabel = value; this.view.domNode.setAttribute('aria-label', value); } domFocus(): void { this.view.domNode.focus({ preventScroll: true }); } layout(height?: number, width?: number): void { this.view.layout(height, width); } triggerTypeNavigation(): void { this.typeNavigationController?.trigger(); } setSelection(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this.selection.set(indexes, browserEvent); } getSelection(): number[] { return this.selection.get(); } getSelectedElements(): T[] { return this.getSelection().map(i => this.view.element(i)); } setAnchor(index: number | undefined): void { if (typeof index === 'undefined') { this.anchor.set([]); return; } if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } this.anchor.set([index]); } getAnchor(): number | undefined { return firstOrDefault(this.anchor.get(), undefined); } getAnchorElement(): T | undefined { const anchor = this.getAnchor(); return typeof anchor === 'undefined' ? undefined : this.element(anchor); } setFocus(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this.focus.set(indexes, browserEvent); } focusNext(n = 1, loop = false, browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const focus = this.focus.get(); const index = this.findNextIndex(focus.length > 0 ? focus[0] + n : 0, loop, filter); if (index > -1) { this.setFocus([index], browserEvent); } } focusPrevious(n = 1, loop = false, browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const focus = this.focus.get(); const index = this.findPreviousIndex(focus.length > 0 ? focus[0] - n : 0, loop, filter); if (index > -1) { this.setFocus([index], browserEvent); } } async focusNextPage(browserEvent?: UIEvent, filter?: (element: T) => boolean): Promise<void> { let lastPageIndex = this.view.indexAt(this.view.getScrollTop() + this.view.renderHeight); lastPageIndex = lastPageIndex === 0 ? 0 : lastPageIndex - 1; const currentlyFocusedElementIndex = this.getFocus()[0]; if (currentlyFocusedElementIndex !== lastPageIndex && (currentlyFocusedElementIndex === undefined || lastPageIndex > currentlyFocusedElementIndex)) { const lastGoodPageIndex = this.findPreviousIndex(lastPageIndex, false, filter); if (lastGoodPageIndex > -1 && currentlyFocusedElementIndex !== lastGoodPageIndex) { this.setFocus([lastGoodPageIndex], browserEvent); } else { this.setFocus([lastPageIndex], browserEvent); } } else { const previousScrollTop = this.view.getScrollTop(); let nextpageScrollTop = previousScrollTop + this.view.renderHeight; if (lastPageIndex > currentlyFocusedElementIndex) { // scroll last page element to the top only if the last page element is below the focused element nextpageScrollTop -= this.view.elementHeight(lastPageIndex); } this.view.setScrollTop(nextpageScrollTop); if (this.view.getScrollTop() !== previousScrollTop) { this.setFocus([]); // Let the scroll event listener run await timeout(0); await this.focusNextPage(browserEvent, filter); } } } async focusPreviousPage(browserEvent?: UIEvent, filter?: (element: T) => boolean): Promise<void> { let firstPageIndex: number; const scrollTop = this.view.getScrollTop(); if (scrollTop === 0) { firstPageIndex = this.view.indexAt(scrollTop); } else { firstPageIndex = this.view.indexAfter(scrollTop - 1); } const currentlyFocusedElementIndex = this.getFocus()[0]; if (currentlyFocusedElementIndex !== firstPageIndex && (currentlyFocusedElementIndex === undefined || currentlyFocusedElementIndex >= firstPageIndex)) { const firstGoodPageIndex = this.findNextIndex(firstPageIndex, false, filter); if (firstGoodPageIndex > -1 && currentlyFocusedElementIndex !== firstGoodPageIndex) { this.setFocus([firstGoodPageIndex], browserEvent); } else { this.setFocus([firstPageIndex], browserEvent); } } else { const previousScrollTop = scrollTop; this.view.setScrollTop(scrollTop - this.view.renderHeight); if (this.view.getScrollTop() !== previousScrollTop) { this.setFocus([]); // Let the scroll event listener run await timeout(0); await this.focusPreviousPage(browserEvent, filter); } } } focusLast(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const index = this.findPreviousIndex(this.length - 1, false, filter); if (index > -1) { this.setFocus([index], browserEvent); } } focusFirst(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { this.focusNth(0, browserEvent, filter); } focusNth(n: number, browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const index = this.findNextIndex(n, false, filter); if (index > -1) { this.setFocus([index], browserEvent); } } private findNextIndex(index: number, loop = false, filter?: (element: T) => boolean): number { for (let i = 0; i < this.length; i++) { if (index >= this.length && !loop) { return -1; } index = index % this.length; if (!filter || filter(this.element(index))) { return index; } index++; } return -1; } private findPreviousIndex(index: number, loop = false, filter?: (element: T) => boolean): number { for (let i = 0; i < this.length; i++) { if (index < 0 && !loop) { return -1; } index = (this.length + (index % this.length)) % this.length; if (!filter || filter(this.element(index))) { return index; } index--; } return -1; } getFocus(): number[] { return this.focus.get(); } getFocusedElements(): T[] { return this.getFocus().map(i => this.view.element(i)); } reveal(index: number, relativeTop?: number): void { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } const scrollTop = this.view.getScrollTop(); const elementTop = this.view.elementTop(index); const elementHeight = this.view.elementHeight(index); if (isNumber(relativeTop)) { // y = mx + b const m = elementHeight - this.view.renderHeight; this.view.setScrollTop(m * clamp(relativeTop, 0, 1) + elementTop); } else { const viewItemBottom = elementTop + elementHeight; const scrollBottom = scrollTop + this.view.renderHeight; if (elementTop < scrollTop && viewItemBottom >= scrollBottom) { // The element is already overflowing the viewport, no-op } else if (elementTop < scrollTop || (viewItemBottom >= scrollBottom && elementHeight >= this.view.renderHeight)) { this.view.setScrollTop(elementTop); } else if (viewItemBottom >= scrollBottom) { this.view.setScrollTop(viewItemBottom - this.view.renderHeight); } } } /** * Returns the relative position of an element rendered in the list. * Returns `null` if the element isn't *entirely* in the visible viewport. */ getRelativeTop(index: number): number | null { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } const scrollTop = this.view.getScrollTop(); const elementTop = this.view.elementTop(index); const elementHeight = this.view.elementHeight(index); if (elementTop < scrollTop || elementTop + elementHeight > scrollTop + this.view.renderHeight) { return null; } // y = mx + b const m = elementHeight - this.view.renderHeight; return Math.abs((scrollTop - elementTop) / m); } isDOMFocused(): boolean { return this.view.domNode === document.activeElement; } getHTMLElement(): HTMLElement { return this.view.domNode; } getElementID(index: number): string { return this.view.getElementDomId(index); } style(styles: IListStyles): void { this.styleController.style(styles); } private toListEvent({ indexes, browserEvent }: ITraitChangeEvent) { return { indexes, elements: indexes.map(i => this.view.element(i)), browserEvent }; } private _onFocusChange(): void { const focus = this.focus.get(); this.view.domNode.classList.toggle('element-focused', focus.length > 0); this.onDidChangeActiveDescendant(); } private onDidChangeActiveDescendant(): void { const focus = this.focus.get(); if (focus.length > 0) { let id: string | undefined; if (this.accessibilityProvider?.getActiveDescendantId) { id = this.accessibilityProvider.getActiveDescendantId(this.view.element(focus[0])); } this.view.domNode.setAttribute('aria-activedescendant', id || this.view.getElementDomId(focus[0])); } else { this.view.domNode.removeAttribute('aria-activedescendant'); } } private _onSelectionChange(): void { const selection = this.selection.get(); this.view.domNode.classList.toggle('selection-none', selection.length === 0); this.view.domNode.classList.toggle('selection-single', selection.length === 1); this.view.domNode.classList.toggle('selection-multiple', selection.length > 1); } dispose(): void { this._onDidDispose.fire(); this.disposables.dispose(); this._onDidDispose.dispose(); } }
src/vs/base/browser/ui/list/listWidget.ts
1
https://github.com/microsoft/vscode/commit/f078e6db483250957314c56c3b12e23dae03d351
[ 0.998786985874176, 0.05568461865186691, 0.000162241849466227, 0.0002112526271957904, 0.20480720698833466 ]
{ "id": 1, "code_window": [ "\n", "\t\tif (!isMouseRightClick(e.browserEvent)) {\n", "\t\t\tthis.list.setSelection([focus], e.browserEvent);\n", "\t\t}\n", "\n", "\t\tthis._onPointer.fire(e);\n", "\t}\n", "\n", "\tprotected onDoubleClick(e: IListMouseEvent<T>): void {\n", "\t\tif (isInputElement(e.browserEvent.target as HTMLElement) || isMonacoEditor(e.browserEvent.target as HTMLElement)) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\te.browserEvent.preventDefault();\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "add", "edit_start_line_idx": 711 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // @ts-check "use strict"; (function () { // @ts-ignore const vscode = acquireVsCodeApi(); function getSettings() { const element = document.getElementById('settings'); if (element) { const data = element.getAttribute('data-settings'); if (data) { return JSON.parse(data); } } throw new Error(`Could not load settings`); } const settings = getSettings(); // State let hasLoadedMedia = false; // Elements const video = document.createElement('video'); if (settings.src !== null) { video.src = settings.src; } video.playsInline = true; video.controls = true; function onLoaded() { if (hasLoadedMedia) { return; } hasLoadedMedia = true; document.body.classList.remove('loading'); document.body.classList.add('ready'); document.body.append(video); } video.addEventListener('error', e => { if (hasLoadedMedia) { return; } hasLoadedMedia = true; document.body.classList.add('error'); document.body.classList.remove('loading'); }); if (settings.src === null) { onLoaded(); } else { video.addEventListener('canplaythrough', () => { onLoaded(); }); } document.querySelector('.open-file-link')?.addEventListener('click', (e) => { e.preventDefault(); vscode.postMessage({ type: 'reopen-as-text', }); }); }());
extensions/media-preview/media/videoPreview.js
0
https://github.com/microsoft/vscode/commit/f078e6db483250957314c56c3b12e23dae03d351
[ 0.0001719175634207204, 0.00016872212290763855, 0.00016738151316531003, 0.00016805031918920577, 0.0000014161810213408899 ]
{ "id": 1, "code_window": [ "\n", "\t\tif (!isMouseRightClick(e.browserEvent)) {\n", "\t\t\tthis.list.setSelection([focus], e.browserEvent);\n", "\t\t}\n", "\n", "\t\tthis._onPointer.fire(e);\n", "\t}\n", "\n", "\tprotected onDoubleClick(e: IListMouseEvent<T>): void {\n", "\t\tif (isInputElement(e.browserEvent.target as HTMLElement) || isMonacoEditor(e.browserEvent.target as HTMLElement)) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\te.browserEvent.preventDefault();\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "add", "edit_start_line_idx": 711 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { EXTENSION_IDENTIFIER_PATTERN, IExtensionGalleryService } from 'vs/platform/extensionManagement/common/extensionManagement'; import { distinct, flatten } from 'vs/base/common/arrays'; import { ExtensionRecommendations, ExtensionRecommendation } from 'vs/workbench/contrib/extensions/browser/extensionRecommendations'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { ExtensionRecommendationReason } from 'vs/workbench/services/extensionRecommendations/common/extensionRecommendations'; import { ILogService } from 'vs/platform/log/common/log'; import { CancellationToken } from 'vs/base/common/cancellation'; import { localize } from 'vs/nls'; import { Emitter } from 'vs/base/common/event'; import { IExtensionsConfigContent, IWorkspaceExtensionsConfigService } from 'vs/workbench/services/extensionRecommendations/common/workspaceExtensionsConfig'; export class WorkspaceRecommendations extends ExtensionRecommendations { private _recommendations: ExtensionRecommendation[] = []; get recommendations(): ReadonlyArray<ExtensionRecommendation> { return this._recommendations; } private _onDidChangeRecommendations = this._register(new Emitter<void>()); readonly onDidChangeRecommendations = this._onDidChangeRecommendations.event; private _ignoredRecommendations: string[] = []; get ignoredRecommendations(): ReadonlyArray<string> { return this._ignoredRecommendations; } constructor( @IWorkspaceExtensionsConfigService private readonly workspaceExtensionsConfigService: IWorkspaceExtensionsConfigService, @IExtensionGalleryService private readonly galleryService: IExtensionGalleryService, @ILogService private readonly logService: ILogService, @INotificationService private readonly notificationService: INotificationService, ) { super(); } protected async doActivate(): Promise<void> { await this.fetch(); this._register(this.workspaceExtensionsConfigService.onDidChangeExtensionsConfigs(() => this.onDidChangeExtensionsConfigs())); } /** * Parse all extensions.json files, fetch workspace recommendations, filter out invalid and unwanted ones */ private async fetch(): Promise<void> { const extensionsConfigs = await this.workspaceExtensionsConfigService.getExtensionsConfigs(); const { invalidRecommendations, message } = await this.validateExtensions(extensionsConfigs); if (invalidRecommendations.length) { this.notificationService.warn(`The ${invalidRecommendations.length} extension(s) below, in workspace recommendations have issues:\n${message}`); } this._recommendations = []; this._ignoredRecommendations = []; for (const extensionsConfig of extensionsConfigs) { if (extensionsConfig.unwantedRecommendations) { for (const unwantedRecommendation of extensionsConfig.unwantedRecommendations) { if (invalidRecommendations.indexOf(unwantedRecommendation) === -1) { this._ignoredRecommendations.push(unwantedRecommendation); } } } if (extensionsConfig.recommendations) { for (const extensionId of extensionsConfig.recommendations) { if (invalidRecommendations.indexOf(extensionId) === -1) { this._recommendations.push({ extensionId, reason: { reasonId: ExtensionRecommendationReason.Workspace, reasonText: localize('workspaceRecommendation', "This extension is recommended by users of the current workspace.") } }); } } } } } private async validateExtensions(contents: IExtensionsConfigContent[]): Promise<{ validRecommendations: string[]; invalidRecommendations: string[]; message: string }> { const validExtensions: string[] = []; const invalidExtensions: string[] = []; const extensionsToQuery: string[] = []; let message = ''; const allRecommendations = distinct(flatten(contents.map(({ recommendations }) => recommendations || []))); const regEx = new RegExp(EXTENSION_IDENTIFIER_PATTERN); for (const extensionId of allRecommendations) { if (regEx.test(extensionId)) { extensionsToQuery.push(extensionId); } else { invalidExtensions.push(extensionId); message += `${extensionId} (bad format) Expected: <provider>.<name>\n`; } } if (extensionsToQuery.length) { try { const galleryExtensions = await this.galleryService.getExtensions(extensionsToQuery.map(id => ({ id })), CancellationToken.None); const extensions = galleryExtensions.map(extension => extension.identifier.id.toLowerCase()); for (const extensionId of extensionsToQuery) { if (extensions.indexOf(extensionId) === -1) { invalidExtensions.push(extensionId); message += `${extensionId} (not found in marketplace)\n`; } else { validExtensions.push(extensionId); } } } catch (e) { this.logService.warn('Error querying extensions gallery', e); } } return { validRecommendations: validExtensions, invalidRecommendations: invalidExtensions, message }; } private async onDidChangeExtensionsConfigs(): Promise<void> { await this.fetch(); this._onDidChangeRecommendations.fire(); } }
src/vs/workbench/contrib/extensions/browser/workspaceRecommendations.ts
0
https://github.com/microsoft/vscode/commit/f078e6db483250957314c56c3b12e23dae03d351
[ 0.00022141110093798488, 0.00017351729911752045, 0.00016564833640586585, 0.00017035008931998163, 0.000013998652320879046 ]
{ "id": 1, "code_window": [ "\n", "\t\tif (!isMouseRightClick(e.browserEvent)) {\n", "\t\t\tthis.list.setSelection([focus], e.browserEvent);\n", "\t\t}\n", "\n", "\t\tthis._onPointer.fire(e);\n", "\t}\n", "\n", "\tprotected onDoubleClick(e: IListMouseEvent<T>): void {\n", "\t\tif (isInputElement(e.browserEvent.target as HTMLElement) || isMonacoEditor(e.browserEvent.target as HTMLElement)) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\te.browserEvent.preventDefault();\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "add", "edit_start_line_idx": 711 }
[ { "c": "% a sample bibliography file", "t": "text.bibtex comment.block.bibtex", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668", "dark_plus_experimental": "comment: #6A9955", "hc_light": "comment: #515151", "light_plus_experimental": "comment: #008000" } }, { "c": "%", "t": "text.bibtex comment.block.bibtex", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668", "dark_plus_experimental": "comment: #6A9955", "hc_light": "comment: #515151", "light_plus_experimental": "comment: #008000" } }, { "c": "@", "t": "text.bibtex meta.entry.braces.bibtex keyword.other.entry-type.bibtex punctuation.definition.keyword.bibtex", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6", "dark_plus_experimental": "keyword: #569CD6", "hc_light": "keyword: #0F4A85", "light_plus_experimental": "keyword: #0000FF" } }, { "c": "article", "t": "text.bibtex meta.entry.braces.bibtex keyword.other.entry-type.bibtex", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6", "dark_plus_experimental": "keyword: #569CD6", "hc_light": "keyword: #0F4A85", "light_plus_experimental": "keyword: #0000FF" } }, { "c": "{", "t": "text.bibtex meta.entry.braces.bibtex punctuation.section.entry.begin.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "small", "t": "text.bibtex meta.entry.braces.bibtex entity.name.type.entry-key.bibtex", "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", "dark_plus_experimental": "entity.name.type: #4EC9B0", "hc_light": "entity.name.type: #185E73", "light_plus_experimental": "entity.name.type: #267F99" } }, { "c": ",", "t": "text.bibtex meta.entry.braces.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "author", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex support.function.key.bibtex", "r": { "dark_plus": "support.function: #DCDCAA", "light_plus": "support.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.function: #DCDCAA", "dark_plus_experimental": "support.function: #DCDCAA", "hc_light": "support.function: #5E2CBC", "light_plus_experimental": "support.function: #795E26" } }, { "c": " ", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "=", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.separator.key-value.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": " ", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "{", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.definition.string.begin.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "Freely, I.P.", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "}", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.definition.string.end.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": ",", "t": "text.bibtex meta.entry.braces.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "title", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex support.function.key.bibtex", "r": { "dark_plus": "support.function: #DCDCAA", "light_plus": "support.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.function: #DCDCAA", "dark_plus_experimental": "support.function: #DCDCAA", "hc_light": "support.function: #5E2CBC", "light_plus_experimental": "support.function: #795E26" } }, { "c": " ", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "=", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.separator.key-value.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": " ", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "{", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.definition.string.begin.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "A small paper", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "}", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.definition.string.end.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": ",", "t": "text.bibtex meta.entry.braces.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "journal", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex support.function.key.bibtex", "r": { "dark_plus": "support.function: #DCDCAA", "light_plus": "support.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.function: #DCDCAA", "dark_plus_experimental": "support.function: #DCDCAA", "hc_light": "support.function: #5E2CBC", "light_plus_experimental": "support.function: #795E26" } }, { "c": " ", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "=", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.separator.key-value.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": " ", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "{", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.definition.string.begin.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "The journal of small papers", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "}", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.definition.string.end.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": ",", "t": "text.bibtex meta.entry.braces.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "year", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex support.function.key.bibtex", "r": { "dark_plus": "support.function: #DCDCAA", "light_plus": "support.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.function: #DCDCAA", "dark_plus_experimental": "support.function: #DCDCAA", "hc_light": "support.function: #5E2CBC", "light_plus_experimental": "support.function: #795E26" } }, { "c": " ", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "=", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.separator.key-value.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": " ", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "1997", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex constant.numeric.bibtex", "r": { "dark_plus": "constant.numeric: #B5CEA8", "light_plus": "constant.numeric: #098658", "dark_vs": "constant.numeric: #B5CEA8", "light_vs": "constant.numeric: #098658", "hc_black": "constant.numeric: #B5CEA8", "dark_plus_experimental": "constant.numeric: #B5CEA8", "hc_light": "constant.numeric: #096D48", "light_plus_experimental": "constant.numeric: #098658" } }, { "c": ",", "t": "text.bibtex meta.entry.braces.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "volume", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex support.function.key.bibtex", "r": { "dark_plus": "support.function: #DCDCAA", "light_plus": "support.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.function: #DCDCAA", "dark_plus_experimental": "support.function: #DCDCAA", "hc_light": "support.function: #5E2CBC", "light_plus_experimental": "support.function: #795E26" } }, { "c": " ", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "=", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.separator.key-value.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": " ", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "{", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.definition.string.begin.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "-1", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "}", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.definition.string.end.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": ",", "t": "text.bibtex meta.entry.braces.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "note", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex support.function.key.bibtex", "r": { "dark_plus": "support.function: #DCDCAA", "light_plus": "support.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.function: #DCDCAA", "dark_plus_experimental": "support.function: #DCDCAA", "hc_light": "support.function: #5E2CBC", "light_plus_experimental": "support.function: #795E26" } }, { "c": " ", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "=", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.separator.key-value.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": " ", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "{", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.definition.string.begin.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "to appear", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "}", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.definition.string.end.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": ",", "t": "text.bibtex meta.entry.braces.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "}", "t": "text.bibtex meta.entry.braces.bibtex punctuation.section.entry.end.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "@", "t": "text.bibtex meta.entry.braces.bibtex keyword.other.entry-type.bibtex punctuation.definition.keyword.bibtex", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6", "dark_plus_experimental": "keyword: #569CD6", "hc_light": "keyword: #0F4A85", "light_plus_experimental": "keyword: #0000FF" } }, { "c": "article", "t": "text.bibtex meta.entry.braces.bibtex keyword.other.entry-type.bibtex", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6", "dark_plus_experimental": "keyword: #569CD6", "hc_light": "keyword: #0F4A85", "light_plus_experimental": "keyword: #0000FF" } }, { "c": "{", "t": "text.bibtex meta.entry.braces.bibtex punctuation.section.entry.begin.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "big", "t": "text.bibtex meta.entry.braces.bibtex entity.name.type.entry-key.bibtex", "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", "dark_plus_experimental": "entity.name.type: #4EC9B0", "hc_light": "entity.name.type: #185E73", "light_plus_experimental": "entity.name.type: #267F99" } }, { "c": ",", "t": "text.bibtex meta.entry.braces.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "author", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex support.function.key.bibtex", "r": { "dark_plus": "support.function: #DCDCAA", "light_plus": "support.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.function: #DCDCAA", "dark_plus_experimental": "support.function: #DCDCAA", "hc_light": "support.function: #5E2CBC", "light_plus_experimental": "support.function: #795E26" } }, { "c": " ", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "=", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.separator.key-value.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": " ", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "{", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.definition.string.begin.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "Jass, Hugh", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "}", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.definition.string.end.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": ",", "t": "text.bibtex meta.entry.braces.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "title", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex support.function.key.bibtex", "r": { "dark_plus": "support.function: #DCDCAA", "light_plus": "support.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.function: #DCDCAA", "dark_plus_experimental": "support.function: #DCDCAA", "hc_light": "support.function: #5E2CBC", "light_plus_experimental": "support.function: #795E26" } }, { "c": " ", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "=", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.separator.key-value.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": " ", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "{", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.definition.string.begin.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "A big paper", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "}", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.definition.string.end.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": ",", "t": "text.bibtex meta.entry.braces.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "journal", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex support.function.key.bibtex", "r": { "dark_plus": "support.function: #DCDCAA", "light_plus": "support.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.function: #DCDCAA", "dark_plus_experimental": "support.function: #DCDCAA", "hc_light": "support.function: #5E2CBC", "light_plus_experimental": "support.function: #795E26" } }, { "c": " ", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "=", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.separator.key-value.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": " ", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "{", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.definition.string.begin.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "The journal of big papers", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "}", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.definition.string.end.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": ",", "t": "text.bibtex meta.entry.braces.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "year", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex support.function.key.bibtex", "r": { "dark_plus": "support.function: #DCDCAA", "light_plus": "support.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.function: #DCDCAA", "dark_plus_experimental": "support.function: #DCDCAA", "hc_light": "support.function: #5E2CBC", "light_plus_experimental": "support.function: #795E26" } }, { "c": " ", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "=", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.separator.key-value.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": " ", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "7991", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex constant.numeric.bibtex", "r": { "dark_plus": "constant.numeric: #B5CEA8", "light_plus": "constant.numeric: #098658", "dark_vs": "constant.numeric: #B5CEA8", "light_vs": "constant.numeric: #098658", "hc_black": "constant.numeric: #B5CEA8", "dark_plus_experimental": "constant.numeric: #B5CEA8", "hc_light": "constant.numeric: #096D48", "light_plus_experimental": "constant.numeric: #098658" } }, { "c": ",", "t": "text.bibtex meta.entry.braces.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "volume", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex support.function.key.bibtex", "r": { "dark_plus": "support.function: #DCDCAA", "light_plus": "support.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.function: #DCDCAA", "dark_plus_experimental": "support.function: #DCDCAA", "hc_light": "support.function: #5E2CBC", "light_plus_experimental": "support.function: #795E26" } }, { "c": " ", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "=", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.separator.key-value.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": " ", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "{", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.definition.string.begin.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "MCMXCVII", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "}", "t": "text.bibtex meta.entry.braces.bibtex meta.key-assignment.bibtex punctuation.definition.string.end.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": ",", "t": "text.bibtex meta.entry.braces.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "}", "t": "text.bibtex meta.entry.braces.bibtex punctuation.section.entry.end.bibtex", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "dark_plus_experimental": "default: #FFFFFFD3", "hc_light": "default: #292929", "light_plus_experimental": "default: #000000E4" } }, { "c": "% The authors mentioned here are almost, but not quite,", "t": "text.bibtex comment.block.bibtex", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668", "dark_plus_experimental": "comment: #6A9955", "hc_light": "comment: #515151", "light_plus_experimental": "comment: #008000" } }, { "c": "% entirely unrelated to Matt Groening.", "t": "text.bibtex comment.block.bibtex", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668", "dark_plus_experimental": "comment: #6A9955", "hc_light": "comment: #515151", "light_plus_experimental": "comment: #008000" } } ]
extensions/vscode-colorize-tests/test/colorize-results/test_bib.json
0
https://github.com/microsoft/vscode/commit/f078e6db483250957314c56c3b12e23dae03d351
[ 0.00017533382924739271, 0.00017204195319209248, 0.0001694028323981911, 0.00017186807235702872, 0.0000010241298014079803 ]
{ "id": 2, "code_window": [ "\n", "\t\tif (this.isSelectionChangeEvent(e)) {\n", "\t\t\treturn;\n", "\t\t}\n", "\n", "\t\tconst focus = this.list.getFocus();\n", "\t\tthis.list.setSelection(focus, e.browserEvent);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\t\tif (e.browserEvent.defaultPrevented) {\n", "\t\t\treturn;\n", "\t\t}\n", "\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "add", "edit_start_line_idx": 723 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IDragAndDropData } from 'vs/base/browser/dnd'; import { createStyleSheet, Dimension, EventHelper } from 'vs/base/browser/dom'; import { DomEmitter } from 'vs/base/browser/event'; import { IKeyboardEvent, StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { Gesture } from 'vs/base/browser/touch'; import { alert, AriaRole } from 'vs/base/browser/ui/aria/aria'; import { CombinedSpliceable } from 'vs/base/browser/ui/list/splice'; import { ScrollableElementChangeOptions } from 'vs/base/browser/ui/scrollbar/scrollableElementOptions'; import { binarySearch, firstOrDefault, range } from 'vs/base/common/arrays'; import { timeout } from 'vs/base/common/async'; import { Color } from 'vs/base/common/color'; import { memoize } from 'vs/base/common/decorators'; import { Emitter, Event, EventBufferer } from 'vs/base/common/event'; import { matchesPrefix } from 'vs/base/common/filters'; import { KeyCode } from 'vs/base/common/keyCodes'; import { DisposableStore, dispose, IDisposable } from 'vs/base/common/lifecycle'; import { clamp } from 'vs/base/common/numbers'; import { mixin } from 'vs/base/common/objects'; import * as platform from 'vs/base/common/platform'; import { ScrollbarVisibility, ScrollEvent } from 'vs/base/common/scrollable'; import { ISpliceable } from 'vs/base/common/sequence'; import { IThemable } from 'vs/base/common/styler'; import { isNumber } from 'vs/base/common/types'; import 'vs/css!./list'; import { IIdentityProvider, IKeyboardNavigationDelegate, IKeyboardNavigationLabelProvider, IListContextMenuEvent, IListDragAndDrop, IListDragOverReaction, IListEvent, IListGestureEvent, IListMouseEvent, IListRenderer, IListTouchEvent, IListVirtualDelegate, ListError } from './list'; import { IListViewAccessibilityProvider, IListViewDragAndDrop, IListViewOptions, IListViewOptionsUpdate, ListView } from './listView'; interface ITraitChangeEvent { indexes: number[]; browserEvent?: UIEvent; } type ITraitTemplateData = HTMLElement; interface IRenderedContainer { templateData: ITraitTemplateData; index: number; } class TraitRenderer<T> implements IListRenderer<T, ITraitTemplateData> { private renderedElements: IRenderedContainer[] = []; constructor(private trait: Trait<T>) { } get templateId(): string { return `template:${this.trait.name}`; } renderTemplate(container: HTMLElement): ITraitTemplateData { return container; } renderElement(element: T, index: number, templateData: ITraitTemplateData): void { const renderedElementIndex = this.renderedElements.findIndex(el => el.templateData === templateData); if (renderedElementIndex >= 0) { const rendered = this.renderedElements[renderedElementIndex]; this.trait.unrender(templateData); rendered.index = index; } else { const rendered = { index, templateData }; this.renderedElements.push(rendered); } this.trait.renderIndex(index, templateData); } splice(start: number, deleteCount: number, insertCount: number): void { const rendered: IRenderedContainer[] = []; for (const renderedElement of this.renderedElements) { if (renderedElement.index < start) { rendered.push(renderedElement); } else if (renderedElement.index >= start + deleteCount) { rendered.push({ index: renderedElement.index + insertCount - deleteCount, templateData: renderedElement.templateData }); } } this.renderedElements = rendered; } renderIndexes(indexes: number[]): void { for (const { index, templateData } of this.renderedElements) { if (indexes.indexOf(index) > -1) { this.trait.renderIndex(index, templateData); } } } disposeTemplate(templateData: ITraitTemplateData): void { const index = this.renderedElements.findIndex(el => el.templateData === templateData); if (index < 0) { return; } this.renderedElements.splice(index, 1); } } class Trait<T> implements ISpliceable<boolean>, IDisposable { private length = 0; private indexes: number[] = []; private sortedIndexes: number[] = []; private readonly _onChange = new Emitter<ITraitChangeEvent>(); readonly onChange: Event<ITraitChangeEvent> = this._onChange.event; get name(): string { return this._trait; } @memoize get renderer(): TraitRenderer<T> { return new TraitRenderer<T>(this); } constructor(private _trait: string) { } splice(start: number, deleteCount: number, elements: boolean[]): void { deleteCount = Math.max(0, Math.min(deleteCount, this.length - start)); const diff = elements.length - deleteCount; const end = start + deleteCount; const sortedIndexes = [ ...this.sortedIndexes.filter(i => i < start), ...elements.map((hasTrait, i) => hasTrait ? i + start : -1).filter(i => i !== -1), ...this.sortedIndexes.filter(i => i >= end).map(i => i + diff) ]; const length = this.length + diff; if (this.sortedIndexes.length > 0 && sortedIndexes.length === 0 && length > 0) { const first = this.sortedIndexes.find(index => index >= start) ?? length - 1; sortedIndexes.push(Math.min(first, length - 1)); } this.renderer.splice(start, deleteCount, elements.length); this._set(sortedIndexes, sortedIndexes); this.length = length; } renderIndex(index: number, container: HTMLElement): void { container.classList.toggle(this._trait, this.contains(index)); } unrender(container: HTMLElement): void { container.classList.remove(this._trait); } /** * Sets the indexes which should have this trait. * * @param indexes Indexes which should have this trait. * @return The old indexes which had this trait. */ set(indexes: number[], browserEvent?: UIEvent): number[] { return this._set(indexes, [...indexes].sort(numericSort), browserEvent); } private _set(indexes: number[], sortedIndexes: number[], browserEvent?: UIEvent): number[] { const result = this.indexes; const sortedResult = this.sortedIndexes; this.indexes = indexes; this.sortedIndexes = sortedIndexes; const toRender = disjunction(sortedResult, indexes); this.renderer.renderIndexes(toRender); this._onChange.fire({ indexes, browserEvent }); return result; } get(): number[] { return this.indexes; } contains(index: number): boolean { return binarySearch(this.sortedIndexes, index, numericSort) >= 0; } dispose() { dispose(this._onChange); } } class SelectionTrait<T> extends Trait<T> { constructor(private setAriaSelected: boolean) { super('selected'); } override renderIndex(index: number, container: HTMLElement): void { super.renderIndex(index, container); if (this.setAriaSelected) { if (this.contains(index)) { container.setAttribute('aria-selected', 'true'); } else { container.setAttribute('aria-selected', 'false'); } } } } /** * The TraitSpliceable is used as a util class to be able * to preserve traits across splice calls, given an identity * provider. */ class TraitSpliceable<T> implements ISpliceable<T> { constructor( private trait: Trait<T>, private view: ListView<T>, private identityProvider?: IIdentityProvider<T> ) { } splice(start: number, deleteCount: number, elements: T[]): void { if (!this.identityProvider) { return this.trait.splice(start, deleteCount, elements.map(() => false)); } const pastElementsWithTrait = this.trait.get().map(i => this.identityProvider!.getId(this.view.element(i)).toString()); const elementsWithTrait = elements.map(e => pastElementsWithTrait.indexOf(this.identityProvider!.getId(e).toString()) > -1); this.trait.splice(start, deleteCount, elementsWithTrait); } } export function isInputElement(e: HTMLElement): boolean { return e.tagName === 'INPUT' || e.tagName === 'TEXTAREA'; } export function isMonacoEditor(e: HTMLElement): boolean { if (e.classList.contains('monaco-editor')) { return true; } if (e.classList.contains('monaco-list')) { return false; } if (!e.parentElement) { return false; } return isMonacoEditor(e.parentElement); } export function isButton(e: HTMLElement): boolean { if ((e.tagName === 'A' && e.classList.contains('monaco-button')) || (e.tagName === 'DIV' && e.classList.contains('monaco-button-dropdown'))) { return true; } if (e.classList.contains('monaco-list')) { return false; } if (!e.parentElement) { return false; } return isButton(e.parentElement); } class KeyboardController<T> implements IDisposable { private readonly disposables = new DisposableStore(); private readonly multipleSelectionDisposables = new DisposableStore(); @memoize private get onKeyDown(): Event.IChainableEvent<StandardKeyboardEvent> { return this.disposables.add(Event.chain(this.disposables.add(new DomEmitter(this.view.domNode, 'keydown')).event) .filter(e => !isInputElement(e.target as HTMLElement)) .map(e => new StandardKeyboardEvent(e))); } constructor( private list: List<T>, private view: ListView<T>, options: IListOptions<T> ) { this.onKeyDown.filter(e => e.keyCode === KeyCode.Enter).on(this.onEnter, this, this.disposables); this.onKeyDown.filter(e => e.keyCode === KeyCode.UpArrow).on(this.onUpArrow, this, this.disposables); this.onKeyDown.filter(e => e.keyCode === KeyCode.DownArrow).on(this.onDownArrow, this, this.disposables); this.onKeyDown.filter(e => e.keyCode === KeyCode.PageUp).on(this.onPageUpArrow, this, this.disposables); this.onKeyDown.filter(e => e.keyCode === KeyCode.PageDown).on(this.onPageDownArrow, this, this.disposables); this.onKeyDown.filter(e => e.keyCode === KeyCode.Escape).on(this.onEscape, this, this.disposables); if (options.multipleSelectionSupport !== false) { this.onKeyDown.filter(e => (platform.isMacintosh ? e.metaKey : e.ctrlKey) && e.keyCode === KeyCode.KeyA).on(this.onCtrlA, this, this.multipleSelectionDisposables); } } updateOptions(optionsUpdate: IListOptionsUpdate): void { if (optionsUpdate.multipleSelectionSupport !== undefined) { this.multipleSelectionDisposables.clear(); if (optionsUpdate.multipleSelectionSupport) { this.onKeyDown.filter(e => (platform.isMacintosh ? e.metaKey : e.ctrlKey) && e.keyCode === KeyCode.KeyA).on(this.onCtrlA, this, this.multipleSelectionDisposables); } } } private onEnter(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.setSelection(this.list.getFocus(), e.browserEvent); } private onUpArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusPrevious(1, false, e.browserEvent); const el = this.list.getFocus()[0]; this.list.setAnchor(el); this.list.reveal(el); this.view.domNode.focus(); } private onDownArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusNext(1, false, e.browserEvent); const el = this.list.getFocus()[0]; this.list.setAnchor(el); this.list.reveal(el); this.view.domNode.focus(); } private onPageUpArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusPreviousPage(e.browserEvent); const el = this.list.getFocus()[0]; this.list.setAnchor(el); this.list.reveal(el); this.view.domNode.focus(); } private onPageDownArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusNextPage(e.browserEvent); const el = this.list.getFocus()[0]; this.list.setAnchor(el); this.list.reveal(el); this.view.domNode.focus(); } private onCtrlA(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.setSelection(range(this.list.length), e.browserEvent); this.list.setAnchor(undefined); this.view.domNode.focus(); } private onEscape(e: StandardKeyboardEvent): void { if (this.list.getSelection().length) { e.preventDefault(); e.stopPropagation(); this.list.setSelection([], e.browserEvent); this.list.setAnchor(undefined); this.view.domNode.focus(); } } dispose() { this.disposables.dispose(); this.multipleSelectionDisposables.dispose(); } } export enum TypeNavigationMode { Automatic, Trigger } enum TypeNavigationControllerState { Idle, Typing } export const DefaultKeyboardNavigationDelegate = new class implements IKeyboardNavigationDelegate { mightProducePrintableCharacter(event: IKeyboardEvent): boolean { if (event.ctrlKey || event.metaKey || event.altKey) { return false; } return (event.keyCode >= KeyCode.KeyA && event.keyCode <= KeyCode.KeyZ) || (event.keyCode >= KeyCode.Digit0 && event.keyCode <= KeyCode.Digit9) || (event.keyCode >= KeyCode.Numpad0 && event.keyCode <= KeyCode.Numpad9) || (event.keyCode >= KeyCode.Semicolon && event.keyCode <= KeyCode.Quote); } }; class TypeNavigationController<T> implements IDisposable { private enabled = false; private state: TypeNavigationControllerState = TypeNavigationControllerState.Idle; private mode = TypeNavigationMode.Automatic; private triggered = false; private previouslyFocused = -1; private readonly enabledDisposables = new DisposableStore(); private readonly disposables = new DisposableStore(); constructor( private list: List<T>, private view: ListView<T>, private keyboardNavigationLabelProvider: IKeyboardNavigationLabelProvider<T>, private keyboardNavigationEventFilter: IKeyboardNavigationEventFilter, private delegate: IKeyboardNavigationDelegate ) { this.updateOptions(list.options); } updateOptions(options: IListOptions<T>): void { if (options.typeNavigationEnabled ?? true) { this.enable(); } else { this.disable(); } this.mode = options.typeNavigationMode ?? TypeNavigationMode.Automatic; } trigger(): void { this.triggered = !this.triggered; } private enable(): void { if (this.enabled) { return; } let typing = false; const onChar = this.enabledDisposables.add(Event.chain(this.enabledDisposables.add(new DomEmitter(this.view.domNode, 'keydown')).event)) .filter(e => !isInputElement(e.target as HTMLElement)) .filter(() => this.mode === TypeNavigationMode.Automatic || this.triggered) .map(event => new StandardKeyboardEvent(event)) .filter(e => typing || this.keyboardNavigationEventFilter(e)) .filter(e => this.delegate.mightProducePrintableCharacter(e)) .forEach(e => EventHelper.stop(e, true)) .map(event => event.browserEvent.key) .event; const onClear = Event.debounce<string, null>(onChar, () => null, 800, undefined, undefined, this.enabledDisposables); const onInput = Event.reduce<string | null, string | null>(Event.any(onChar, onClear), (r, i) => i === null ? null : ((r || '') + i), undefined, this.enabledDisposables); onInput(this.onInput, this, this.enabledDisposables); onClear(this.onClear, this, this.enabledDisposables); onChar(() => typing = true, undefined, this.enabledDisposables); onClear(() => typing = false, undefined, this.enabledDisposables); this.enabled = true; this.triggered = false; } private disable(): void { if (!this.enabled) { return; } this.enabledDisposables.clear(); this.enabled = false; this.triggered = false; } private onClear(): void { const focus = this.list.getFocus(); if (focus.length > 0 && focus[0] === this.previouslyFocused) { // List: re-announce element on typing end since typed keys will interrupt aria label of focused element // Do not announce if there was a focus change at the end to prevent duplication https://github.com/microsoft/vscode/issues/95961 const ariaLabel = this.list.options.accessibilityProvider?.getAriaLabel(this.list.element(focus[0])); if (ariaLabel) { alert(ariaLabel); } } this.previouslyFocused = -1; } private onInput(word: string | null): void { if (!word) { this.state = TypeNavigationControllerState.Idle; this.triggered = false; return; } const focus = this.list.getFocus(); const start = focus.length > 0 ? focus[0] : 0; const delta = this.state === TypeNavigationControllerState.Idle ? 1 : 0; this.state = TypeNavigationControllerState.Typing; for (let i = 0; i < this.list.length; i++) { const index = (start + i + delta) % this.list.length; const label = this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(this.view.element(index)); const labelStr = label && label.toString(); if (typeof labelStr === 'undefined' || matchesPrefix(word, labelStr)) { this.previouslyFocused = start; this.list.setFocus([index]); this.list.reveal(index); return; } } } dispose() { this.disable(); this.enabledDisposables.dispose(); this.disposables.dispose(); } } class DOMFocusController<T> implements IDisposable { private readonly disposables = new DisposableStore(); constructor( private list: List<T>, private view: ListView<T> ) { const onKeyDown = this.disposables.add(Event.chain(this.disposables.add(new DomEmitter(view.domNode, 'keydown')).event)) .filter(e => !isInputElement(e.target as HTMLElement)) .map(e => new StandardKeyboardEvent(e)); onKeyDown.filter(e => e.keyCode === KeyCode.Tab && !e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey) .on(this.onTab, this, this.disposables); } private onTab(e: StandardKeyboardEvent): void { if (e.target !== this.view.domNode) { return; } const focus = this.list.getFocus(); if (focus.length === 0) { return; } const focusedDomElement = this.view.domElement(focus[0]); if (!focusedDomElement) { return; } const tabIndexElement = focusedDomElement.querySelector('[tabIndex]'); if (!tabIndexElement || !(tabIndexElement instanceof HTMLElement) || tabIndexElement.tabIndex === -1) { return; } const style = window.getComputedStyle(tabIndexElement); if (style.visibility === 'hidden' || style.display === 'none') { return; } e.preventDefault(); e.stopPropagation(); tabIndexElement.focus(); } dispose() { this.disposables.dispose(); } } export function isSelectionSingleChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return platform.isMacintosh ? event.browserEvent.metaKey : event.browserEvent.ctrlKey; } export function isSelectionRangeChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return event.browserEvent.shiftKey; } function isMouseRightClick(event: UIEvent): boolean { return event instanceof MouseEvent && event.button === 2; } const DefaultMultipleSelectionController = { isSelectionSingleChangeEvent, isSelectionRangeChangeEvent }; export class MouseController<T> implements IDisposable { private multipleSelectionController: IMultipleSelectionController<T> | undefined; private mouseSupport: boolean; private readonly disposables = new DisposableStore(); private _onPointer = new Emitter<IListMouseEvent<T>>(); readonly onPointer: Event<IListMouseEvent<T>> = this._onPointer.event; constructor(protected list: List<T>) { if (list.options.multipleSelectionSupport !== false) { this.multipleSelectionController = this.list.options.multipleSelectionController || DefaultMultipleSelectionController; } this.mouseSupport = typeof list.options.mouseSupport === 'undefined' || !!list.options.mouseSupport; if (this.mouseSupport) { list.onMouseDown(this.onMouseDown, this, this.disposables); list.onContextMenu(this.onContextMenu, this, this.disposables); list.onMouseDblClick(this.onDoubleClick, this, this.disposables); list.onTouchStart(this.onMouseDown, this, this.disposables); this.disposables.add(Gesture.addTarget(list.getHTMLElement())); } Event.any(list.onMouseClick, list.onMouseMiddleClick, list.onTap)(this.onViewPointer, this, this.disposables); } updateOptions(optionsUpdate: IListOptionsUpdate): void { if (optionsUpdate.multipleSelectionSupport !== undefined) { this.multipleSelectionController = undefined; if (optionsUpdate.multipleSelectionSupport) { this.multipleSelectionController = this.list.options.multipleSelectionController || DefaultMultipleSelectionController; } } } protected isSelectionSingleChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { if (!this.multipleSelectionController) { return false; } return this.multipleSelectionController.isSelectionSingleChangeEvent(event); } protected isSelectionRangeChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { if (!this.multipleSelectionController) { return false; } return this.multipleSelectionController.isSelectionRangeChangeEvent(event); } private isSelectionChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return this.isSelectionSingleChangeEvent(event) || this.isSelectionRangeChangeEvent(event); } private onMouseDown(e: IListMouseEvent<T> | IListTouchEvent<T>): void { if (isMonacoEditor(e.browserEvent.target as HTMLElement)) { return; } if (document.activeElement !== e.browserEvent.target) { this.list.domFocus(); } } private onContextMenu(e: IListContextMenuEvent<T>): void { if (isInputElement(e.browserEvent.target as HTMLElement) || isMonacoEditor(e.browserEvent.target as HTMLElement)) { return; } const focus = typeof e.index === 'undefined' ? [] : [e.index]; this.list.setFocus(focus, e.browserEvent); } protected onViewPointer(e: IListMouseEvent<T>): void { if (!this.mouseSupport) { return; } if (isInputElement(e.browserEvent.target as HTMLElement) || isMonacoEditor(e.browserEvent.target as HTMLElement)) { return; } const focus = e.index; if (typeof focus === 'undefined') { this.list.setFocus([], e.browserEvent); this.list.setSelection([], e.browserEvent); this.list.setAnchor(undefined); return; } if (this.isSelectionRangeChangeEvent(e)) { return this.changeSelection(e); } if (this.isSelectionChangeEvent(e)) { return this.changeSelection(e); } this.list.setFocus([focus], e.browserEvent); this.list.setAnchor(focus); if (!isMouseRightClick(e.browserEvent)) { this.list.setSelection([focus], e.browserEvent); } this._onPointer.fire(e); } protected onDoubleClick(e: IListMouseEvent<T>): void { if (isInputElement(e.browserEvent.target as HTMLElement) || isMonacoEditor(e.browserEvent.target as HTMLElement)) { return; } if (this.isSelectionChangeEvent(e)) { return; } const focus = this.list.getFocus(); this.list.setSelection(focus, e.browserEvent); } private changeSelection(e: IListMouseEvent<T> | IListTouchEvent<T>): void { const focus = e.index!; let anchor = this.list.getAnchor(); if (this.isSelectionRangeChangeEvent(e)) { if (typeof anchor === 'undefined') { const currentFocus = this.list.getFocus()[0]; anchor = currentFocus ?? focus; this.list.setAnchor(anchor); } const min = Math.min(anchor, focus); const max = Math.max(anchor, focus); const rangeSelection = range(min, max + 1); const selection = this.list.getSelection(); const contiguousRange = getContiguousRangeContaining(disjunction(selection, [anchor]), anchor); if (contiguousRange.length === 0) { return; } const newSelection = disjunction(rangeSelection, relativeComplement(selection, contiguousRange)); this.list.setSelection(newSelection, e.browserEvent); this.list.setFocus([focus], e.browserEvent); } else if (this.isSelectionSingleChangeEvent(e)) { const selection = this.list.getSelection(); const newSelection = selection.filter(i => i !== focus); this.list.setFocus([focus]); this.list.setAnchor(focus); if (selection.length === newSelection.length) { this.list.setSelection([...newSelection, focus], e.browserEvent); } else { this.list.setSelection(newSelection, e.browserEvent); } } } dispose() { this.disposables.dispose(); } } export interface IMultipleSelectionController<T> { isSelectionSingleChangeEvent(event: IListMouseEvent<T> | IListTouchEvent<T>): boolean; isSelectionRangeChangeEvent(event: IListMouseEvent<T> | IListTouchEvent<T>): boolean; } export interface IStyleController { style(styles: IListStyles): void; } export interface IListAccessibilityProvider<T> extends IListViewAccessibilityProvider<T> { getAriaLabel(element: T): string | null; getWidgetAriaLabel(): string; getWidgetRole?(): AriaRole; getAriaLevel?(element: T): number | undefined; onDidChangeActiveDescendant?: Event<void>; getActiveDescendantId?(element: T): string | undefined; } export class DefaultStyleController implements IStyleController { constructor(private styleElement: HTMLStyleElement, private selectorSuffix: string) { } style(styles: IListStyles): void { const suffix = this.selectorSuffix && `.${this.selectorSuffix}`; const content: string[] = []; if (styles.listBackground) { if (styles.listBackground.isOpaque()) { content.push(`.monaco-list${suffix} .monaco-list-rows { background: ${styles.listBackground}; }`); } else if (!platform.isMacintosh) { // subpixel AA doesn't exist in macOS console.warn(`List with id '${this.selectorSuffix}' was styled with a non-opaque background color. This will break sub-pixel antialiasing.`); } } if (styles.listFocusBackground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { background-color: ${styles.listFocusBackground}; }`); content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused:hover { background-color: ${styles.listFocusBackground}; }`); // overwrite :hover style in this case! } if (styles.listFocusForeground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { color: ${styles.listFocusForeground}; }`); } if (styles.listActiveSelectionBackground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { background-color: ${styles.listActiveSelectionBackground}; }`); content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected:hover { background-color: ${styles.listActiveSelectionBackground}; }`); // overwrite :hover style in this case! } if (styles.listActiveSelectionForeground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { color: ${styles.listActiveSelectionForeground}; }`); } if (styles.listActiveSelectionIconForeground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected .codicon { color: ${styles.listActiveSelectionIconForeground}; }`); } if (styles.listFocusAndSelectionOutline) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { outline-color: ${styles.listFocusAndSelectionOutline} !important; }`); } if (styles.listFocusAndSelectionBackground) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.selected.focused { background-color: ${styles.listFocusAndSelectionBackground}; } `); } if (styles.listFocusAndSelectionForeground) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.selected.focused { color: ${styles.listFocusAndSelectionForeground}; } `); } if (styles.listInactiveFocusForeground) { content.push(`.monaco-list${suffix} .monaco-list-row.focused { color: ${styles.listInactiveFocusForeground}; }`); content.push(`.monaco-list${suffix} .monaco-list-row.focused:hover { color: ${styles.listInactiveFocusForeground}; }`); // overwrite :hover style in this case! } if (styles.listInactiveSelectionIconForeground) { content.push(`.monaco-list${suffix} .monaco-list-row.focused .codicon { color: ${styles.listInactiveSelectionIconForeground}; }`); } if (styles.listInactiveFocusBackground) { content.push(`.monaco-list${suffix} .monaco-list-row.focused { background-color: ${styles.listInactiveFocusBackground}; }`); content.push(`.monaco-list${suffix} .monaco-list-row.focused:hover { background-color: ${styles.listInactiveFocusBackground}; }`); // overwrite :hover style in this case! } if (styles.listInactiveSelectionBackground) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { background-color: ${styles.listInactiveSelectionBackground}; }`); content.push(`.monaco-list${suffix} .monaco-list-row.selected:hover { background-color: ${styles.listInactiveSelectionBackground}; }`); // overwrite :hover style in this case! } if (styles.listInactiveSelectionForeground) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { color: ${styles.listInactiveSelectionForeground}; }`); } if (styles.listHoverBackground) { content.push(`.monaco-list${suffix}:not(.drop-target):not(.dragging) .monaco-list-row:hover:not(.selected):not(.focused) { background-color: ${styles.listHoverBackground}; }`); } if (styles.listHoverForeground) { content.push(`.monaco-list${suffix}:not(.drop-target):not(.dragging) .monaco-list-row:hover:not(.selected):not(.focused) { color: ${styles.listHoverForeground}; }`); } if (styles.listSelectionOutline) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { outline: 1px dotted ${styles.listSelectionOutline}; outline-offset: -1px; }`); } if (styles.listFocusOutline) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; } .monaco-workbench.context-menu-visible .monaco-list${suffix}.last-focused .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; } `); } if (styles.listInactiveFocusOutline) { content.push(`.monaco-list${suffix} .monaco-list-row.focused { outline: 1px dotted ${styles.listInactiveFocusOutline}; outline-offset: -1px; }`); } if (styles.listHoverOutline) { content.push(`.monaco-list${suffix} .monaco-list-row:hover { outline: 1px dashed ${styles.listHoverOutline}; outline-offset: -1px; }`); } if (styles.listDropBackground) { content.push(` .monaco-list${suffix}.drop-target, .monaco-list${suffix} .monaco-list-rows.drop-target, .monaco-list${suffix} .monaco-list-row.drop-target { background-color: ${styles.listDropBackground} !important; color: inherit !important; } `); } if (styles.tableColumnsBorder) { content.push(` .monaco-table > .monaco-split-view2, .monaco-table > .monaco-split-view2 .monaco-sash.vertical::before, .monaco-workbench:not(.reduce-motion) .monaco-table:hover > .monaco-split-view2, .monaco-workbench:not(.reduce-motion) .monaco-table:hover > .monaco-split-view2 .monaco-sash.vertical::before { border-color: ${styles.tableColumnsBorder}; } .monaco-workbench:not(.reduce-motion) .monaco-table > .monaco-split-view2, .monaco-workbench:not(.reduce-motion) .monaco-table > .monaco-split-view2 .monaco-sash.vertical::before { border-color: transparent; } `); } if (styles.tableOddRowsBackgroundColor) { content.push(` .monaco-table .monaco-list-row[data-parity=odd]:not(.focused):not(.selected):not(:hover) .monaco-table-tr, .monaco-table .monaco-list:not(:focus) .monaco-list-row[data-parity=odd].focused:not(.selected):not(:hover) .monaco-table-tr, .monaco-table .monaco-list:not(.focused) .monaco-list-row[data-parity=odd].focused:not(.selected):not(:hover) .monaco-table-tr { background-color: ${styles.tableOddRowsBackgroundColor}; } `); } this.styleElement.textContent = content.join('\n'); } } export interface IKeyboardNavigationEventFilter { (e: StandardKeyboardEvent): boolean; } export interface IListOptionsUpdate extends IListViewOptionsUpdate { readonly typeNavigationEnabled?: boolean; readonly typeNavigationMode?: TypeNavigationMode; readonly multipleSelectionSupport?: boolean; } export interface IListOptions<T> extends IListOptionsUpdate { readonly identityProvider?: IIdentityProvider<T>; readonly dnd?: IListDragAndDrop<T>; readonly keyboardNavigationLabelProvider?: IKeyboardNavigationLabelProvider<T>; readonly keyboardNavigationDelegate?: IKeyboardNavigationDelegate; readonly keyboardSupport?: boolean; readonly multipleSelectionController?: IMultipleSelectionController<T>; readonly styleController?: (suffix: string) => IStyleController; readonly accessibilityProvider?: IListAccessibilityProvider<T>; readonly keyboardNavigationEventFilter?: IKeyboardNavigationEventFilter; // list view options readonly useShadows?: boolean; readonly verticalScrollMode?: ScrollbarVisibility; readonly setRowLineHeight?: boolean; readonly setRowHeight?: boolean; readonly supportDynamicHeights?: boolean; readonly mouseSupport?: boolean; readonly horizontalScrolling?: boolean; readonly scrollByPage?: boolean; readonly additionalScrollHeight?: number; readonly transformOptimization?: boolean; readonly smoothScrolling?: boolean; readonly scrollableElementChangeOptions?: ScrollableElementChangeOptions; readonly alwaysConsumeMouseWheel?: boolean; readonly initialSize?: Dimension; } export interface IListStyles { listBackground?: Color; listFocusBackground?: Color; listFocusForeground?: Color; listActiveSelectionBackground?: Color; listActiveSelectionForeground?: Color; listActiveSelectionIconForeground?: Color; listFocusAndSelectionOutline?: Color; listFocusAndSelectionBackground?: Color; listFocusAndSelectionForeground?: Color; listInactiveSelectionBackground?: Color; listInactiveSelectionIconForeground?: Color; listInactiveSelectionForeground?: Color; listInactiveFocusForeground?: Color; listInactiveFocusBackground?: Color; listHoverBackground?: Color; listHoverForeground?: Color; listDropBackground?: Color; listFocusOutline?: Color; listInactiveFocusOutline?: Color; listSelectionOutline?: Color; listHoverOutline?: Color; treeIndentGuidesStroke?: Color; tableColumnsBorder?: Color; tableOddRowsBackgroundColor?: Color; } const defaultStyles: IListStyles = { listFocusBackground: Color.fromHex('#7FB0D0'), listActiveSelectionBackground: Color.fromHex('#0E639C'), listActiveSelectionForeground: Color.fromHex('#FFFFFF'), listActiveSelectionIconForeground: Color.fromHex('#FFFFFF'), listFocusAndSelectionOutline: Color.fromHex('#90C2F9'), listFocusAndSelectionBackground: Color.fromHex('#094771'), listFocusAndSelectionForeground: Color.fromHex('#FFFFFF'), listInactiveSelectionBackground: Color.fromHex('#3F3F46'), listInactiveSelectionIconForeground: Color.fromHex('#FFFFFF'), listHoverBackground: Color.fromHex('#2A2D2E'), listDropBackground: Color.fromHex('#383B3D'), treeIndentGuidesStroke: Color.fromHex('#a9a9a9'), tableColumnsBorder: Color.fromHex('#cccccc').transparent(0.2), tableOddRowsBackgroundColor: Color.fromHex('#cccccc').transparent(0.04) }; const DefaultOptions: IListOptions<any> = { keyboardSupport: true, mouseSupport: true, multipleSelectionSupport: true, dnd: { getDragURI() { return null; }, onDragStart(): void { }, onDragOver() { return false; }, drop() { } } }; // TODO@Joao: move these utils into a SortedArray class function getContiguousRangeContaining(range: number[], value: number): number[] { const index = range.indexOf(value); if (index === -1) { return []; } const result: number[] = []; let i = index - 1; while (i >= 0 && range[i] === value - (index - i)) { result.push(range[i--]); } result.reverse(); i = index; while (i < range.length && range[i] === value + (i - index)) { result.push(range[i++]); } return result; } /** * Given two sorted collections of numbers, returns the intersection * between them (OR). */ function disjunction(one: number[], other: number[]): number[] { const result: number[] = []; let i = 0, j = 0; while (i < one.length || j < other.length) { if (i >= one.length) { result.push(other[j++]); } else if (j >= other.length) { result.push(one[i++]); } else if (one[i] === other[j]) { result.push(one[i]); i++; j++; continue; } else if (one[i] < other[j]) { result.push(one[i++]); } else { result.push(other[j++]); } } return result; } /** * Given two sorted collections of numbers, returns the relative * complement between them (XOR). */ function relativeComplement(one: number[], other: number[]): number[] { const result: number[] = []; let i = 0, j = 0; while (i < one.length || j < other.length) { if (i >= one.length) { result.push(other[j++]); } else if (j >= other.length) { result.push(one[i++]); } else if (one[i] === other[j]) { i++; j++; continue; } else if (one[i] < other[j]) { result.push(one[i++]); } else { j++; } } return result; } const numericSort = (a: number, b: number) => a - b; class PipelineRenderer<T> implements IListRenderer<T, any> { constructor( private _templateId: string, private renderers: IListRenderer<any /* TODO@joao */, any>[] ) { } get templateId(): string { return this._templateId; } renderTemplate(container: HTMLElement): any[] { return this.renderers.map(r => r.renderTemplate(container)); } renderElement(element: T, index: number, templateData: any[], height: number | undefined): void { let i = 0; for (const renderer of this.renderers) { renderer.renderElement(element, index, templateData[i++], height); } } disposeElement(element: T, index: number, templateData: any[], height: number | undefined): void { let i = 0; for (const renderer of this.renderers) { renderer.disposeElement?.(element, index, templateData[i], height); i += 1; } } disposeTemplate(templateData: any[]): void { let i = 0; for (const renderer of this.renderers) { renderer.disposeTemplate(templateData[i++]); } } } class AccessibiltyRenderer<T> implements IListRenderer<T, HTMLElement> { templateId: string = 'a18n'; constructor(private accessibilityProvider: IListAccessibilityProvider<T>) { } renderTemplate(container: HTMLElement): HTMLElement { return container; } renderElement(element: T, index: number, container: HTMLElement): void { const ariaLabel = this.accessibilityProvider.getAriaLabel(element); if (ariaLabel) { container.setAttribute('aria-label', ariaLabel); } else { container.removeAttribute('aria-label'); } const ariaLevel = this.accessibilityProvider.getAriaLevel && this.accessibilityProvider.getAriaLevel(element); if (typeof ariaLevel === 'number') { container.setAttribute('aria-level', `${ariaLevel}`); } else { container.removeAttribute('aria-level'); } } disposeTemplate(templateData: any): void { // noop } } class ListViewDragAndDrop<T> implements IListViewDragAndDrop<T> { constructor(private list: List<T>, private dnd: IListDragAndDrop<T>) { } getDragElements(element: T): T[] { const selection = this.list.getSelectedElements(); const elements = selection.indexOf(element) > -1 ? selection : [element]; return elements; } getDragURI(element: T): string | null { return this.dnd.getDragURI(element); } getDragLabel?(elements: T[], originalEvent: DragEvent): string | undefined { if (this.dnd.getDragLabel) { return this.dnd.getDragLabel(elements, originalEvent); } return undefined; } onDragStart(data: IDragAndDropData, originalEvent: DragEvent): void { this.dnd.onDragStart?.(data, originalEvent); } onDragOver(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): boolean | IListDragOverReaction { return this.dnd.onDragOver(data, targetElement, targetIndex, originalEvent); } onDragLeave(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): void { this.dnd.onDragLeave?.(data, targetElement, targetIndex, originalEvent); } onDragEnd(originalEvent: DragEvent): void { this.dnd.onDragEnd?.(originalEvent); } drop(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): void { this.dnd.drop(data, targetElement, targetIndex, originalEvent); } } /** * The {@link List} is a virtual scrolling widget, built on top of the {@link ListView} * widget. * * Features: * - Customizable keyboard and mouse support * - Element traits: focus, selection, achor * - Accessibility support * - Touch support * - Performant template-based rendering * - Horizontal scrolling * - Variable element height support * - Dynamic element height support * - Drag-and-drop support */ export class List<T> implements ISpliceable<T>, IThemable, IDisposable { private focus = new Trait<T>('focused'); private selection: Trait<T>; private anchor = new Trait<T>('anchor'); private eventBufferer = new EventBufferer(); protected view: ListView<T>; private spliceable: ISpliceable<T>; private styleController: IStyleController; private typeNavigationController?: TypeNavigationController<T>; private accessibilityProvider?: IListAccessibilityProvider<T>; private keyboardController: KeyboardController<T> | undefined; private mouseController: MouseController<T>; private _ariaLabel: string = ''; protected readonly disposables = new DisposableStore(); @memoize get onDidChangeFocus(): Event<IListEvent<T>> { return Event.map(this.eventBufferer.wrapEvent(this.focus.onChange), e => this.toListEvent(e), this.disposables); } @memoize get onDidChangeSelection(): Event<IListEvent<T>> { return Event.map(this.eventBufferer.wrapEvent(this.selection.onChange), e => this.toListEvent(e), this.disposables); } get domId(): string { return this.view.domId; } get onDidScroll(): Event<ScrollEvent> { return this.view.onDidScroll; } get onMouseClick(): Event<IListMouseEvent<T>> { return this.view.onMouseClick; } get onMouseDblClick(): Event<IListMouseEvent<T>> { return this.view.onMouseDblClick; } get onMouseMiddleClick(): Event<IListMouseEvent<T>> { return this.view.onMouseMiddleClick; } get onPointer(): Event<IListMouseEvent<T>> { return this.mouseController.onPointer; } get onMouseUp(): Event<IListMouseEvent<T>> { return this.view.onMouseUp; } get onMouseDown(): Event<IListMouseEvent<T>> { return this.view.onMouseDown; } get onMouseOver(): Event<IListMouseEvent<T>> { return this.view.onMouseOver; } get onMouseMove(): Event<IListMouseEvent<T>> { return this.view.onMouseMove; } get onMouseOut(): Event<IListMouseEvent<T>> { return this.view.onMouseOut; } get onTouchStart(): Event<IListTouchEvent<T>> { return this.view.onTouchStart; } get onTap(): Event<IListGestureEvent<T>> { return this.view.onTap; } /** * Possible context menu trigger events: * - ContextMenu key * - Shift F10 * - Ctrl Option Shift M (macOS with VoiceOver) * - Mouse right click */ @memoize get onContextMenu(): Event<IListContextMenuEvent<T>> { let didJustPressContextMenuKey = false; const fromKeyDown = this.disposables.add(Event.chain(this.disposables.add(new DomEmitter(this.view.domNode, 'keydown')).event)) .map(e => new StandardKeyboardEvent(e)) .filter(e => didJustPressContextMenuKey = e.keyCode === KeyCode.ContextMenu || (e.shiftKey && e.keyCode === KeyCode.F10)) .map(e => EventHelper.stop(e, true)) .filter(() => false) .event as Event<any>; const fromKeyUp = this.disposables.add(Event.chain(this.disposables.add(new DomEmitter(this.view.domNode, 'keyup')).event)) .forEach(() => didJustPressContextMenuKey = false) .map(e => new StandardKeyboardEvent(e)) .filter(e => e.keyCode === KeyCode.ContextMenu || (e.shiftKey && e.keyCode === KeyCode.F10)) .map(e => EventHelper.stop(e, true)) .map(({ browserEvent }) => { const focus = this.getFocus(); const index = focus.length ? focus[0] : undefined; const element = typeof index !== 'undefined' ? this.view.element(index) : undefined; const anchor = typeof index !== 'undefined' ? this.view.domElement(index) as HTMLElement : this.view.domNode; return { index, element, anchor, browserEvent }; }) .event; const fromMouse = this.disposables.add(Event.chain(this.view.onContextMenu)) .filter(_ => !didJustPressContextMenuKey) .map(({ element, index, browserEvent }) => ({ element, index, anchor: { x: browserEvent.pageX + 1, y: browserEvent.pageY }, browserEvent })) .event; return Event.any<IListContextMenuEvent<T>>(fromKeyDown, fromKeyUp, fromMouse); } @memoize get onKeyDown(): Event<KeyboardEvent> { return this.disposables.add(new DomEmitter(this.view.domNode, 'keydown')).event; } @memoize get onKeyUp(): Event<KeyboardEvent> { return this.disposables.add(new DomEmitter(this.view.domNode, 'keyup')).event; } @memoize get onKeyPress(): Event<KeyboardEvent> { return this.disposables.add(new DomEmitter(this.view.domNode, 'keypress')).event; } @memoize get onDidFocus(): Event<void> { return Event.signal(this.disposables.add(new DomEmitter(this.view.domNode, 'focus', true)).event); } @memoize get onDidBlur(): Event<void> { return Event.signal(this.disposables.add(new DomEmitter(this.view.domNode, 'blur', true)).event); } private readonly _onDidDispose = new Emitter<void>(); readonly onDidDispose: Event<void> = this._onDidDispose.event; constructor( private user: string, container: HTMLElement, virtualDelegate: IListVirtualDelegate<T>, renderers: IListRenderer<any /* TODO@joao */, any>[], private _options: IListOptions<T> = DefaultOptions ) { const role = this._options.accessibilityProvider && this._options.accessibilityProvider.getWidgetRole ? this._options.accessibilityProvider?.getWidgetRole() : 'list'; this.selection = new SelectionTrait(role !== 'listbox'); mixin(_options, defaultStyles, false); const baseRenderers: IListRenderer<T, ITraitTemplateData>[] = [this.focus.renderer, this.selection.renderer]; this.accessibilityProvider = _options.accessibilityProvider; if (this.accessibilityProvider) { baseRenderers.push(new AccessibiltyRenderer<T>(this.accessibilityProvider)); this.accessibilityProvider.onDidChangeActiveDescendant?.(this.onDidChangeActiveDescendant, this, this.disposables); } renderers = renderers.map(r => new PipelineRenderer(r.templateId, [...baseRenderers, r])); const viewOptions: IListViewOptions<T> = { ..._options, dnd: _options.dnd && new ListViewDragAndDrop(this, _options.dnd) }; this.view = new ListView(container, virtualDelegate, renderers, viewOptions); this.view.domNode.setAttribute('role', role); if (_options.styleController) { this.styleController = _options.styleController(this.view.domId); } else { const styleElement = createStyleSheet(this.view.domNode); this.styleController = new DefaultStyleController(styleElement, this.view.domId); } this.spliceable = new CombinedSpliceable([ new TraitSpliceable(this.focus, this.view, _options.identityProvider), new TraitSpliceable(this.selection, this.view, _options.identityProvider), new TraitSpliceable(this.anchor, this.view, _options.identityProvider), this.view ]); this.disposables.add(this.focus); this.disposables.add(this.selection); this.disposables.add(this.anchor); this.disposables.add(this.view); this.disposables.add(this._onDidDispose); this.disposables.add(new DOMFocusController(this, this.view)); if (typeof _options.keyboardSupport !== 'boolean' || _options.keyboardSupport) { this.keyboardController = new KeyboardController(this, this.view, _options); this.disposables.add(this.keyboardController); } if (_options.keyboardNavigationLabelProvider) { const delegate = _options.keyboardNavigationDelegate || DefaultKeyboardNavigationDelegate; this.typeNavigationController = new TypeNavigationController(this, this.view, _options.keyboardNavigationLabelProvider, _options.keyboardNavigationEventFilter ?? (() => true), delegate); this.disposables.add(this.typeNavigationController); } this.mouseController = this.createMouseController(_options); this.disposables.add(this.mouseController); this.onDidChangeFocus(this._onFocusChange, this, this.disposables); this.onDidChangeSelection(this._onSelectionChange, this, this.disposables); if (this.accessibilityProvider) { this.ariaLabel = this.accessibilityProvider.getWidgetAriaLabel(); } if (this._options.multipleSelectionSupport !== false) { this.view.domNode.setAttribute('aria-multiselectable', 'true'); } } protected createMouseController(options: IListOptions<T>): MouseController<T> { return new MouseController(this); } updateOptions(optionsUpdate: IListOptionsUpdate = {}): void { this._options = { ...this._options, ...optionsUpdate }; this.typeNavigationController?.updateOptions(this._options); if (this._options.multipleSelectionController !== undefined) { if (this._options.multipleSelectionSupport) { this.view.domNode.setAttribute('aria-multiselectable', 'true'); } else { this.view.domNode.removeAttribute('aria-multiselectable'); } } this.mouseController.updateOptions(optionsUpdate); this.keyboardController?.updateOptions(optionsUpdate); this.view.updateOptions(optionsUpdate); } get options(): IListOptions<T> { return this._options; } splice(start: number, deleteCount: number, elements: readonly T[] = []): void { if (start < 0 || start > this.view.length) { throw new ListError(this.user, `Invalid start index: ${start}`); } if (deleteCount < 0) { throw new ListError(this.user, `Invalid delete count: ${deleteCount}`); } if (deleteCount === 0 && elements.length === 0) { return; } this.eventBufferer.bufferEvents(() => this.spliceable.splice(start, deleteCount, elements)); } updateWidth(index: number): void { this.view.updateWidth(index); } updateElementHeight(index: number, size: number): void { this.view.updateElementHeight(index, size, null); } rerender(): void { this.view.rerender(); } element(index: number): T { return this.view.element(index); } indexOf(element: T): number { return this.view.indexOf(element); } get length(): number { return this.view.length; } get contentHeight(): number { return this.view.contentHeight; } get onDidChangeContentHeight(): Event<number> { return this.view.onDidChangeContentHeight; } get scrollTop(): number { return this.view.getScrollTop(); } set scrollTop(scrollTop: number) { this.view.setScrollTop(scrollTop); } get scrollLeft(): number { return this.view.getScrollLeft(); } set scrollLeft(scrollLeft: number) { this.view.setScrollLeft(scrollLeft); } get scrollHeight(): number { return this.view.scrollHeight; } get renderHeight(): number { return this.view.renderHeight; } get firstVisibleIndex(): number { return this.view.firstVisibleIndex; } get lastVisibleIndex(): number { return this.view.lastVisibleIndex; } get ariaLabel(): string { return this._ariaLabel; } set ariaLabel(value: string) { this._ariaLabel = value; this.view.domNode.setAttribute('aria-label', value); } domFocus(): void { this.view.domNode.focus({ preventScroll: true }); } layout(height?: number, width?: number): void { this.view.layout(height, width); } triggerTypeNavigation(): void { this.typeNavigationController?.trigger(); } setSelection(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this.selection.set(indexes, browserEvent); } getSelection(): number[] { return this.selection.get(); } getSelectedElements(): T[] { return this.getSelection().map(i => this.view.element(i)); } setAnchor(index: number | undefined): void { if (typeof index === 'undefined') { this.anchor.set([]); return; } if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } this.anchor.set([index]); } getAnchor(): number | undefined { return firstOrDefault(this.anchor.get(), undefined); } getAnchorElement(): T | undefined { const anchor = this.getAnchor(); return typeof anchor === 'undefined' ? undefined : this.element(anchor); } setFocus(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this.focus.set(indexes, browserEvent); } focusNext(n = 1, loop = false, browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const focus = this.focus.get(); const index = this.findNextIndex(focus.length > 0 ? focus[0] + n : 0, loop, filter); if (index > -1) { this.setFocus([index], browserEvent); } } focusPrevious(n = 1, loop = false, browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const focus = this.focus.get(); const index = this.findPreviousIndex(focus.length > 0 ? focus[0] - n : 0, loop, filter); if (index > -1) { this.setFocus([index], browserEvent); } } async focusNextPage(browserEvent?: UIEvent, filter?: (element: T) => boolean): Promise<void> { let lastPageIndex = this.view.indexAt(this.view.getScrollTop() + this.view.renderHeight); lastPageIndex = lastPageIndex === 0 ? 0 : lastPageIndex - 1; const currentlyFocusedElementIndex = this.getFocus()[0]; if (currentlyFocusedElementIndex !== lastPageIndex && (currentlyFocusedElementIndex === undefined || lastPageIndex > currentlyFocusedElementIndex)) { const lastGoodPageIndex = this.findPreviousIndex(lastPageIndex, false, filter); if (lastGoodPageIndex > -1 && currentlyFocusedElementIndex !== lastGoodPageIndex) { this.setFocus([lastGoodPageIndex], browserEvent); } else { this.setFocus([lastPageIndex], browserEvent); } } else { const previousScrollTop = this.view.getScrollTop(); let nextpageScrollTop = previousScrollTop + this.view.renderHeight; if (lastPageIndex > currentlyFocusedElementIndex) { // scroll last page element to the top only if the last page element is below the focused element nextpageScrollTop -= this.view.elementHeight(lastPageIndex); } this.view.setScrollTop(nextpageScrollTop); if (this.view.getScrollTop() !== previousScrollTop) { this.setFocus([]); // Let the scroll event listener run await timeout(0); await this.focusNextPage(browserEvent, filter); } } } async focusPreviousPage(browserEvent?: UIEvent, filter?: (element: T) => boolean): Promise<void> { let firstPageIndex: number; const scrollTop = this.view.getScrollTop(); if (scrollTop === 0) { firstPageIndex = this.view.indexAt(scrollTop); } else { firstPageIndex = this.view.indexAfter(scrollTop - 1); } const currentlyFocusedElementIndex = this.getFocus()[0]; if (currentlyFocusedElementIndex !== firstPageIndex && (currentlyFocusedElementIndex === undefined || currentlyFocusedElementIndex >= firstPageIndex)) { const firstGoodPageIndex = this.findNextIndex(firstPageIndex, false, filter); if (firstGoodPageIndex > -1 && currentlyFocusedElementIndex !== firstGoodPageIndex) { this.setFocus([firstGoodPageIndex], browserEvent); } else { this.setFocus([firstPageIndex], browserEvent); } } else { const previousScrollTop = scrollTop; this.view.setScrollTop(scrollTop - this.view.renderHeight); if (this.view.getScrollTop() !== previousScrollTop) { this.setFocus([]); // Let the scroll event listener run await timeout(0); await this.focusPreviousPage(browserEvent, filter); } } } focusLast(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const index = this.findPreviousIndex(this.length - 1, false, filter); if (index > -1) { this.setFocus([index], browserEvent); } } focusFirst(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { this.focusNth(0, browserEvent, filter); } focusNth(n: number, browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const index = this.findNextIndex(n, false, filter); if (index > -1) { this.setFocus([index], browserEvent); } } private findNextIndex(index: number, loop = false, filter?: (element: T) => boolean): number { for (let i = 0; i < this.length; i++) { if (index >= this.length && !loop) { return -1; } index = index % this.length; if (!filter || filter(this.element(index))) { return index; } index++; } return -1; } private findPreviousIndex(index: number, loop = false, filter?: (element: T) => boolean): number { for (let i = 0; i < this.length; i++) { if (index < 0 && !loop) { return -1; } index = (this.length + (index % this.length)) % this.length; if (!filter || filter(this.element(index))) { return index; } index--; } return -1; } getFocus(): number[] { return this.focus.get(); } getFocusedElements(): T[] { return this.getFocus().map(i => this.view.element(i)); } reveal(index: number, relativeTop?: number): void { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } const scrollTop = this.view.getScrollTop(); const elementTop = this.view.elementTop(index); const elementHeight = this.view.elementHeight(index); if (isNumber(relativeTop)) { // y = mx + b const m = elementHeight - this.view.renderHeight; this.view.setScrollTop(m * clamp(relativeTop, 0, 1) + elementTop); } else { const viewItemBottom = elementTop + elementHeight; const scrollBottom = scrollTop + this.view.renderHeight; if (elementTop < scrollTop && viewItemBottom >= scrollBottom) { // The element is already overflowing the viewport, no-op } else if (elementTop < scrollTop || (viewItemBottom >= scrollBottom && elementHeight >= this.view.renderHeight)) { this.view.setScrollTop(elementTop); } else if (viewItemBottom >= scrollBottom) { this.view.setScrollTop(viewItemBottom - this.view.renderHeight); } } } /** * Returns the relative position of an element rendered in the list. * Returns `null` if the element isn't *entirely* in the visible viewport. */ getRelativeTop(index: number): number | null { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } const scrollTop = this.view.getScrollTop(); const elementTop = this.view.elementTop(index); const elementHeight = this.view.elementHeight(index); if (elementTop < scrollTop || elementTop + elementHeight > scrollTop + this.view.renderHeight) { return null; } // y = mx + b const m = elementHeight - this.view.renderHeight; return Math.abs((scrollTop - elementTop) / m); } isDOMFocused(): boolean { return this.view.domNode === document.activeElement; } getHTMLElement(): HTMLElement { return this.view.domNode; } getElementID(index: number): string { return this.view.getElementDomId(index); } style(styles: IListStyles): void { this.styleController.style(styles); } private toListEvent({ indexes, browserEvent }: ITraitChangeEvent) { return { indexes, elements: indexes.map(i => this.view.element(i)), browserEvent }; } private _onFocusChange(): void { const focus = this.focus.get(); this.view.domNode.classList.toggle('element-focused', focus.length > 0); this.onDidChangeActiveDescendant(); } private onDidChangeActiveDescendant(): void { const focus = this.focus.get(); if (focus.length > 0) { let id: string | undefined; if (this.accessibilityProvider?.getActiveDescendantId) { id = this.accessibilityProvider.getActiveDescendantId(this.view.element(focus[0])); } this.view.domNode.setAttribute('aria-activedescendant', id || this.view.getElementDomId(focus[0])); } else { this.view.domNode.removeAttribute('aria-activedescendant'); } } private _onSelectionChange(): void { const selection = this.selection.get(); this.view.domNode.classList.toggle('selection-none', selection.length === 0); this.view.domNode.classList.toggle('selection-single', selection.length === 1); this.view.domNode.classList.toggle('selection-multiple', selection.length > 1); } dispose(): void { this._onDidDispose.fire(); this.disposables.dispose(); this._onDidDispose.dispose(); } }
src/vs/base/browser/ui/list/listWidget.ts
1
https://github.com/microsoft/vscode/commit/f078e6db483250957314c56c3b12e23dae03d351
[ 0.9985872507095337, 0.13698020577430725, 0.00016130029689520597, 0.00017545715672895312, 0.3281533122062683 ]
{ "id": 2, "code_window": [ "\n", "\t\tif (this.isSelectionChangeEvent(e)) {\n", "\t\t\treturn;\n", "\t\t}\n", "\n", "\t\tconst focus = this.list.getFocus();\n", "\t\tthis.list.setSelection(focus, e.browserEvent);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\t\tif (e.browserEvent.defaultPrevented) {\n", "\t\t\treturn;\n", "\t\t}\n", "\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "add", "edit_start_line_idx": 723 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import TypeScriptServiceClientHost from '../typeScriptServiceClientHost'; import { ActiveJsTsEditorTracker } from '../utils/activeJsTsEditorTracker'; import { Lazy } from '../utils/lazy'; import { openProjectConfigForFile, ProjectType } from '../utils/tsconfig'; import { Command } from './commandManager'; export class TypeScriptGoToProjectConfigCommand implements Command { public readonly id = 'typescript.goToProjectConfig'; public constructor( private readonly activeJsTsEditorTracker: ActiveJsTsEditorTracker, private readonly lazyClientHost: Lazy<TypeScriptServiceClientHost>, ) { } public execute() { const editor = this.activeJsTsEditorTracker.activeJsTsEditor; if (editor) { openProjectConfigForFile(ProjectType.TypeScript, this.lazyClientHost.value.serviceClient, editor.document.uri); } } } export class JavaScriptGoToProjectConfigCommand implements Command { public readonly id = 'javascript.goToProjectConfig'; public constructor( private readonly activeJsTsEditorTracker: ActiveJsTsEditorTracker, private readonly lazyClientHost: Lazy<TypeScriptServiceClientHost>, ) { } public execute() { const editor = this.activeJsTsEditorTracker.activeJsTsEditor; if (editor) { openProjectConfigForFile(ProjectType.JavaScript, this.lazyClientHost.value.serviceClient, editor.document.uri); } } }
extensions/typescript-language-features/src/commands/goToProjectConfiguration.ts
0
https://github.com/microsoft/vscode/commit/f078e6db483250957314c56c3b12e23dae03d351
[ 0.00017658830620348454, 0.0001725595648167655, 0.00016839081945363432, 0.0001724851899780333, 0.000003411608531678212 ]
{ "id": 2, "code_window": [ "\n", "\t\tif (this.isSelectionChangeEvent(e)) {\n", "\t\t\treturn;\n", "\t\t}\n", "\n", "\t\tconst focus = this.list.getFocus();\n", "\t\tthis.list.setSelection(focus, e.browserEvent);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\t\tif (e.browserEvent.defaultPrevented) {\n", "\t\t\treturn;\n", "\t\t}\n", "\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "add", "edit_start_line_idx": 723 }
# --------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------------------------------- builtin autoload -Uz add-zsh-hook # Prevent the script recursing when setting up if [ -n "$VSCODE_SHELL_INTEGRATION" ]; then ZDOTDIR=$USER_ZDOTDIR builtin return fi # This variable allows the shell to both detect that VS Code's shell integration is enabled as well # as disable it by unsetting the variable. VSCODE_SHELL_INTEGRATION=1 # By default, zsh will set the $HISTFILE to the $ZDOTDIR location automatically. In the case of the # shell integration being injected, this means that the terminal will use a different history file # to other terminals. To fix this issue, set $HISTFILE back to the default location before ~/.zshrc # is called as that may depend upon the value. if [[ "$VSCODE_INJECTION" == "1" ]]; then HISTFILE=$USER_ZDOTDIR/.zsh_history fi # Only fix up ZDOTDIR if shell integration was injected (not manually installed) and has not been called yet if [[ "$VSCODE_INJECTION" == "1" ]]; then if [[ $options[norcs] = off && -f $USER_ZDOTDIR/.zshrc ]]; then VSCODE_ZDOTDIR=$ZDOTDIR ZDOTDIR=$USER_ZDOTDIR # A user's custom HISTFILE location might be set when their .zshrc file is sourced below . $USER_ZDOTDIR/.zshrc fi fi # Shell integration was disabled by the shell, exit without warning assuming either the shell has # explicitly disabled shell integration as it's incompatible or it implements the protocol. if [ -z "$VSCODE_SHELL_INTEGRATION" ]; then builtin return fi # The property (P) and command (E) codes embed values which require escaping. # Backslashes are doubled. Non-alphanumeric characters are converted to escaped hex. __vsc_escape_value() { builtin emulate -L zsh # Process text byte by byte, not by codepoint. builtin local LC_ALL=C str="$1" i byte token out='' for (( i = 0; i < ${#str}; ++i )); do byte="${str:$i:1}" # Backslashes must be doubled. if [ "$byte" = "\\" ]; then token="\\\\" # Conservatively pass alphanumerics through. elif [[ "$byte" == [0-9A-Za-z] ]]; then token="$byte" # Hex-encode anything else. # (Importantly including: semicolon, newline, and control chars). else token="\\x${(l:2::0:)$(( [##16] #byte ))}" # | | | |/|/ |_____| # | | | | | | # left-pad --+ | | | | +- the byte value of the character # two digits --+ | | +------- in hexadecimal # with '0' -------+ +--------- with no prefix fi out+="$token" done builtin print -r "$out" } __vsc_in_command_execution="1" __vsc_current_command="" __vsc_prompt_start() { builtin printf '\e]633;A\a' } __vsc_prompt_end() { builtin printf '\e]633;B\a' } __vsc_update_cwd() { builtin printf '\e]633;P;Cwd=%s\a' "$(__vsc_escape_value "${PWD}")" } __vsc_command_output_start() { builtin printf '\e]633;C\a' builtin printf '\e]633;E;%s\a' "$(__vsc_escape_value "${__vsc_current_command}")" } __vsc_continuation_start() { builtin printf '\e]633;F\a' } __vsc_continuation_end() { builtin printf '\e]633;G\a' } __vsc_right_prompt_start() { builtin printf '\e]633;H\a' } __vsc_right_prompt_end() { builtin printf '\e]633;I\a' } __vsc_command_complete() { if [[ "$__vsc_current_command" == "" ]]; then builtin printf '\e]633;D\a' else builtin printf '\e]633;D;%s\a' "$__vsc_status" fi __vsc_update_cwd } if [[ -o NOUNSET ]]; then if [ -z "${RPROMPT-}" ]; then RPROMPT="" fi fi __vsc_update_prompt() { __vsc_prior_prompt="$PS1" __vsc_prior_prompt2="$PS2" __vsc_in_command_execution="" PS1="%{$(__vsc_prompt_start)%}$PS1%{$(__vsc_prompt_end)%}" PS2="%{$(__vsc_continuation_start)%}$PS2%{$(__vsc_continuation_end)%}" if [ -n "$RPROMPT" ]; then __vsc_prior_rprompt="$RPROMPT" RPROMPT="%{$(__vsc_right_prompt_start)%}$RPROMPT%{$(__vsc_right_prompt_end)%}" fi } __vsc_precmd() { local __vsc_status="$?" if [ -z "${__vsc_in_command_execution-}" ]; then # not in command execution __vsc_command_output_start fi __vsc_command_complete "$__vsc_status" __vsc_current_command="" # in command execution if [ -n "$__vsc_in_command_execution" ]; then # non null __vsc_update_prompt fi } __vsc_preexec() { PS1="$__vsc_prior_prompt" PS2="$__vsc_prior_prompt2" if [ -n "$RPROMPT" ]; then RPROMPT="$__vsc_prior_rprompt" fi __vsc_in_command_execution="1" __vsc_current_command=$1 __vsc_command_output_start } add-zsh-hook precmd __vsc_precmd add-zsh-hook preexec __vsc_preexec if [[ $options[login] = off && $USER_ZDOTDIR != $VSCODE_ZDOTDIR ]]; then ZDOTDIR=$USER_ZDOTDIR fi
src/vs/workbench/contrib/terminal/browser/media/shellIntegration-rc.zsh
0
https://github.com/microsoft/vscode/commit/f078e6db483250957314c56c3b12e23dae03d351
[ 0.0001746583729982376, 0.00016822348698042333, 0.00016415758000221103, 0.00016781908925622702, 0.0000022371466457116185 ]
{ "id": 2, "code_window": [ "\n", "\t\tif (this.isSelectionChangeEvent(e)) {\n", "\t\t\treturn;\n", "\t\t}\n", "\n", "\t\tconst focus = this.list.getFocus();\n", "\t\tthis.list.setSelection(focus, e.browserEvent);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\t\tif (e.browserEvent.defaultPrevented) {\n", "\t\t\treturn;\n", "\t\t}\n", "\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "add", "edit_start_line_idx": 723 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { RawContextKey } from 'vs/platform/contextkey/common/contextkey'; export const InSearchEditor = new RawContextKey<boolean>('inSearchEditor', false); export const SearchEditorScheme = 'search-editor'; export const SearchEditorWorkingCopyTypeId = 'search/editor'; export const SearchEditorFindMatchClass = 'searchEditorFindMatch'; export const SearchEditorID = 'workbench.editor.searchEditor'; export const OpenNewEditorCommandId = 'search.action.openNewEditor'; export const OpenEditorCommandId = 'search.action.openEditor'; export const ToggleSearchEditorContextLinesCommandId = 'toggleSearchEditorContextLines'; export const SearchEditorInputTypeId = 'workbench.editorinputs.searchEditorInput';
src/vs/workbench/contrib/searchEditor/browser/constants.ts
0
https://github.com/microsoft/vscode/commit/f078e6db483250957314c56c3b12e23dae03d351
[ 0.0001765576598700136, 0.00017065669817384332, 0.00016656015941407531, 0.00016885227523744106, 0.000004276249001122778 ]
{ "id": 4, "code_window": [ "\t\t\treturn;\n", "\t\t}\n", "\n", "\t\tconst node = e.element;\n", "\n", "\t\tif (!node) {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (e.browserEvent.defaultPrevented) {\n", "\t\t\treturn;\n", "\t\t}\n", "\n" ], "file_path": "src/vs/base/browser/ui/tree/abstractTree.ts", "type": "add", "edit_start_line_idx": 1000 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IDragAndDropData } from 'vs/base/browser/dnd'; import { createStyleSheet, Dimension, EventHelper } from 'vs/base/browser/dom'; import { DomEmitter } from 'vs/base/browser/event'; import { IKeyboardEvent, StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { Gesture } from 'vs/base/browser/touch'; import { alert, AriaRole } from 'vs/base/browser/ui/aria/aria'; import { CombinedSpliceable } from 'vs/base/browser/ui/list/splice'; import { ScrollableElementChangeOptions } from 'vs/base/browser/ui/scrollbar/scrollableElementOptions'; import { binarySearch, firstOrDefault, range } from 'vs/base/common/arrays'; import { timeout } from 'vs/base/common/async'; import { Color } from 'vs/base/common/color'; import { memoize } from 'vs/base/common/decorators'; import { Emitter, Event, EventBufferer } from 'vs/base/common/event'; import { matchesPrefix } from 'vs/base/common/filters'; import { KeyCode } from 'vs/base/common/keyCodes'; import { DisposableStore, dispose, IDisposable } from 'vs/base/common/lifecycle'; import { clamp } from 'vs/base/common/numbers'; import { mixin } from 'vs/base/common/objects'; import * as platform from 'vs/base/common/platform'; import { ScrollbarVisibility, ScrollEvent } from 'vs/base/common/scrollable'; import { ISpliceable } from 'vs/base/common/sequence'; import { IThemable } from 'vs/base/common/styler'; import { isNumber } from 'vs/base/common/types'; import 'vs/css!./list'; import { IIdentityProvider, IKeyboardNavigationDelegate, IKeyboardNavigationLabelProvider, IListContextMenuEvent, IListDragAndDrop, IListDragOverReaction, IListEvent, IListGestureEvent, IListMouseEvent, IListRenderer, IListTouchEvent, IListVirtualDelegate, ListError } from './list'; import { IListViewAccessibilityProvider, IListViewDragAndDrop, IListViewOptions, IListViewOptionsUpdate, ListView } from './listView'; interface ITraitChangeEvent { indexes: number[]; browserEvent?: UIEvent; } type ITraitTemplateData = HTMLElement; interface IRenderedContainer { templateData: ITraitTemplateData; index: number; } class TraitRenderer<T> implements IListRenderer<T, ITraitTemplateData> { private renderedElements: IRenderedContainer[] = []; constructor(private trait: Trait<T>) { } get templateId(): string { return `template:${this.trait.name}`; } renderTemplate(container: HTMLElement): ITraitTemplateData { return container; } renderElement(element: T, index: number, templateData: ITraitTemplateData): void { const renderedElementIndex = this.renderedElements.findIndex(el => el.templateData === templateData); if (renderedElementIndex >= 0) { const rendered = this.renderedElements[renderedElementIndex]; this.trait.unrender(templateData); rendered.index = index; } else { const rendered = { index, templateData }; this.renderedElements.push(rendered); } this.trait.renderIndex(index, templateData); } splice(start: number, deleteCount: number, insertCount: number): void { const rendered: IRenderedContainer[] = []; for (const renderedElement of this.renderedElements) { if (renderedElement.index < start) { rendered.push(renderedElement); } else if (renderedElement.index >= start + deleteCount) { rendered.push({ index: renderedElement.index + insertCount - deleteCount, templateData: renderedElement.templateData }); } } this.renderedElements = rendered; } renderIndexes(indexes: number[]): void { for (const { index, templateData } of this.renderedElements) { if (indexes.indexOf(index) > -1) { this.trait.renderIndex(index, templateData); } } } disposeTemplate(templateData: ITraitTemplateData): void { const index = this.renderedElements.findIndex(el => el.templateData === templateData); if (index < 0) { return; } this.renderedElements.splice(index, 1); } } class Trait<T> implements ISpliceable<boolean>, IDisposable { private length = 0; private indexes: number[] = []; private sortedIndexes: number[] = []; private readonly _onChange = new Emitter<ITraitChangeEvent>(); readonly onChange: Event<ITraitChangeEvent> = this._onChange.event; get name(): string { return this._trait; } @memoize get renderer(): TraitRenderer<T> { return new TraitRenderer<T>(this); } constructor(private _trait: string) { } splice(start: number, deleteCount: number, elements: boolean[]): void { deleteCount = Math.max(0, Math.min(deleteCount, this.length - start)); const diff = elements.length - deleteCount; const end = start + deleteCount; const sortedIndexes = [ ...this.sortedIndexes.filter(i => i < start), ...elements.map((hasTrait, i) => hasTrait ? i + start : -1).filter(i => i !== -1), ...this.sortedIndexes.filter(i => i >= end).map(i => i + diff) ]; const length = this.length + diff; if (this.sortedIndexes.length > 0 && sortedIndexes.length === 0 && length > 0) { const first = this.sortedIndexes.find(index => index >= start) ?? length - 1; sortedIndexes.push(Math.min(first, length - 1)); } this.renderer.splice(start, deleteCount, elements.length); this._set(sortedIndexes, sortedIndexes); this.length = length; } renderIndex(index: number, container: HTMLElement): void { container.classList.toggle(this._trait, this.contains(index)); } unrender(container: HTMLElement): void { container.classList.remove(this._trait); } /** * Sets the indexes which should have this trait. * * @param indexes Indexes which should have this trait. * @return The old indexes which had this trait. */ set(indexes: number[], browserEvent?: UIEvent): number[] { return this._set(indexes, [...indexes].sort(numericSort), browserEvent); } private _set(indexes: number[], sortedIndexes: number[], browserEvent?: UIEvent): number[] { const result = this.indexes; const sortedResult = this.sortedIndexes; this.indexes = indexes; this.sortedIndexes = sortedIndexes; const toRender = disjunction(sortedResult, indexes); this.renderer.renderIndexes(toRender); this._onChange.fire({ indexes, browserEvent }); return result; } get(): number[] { return this.indexes; } contains(index: number): boolean { return binarySearch(this.sortedIndexes, index, numericSort) >= 0; } dispose() { dispose(this._onChange); } } class SelectionTrait<T> extends Trait<T> { constructor(private setAriaSelected: boolean) { super('selected'); } override renderIndex(index: number, container: HTMLElement): void { super.renderIndex(index, container); if (this.setAriaSelected) { if (this.contains(index)) { container.setAttribute('aria-selected', 'true'); } else { container.setAttribute('aria-selected', 'false'); } } } } /** * The TraitSpliceable is used as a util class to be able * to preserve traits across splice calls, given an identity * provider. */ class TraitSpliceable<T> implements ISpliceable<T> { constructor( private trait: Trait<T>, private view: ListView<T>, private identityProvider?: IIdentityProvider<T> ) { } splice(start: number, deleteCount: number, elements: T[]): void { if (!this.identityProvider) { return this.trait.splice(start, deleteCount, elements.map(() => false)); } const pastElementsWithTrait = this.trait.get().map(i => this.identityProvider!.getId(this.view.element(i)).toString()); const elementsWithTrait = elements.map(e => pastElementsWithTrait.indexOf(this.identityProvider!.getId(e).toString()) > -1); this.trait.splice(start, deleteCount, elementsWithTrait); } } export function isInputElement(e: HTMLElement): boolean { return e.tagName === 'INPUT' || e.tagName === 'TEXTAREA'; } export function isMonacoEditor(e: HTMLElement): boolean { if (e.classList.contains('monaco-editor')) { return true; } if (e.classList.contains('monaco-list')) { return false; } if (!e.parentElement) { return false; } return isMonacoEditor(e.parentElement); } export function isButton(e: HTMLElement): boolean { if ((e.tagName === 'A' && e.classList.contains('monaco-button')) || (e.tagName === 'DIV' && e.classList.contains('monaco-button-dropdown'))) { return true; } if (e.classList.contains('monaco-list')) { return false; } if (!e.parentElement) { return false; } return isButton(e.parentElement); } class KeyboardController<T> implements IDisposable { private readonly disposables = new DisposableStore(); private readonly multipleSelectionDisposables = new DisposableStore(); @memoize private get onKeyDown(): Event.IChainableEvent<StandardKeyboardEvent> { return this.disposables.add(Event.chain(this.disposables.add(new DomEmitter(this.view.domNode, 'keydown')).event) .filter(e => !isInputElement(e.target as HTMLElement)) .map(e => new StandardKeyboardEvent(e))); } constructor( private list: List<T>, private view: ListView<T>, options: IListOptions<T> ) { this.onKeyDown.filter(e => e.keyCode === KeyCode.Enter).on(this.onEnter, this, this.disposables); this.onKeyDown.filter(e => e.keyCode === KeyCode.UpArrow).on(this.onUpArrow, this, this.disposables); this.onKeyDown.filter(e => e.keyCode === KeyCode.DownArrow).on(this.onDownArrow, this, this.disposables); this.onKeyDown.filter(e => e.keyCode === KeyCode.PageUp).on(this.onPageUpArrow, this, this.disposables); this.onKeyDown.filter(e => e.keyCode === KeyCode.PageDown).on(this.onPageDownArrow, this, this.disposables); this.onKeyDown.filter(e => e.keyCode === KeyCode.Escape).on(this.onEscape, this, this.disposables); if (options.multipleSelectionSupport !== false) { this.onKeyDown.filter(e => (platform.isMacintosh ? e.metaKey : e.ctrlKey) && e.keyCode === KeyCode.KeyA).on(this.onCtrlA, this, this.multipleSelectionDisposables); } } updateOptions(optionsUpdate: IListOptionsUpdate): void { if (optionsUpdate.multipleSelectionSupport !== undefined) { this.multipleSelectionDisposables.clear(); if (optionsUpdate.multipleSelectionSupport) { this.onKeyDown.filter(e => (platform.isMacintosh ? e.metaKey : e.ctrlKey) && e.keyCode === KeyCode.KeyA).on(this.onCtrlA, this, this.multipleSelectionDisposables); } } } private onEnter(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.setSelection(this.list.getFocus(), e.browserEvent); } private onUpArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusPrevious(1, false, e.browserEvent); const el = this.list.getFocus()[0]; this.list.setAnchor(el); this.list.reveal(el); this.view.domNode.focus(); } private onDownArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusNext(1, false, e.browserEvent); const el = this.list.getFocus()[0]; this.list.setAnchor(el); this.list.reveal(el); this.view.domNode.focus(); } private onPageUpArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusPreviousPage(e.browserEvent); const el = this.list.getFocus()[0]; this.list.setAnchor(el); this.list.reveal(el); this.view.domNode.focus(); } private onPageDownArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusNextPage(e.browserEvent); const el = this.list.getFocus()[0]; this.list.setAnchor(el); this.list.reveal(el); this.view.domNode.focus(); } private onCtrlA(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.setSelection(range(this.list.length), e.browserEvent); this.list.setAnchor(undefined); this.view.domNode.focus(); } private onEscape(e: StandardKeyboardEvent): void { if (this.list.getSelection().length) { e.preventDefault(); e.stopPropagation(); this.list.setSelection([], e.browserEvent); this.list.setAnchor(undefined); this.view.domNode.focus(); } } dispose() { this.disposables.dispose(); this.multipleSelectionDisposables.dispose(); } } export enum TypeNavigationMode { Automatic, Trigger } enum TypeNavigationControllerState { Idle, Typing } export const DefaultKeyboardNavigationDelegate = new class implements IKeyboardNavigationDelegate { mightProducePrintableCharacter(event: IKeyboardEvent): boolean { if (event.ctrlKey || event.metaKey || event.altKey) { return false; } return (event.keyCode >= KeyCode.KeyA && event.keyCode <= KeyCode.KeyZ) || (event.keyCode >= KeyCode.Digit0 && event.keyCode <= KeyCode.Digit9) || (event.keyCode >= KeyCode.Numpad0 && event.keyCode <= KeyCode.Numpad9) || (event.keyCode >= KeyCode.Semicolon && event.keyCode <= KeyCode.Quote); } }; class TypeNavigationController<T> implements IDisposable { private enabled = false; private state: TypeNavigationControllerState = TypeNavigationControllerState.Idle; private mode = TypeNavigationMode.Automatic; private triggered = false; private previouslyFocused = -1; private readonly enabledDisposables = new DisposableStore(); private readonly disposables = new DisposableStore(); constructor( private list: List<T>, private view: ListView<T>, private keyboardNavigationLabelProvider: IKeyboardNavigationLabelProvider<T>, private keyboardNavigationEventFilter: IKeyboardNavigationEventFilter, private delegate: IKeyboardNavigationDelegate ) { this.updateOptions(list.options); } updateOptions(options: IListOptions<T>): void { if (options.typeNavigationEnabled ?? true) { this.enable(); } else { this.disable(); } this.mode = options.typeNavigationMode ?? TypeNavigationMode.Automatic; } trigger(): void { this.triggered = !this.triggered; } private enable(): void { if (this.enabled) { return; } let typing = false; const onChar = this.enabledDisposables.add(Event.chain(this.enabledDisposables.add(new DomEmitter(this.view.domNode, 'keydown')).event)) .filter(e => !isInputElement(e.target as HTMLElement)) .filter(() => this.mode === TypeNavigationMode.Automatic || this.triggered) .map(event => new StandardKeyboardEvent(event)) .filter(e => typing || this.keyboardNavigationEventFilter(e)) .filter(e => this.delegate.mightProducePrintableCharacter(e)) .forEach(e => EventHelper.stop(e, true)) .map(event => event.browserEvent.key) .event; const onClear = Event.debounce<string, null>(onChar, () => null, 800, undefined, undefined, this.enabledDisposables); const onInput = Event.reduce<string | null, string | null>(Event.any(onChar, onClear), (r, i) => i === null ? null : ((r || '') + i), undefined, this.enabledDisposables); onInput(this.onInput, this, this.enabledDisposables); onClear(this.onClear, this, this.enabledDisposables); onChar(() => typing = true, undefined, this.enabledDisposables); onClear(() => typing = false, undefined, this.enabledDisposables); this.enabled = true; this.triggered = false; } private disable(): void { if (!this.enabled) { return; } this.enabledDisposables.clear(); this.enabled = false; this.triggered = false; } private onClear(): void { const focus = this.list.getFocus(); if (focus.length > 0 && focus[0] === this.previouslyFocused) { // List: re-announce element on typing end since typed keys will interrupt aria label of focused element // Do not announce if there was a focus change at the end to prevent duplication https://github.com/microsoft/vscode/issues/95961 const ariaLabel = this.list.options.accessibilityProvider?.getAriaLabel(this.list.element(focus[0])); if (ariaLabel) { alert(ariaLabel); } } this.previouslyFocused = -1; } private onInput(word: string | null): void { if (!word) { this.state = TypeNavigationControllerState.Idle; this.triggered = false; return; } const focus = this.list.getFocus(); const start = focus.length > 0 ? focus[0] : 0; const delta = this.state === TypeNavigationControllerState.Idle ? 1 : 0; this.state = TypeNavigationControllerState.Typing; for (let i = 0; i < this.list.length; i++) { const index = (start + i + delta) % this.list.length; const label = this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(this.view.element(index)); const labelStr = label && label.toString(); if (typeof labelStr === 'undefined' || matchesPrefix(word, labelStr)) { this.previouslyFocused = start; this.list.setFocus([index]); this.list.reveal(index); return; } } } dispose() { this.disable(); this.enabledDisposables.dispose(); this.disposables.dispose(); } } class DOMFocusController<T> implements IDisposable { private readonly disposables = new DisposableStore(); constructor( private list: List<T>, private view: ListView<T> ) { const onKeyDown = this.disposables.add(Event.chain(this.disposables.add(new DomEmitter(view.domNode, 'keydown')).event)) .filter(e => !isInputElement(e.target as HTMLElement)) .map(e => new StandardKeyboardEvent(e)); onKeyDown.filter(e => e.keyCode === KeyCode.Tab && !e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey) .on(this.onTab, this, this.disposables); } private onTab(e: StandardKeyboardEvent): void { if (e.target !== this.view.domNode) { return; } const focus = this.list.getFocus(); if (focus.length === 0) { return; } const focusedDomElement = this.view.domElement(focus[0]); if (!focusedDomElement) { return; } const tabIndexElement = focusedDomElement.querySelector('[tabIndex]'); if (!tabIndexElement || !(tabIndexElement instanceof HTMLElement) || tabIndexElement.tabIndex === -1) { return; } const style = window.getComputedStyle(tabIndexElement); if (style.visibility === 'hidden' || style.display === 'none') { return; } e.preventDefault(); e.stopPropagation(); tabIndexElement.focus(); } dispose() { this.disposables.dispose(); } } export function isSelectionSingleChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return platform.isMacintosh ? event.browserEvent.metaKey : event.browserEvent.ctrlKey; } export function isSelectionRangeChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return event.browserEvent.shiftKey; } function isMouseRightClick(event: UIEvent): boolean { return event instanceof MouseEvent && event.button === 2; } const DefaultMultipleSelectionController = { isSelectionSingleChangeEvent, isSelectionRangeChangeEvent }; export class MouseController<T> implements IDisposable { private multipleSelectionController: IMultipleSelectionController<T> | undefined; private mouseSupport: boolean; private readonly disposables = new DisposableStore(); private _onPointer = new Emitter<IListMouseEvent<T>>(); readonly onPointer: Event<IListMouseEvent<T>> = this._onPointer.event; constructor(protected list: List<T>) { if (list.options.multipleSelectionSupport !== false) { this.multipleSelectionController = this.list.options.multipleSelectionController || DefaultMultipleSelectionController; } this.mouseSupport = typeof list.options.mouseSupport === 'undefined' || !!list.options.mouseSupport; if (this.mouseSupport) { list.onMouseDown(this.onMouseDown, this, this.disposables); list.onContextMenu(this.onContextMenu, this, this.disposables); list.onMouseDblClick(this.onDoubleClick, this, this.disposables); list.onTouchStart(this.onMouseDown, this, this.disposables); this.disposables.add(Gesture.addTarget(list.getHTMLElement())); } Event.any(list.onMouseClick, list.onMouseMiddleClick, list.onTap)(this.onViewPointer, this, this.disposables); } updateOptions(optionsUpdate: IListOptionsUpdate): void { if (optionsUpdate.multipleSelectionSupport !== undefined) { this.multipleSelectionController = undefined; if (optionsUpdate.multipleSelectionSupport) { this.multipleSelectionController = this.list.options.multipleSelectionController || DefaultMultipleSelectionController; } } } protected isSelectionSingleChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { if (!this.multipleSelectionController) { return false; } return this.multipleSelectionController.isSelectionSingleChangeEvent(event); } protected isSelectionRangeChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { if (!this.multipleSelectionController) { return false; } return this.multipleSelectionController.isSelectionRangeChangeEvent(event); } private isSelectionChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return this.isSelectionSingleChangeEvent(event) || this.isSelectionRangeChangeEvent(event); } private onMouseDown(e: IListMouseEvent<T> | IListTouchEvent<T>): void { if (isMonacoEditor(e.browserEvent.target as HTMLElement)) { return; } if (document.activeElement !== e.browserEvent.target) { this.list.domFocus(); } } private onContextMenu(e: IListContextMenuEvent<T>): void { if (isInputElement(e.browserEvent.target as HTMLElement) || isMonacoEditor(e.browserEvent.target as HTMLElement)) { return; } const focus = typeof e.index === 'undefined' ? [] : [e.index]; this.list.setFocus(focus, e.browserEvent); } protected onViewPointer(e: IListMouseEvent<T>): void { if (!this.mouseSupport) { return; } if (isInputElement(e.browserEvent.target as HTMLElement) || isMonacoEditor(e.browserEvent.target as HTMLElement)) { return; } const focus = e.index; if (typeof focus === 'undefined') { this.list.setFocus([], e.browserEvent); this.list.setSelection([], e.browserEvent); this.list.setAnchor(undefined); return; } if (this.isSelectionRangeChangeEvent(e)) { return this.changeSelection(e); } if (this.isSelectionChangeEvent(e)) { return this.changeSelection(e); } this.list.setFocus([focus], e.browserEvent); this.list.setAnchor(focus); if (!isMouseRightClick(e.browserEvent)) { this.list.setSelection([focus], e.browserEvent); } this._onPointer.fire(e); } protected onDoubleClick(e: IListMouseEvent<T>): void { if (isInputElement(e.browserEvent.target as HTMLElement) || isMonacoEditor(e.browserEvent.target as HTMLElement)) { return; } if (this.isSelectionChangeEvent(e)) { return; } const focus = this.list.getFocus(); this.list.setSelection(focus, e.browserEvent); } private changeSelection(e: IListMouseEvent<T> | IListTouchEvent<T>): void { const focus = e.index!; let anchor = this.list.getAnchor(); if (this.isSelectionRangeChangeEvent(e)) { if (typeof anchor === 'undefined') { const currentFocus = this.list.getFocus()[0]; anchor = currentFocus ?? focus; this.list.setAnchor(anchor); } const min = Math.min(anchor, focus); const max = Math.max(anchor, focus); const rangeSelection = range(min, max + 1); const selection = this.list.getSelection(); const contiguousRange = getContiguousRangeContaining(disjunction(selection, [anchor]), anchor); if (contiguousRange.length === 0) { return; } const newSelection = disjunction(rangeSelection, relativeComplement(selection, contiguousRange)); this.list.setSelection(newSelection, e.browserEvent); this.list.setFocus([focus], e.browserEvent); } else if (this.isSelectionSingleChangeEvent(e)) { const selection = this.list.getSelection(); const newSelection = selection.filter(i => i !== focus); this.list.setFocus([focus]); this.list.setAnchor(focus); if (selection.length === newSelection.length) { this.list.setSelection([...newSelection, focus], e.browserEvent); } else { this.list.setSelection(newSelection, e.browserEvent); } } } dispose() { this.disposables.dispose(); } } export interface IMultipleSelectionController<T> { isSelectionSingleChangeEvent(event: IListMouseEvent<T> | IListTouchEvent<T>): boolean; isSelectionRangeChangeEvent(event: IListMouseEvent<T> | IListTouchEvent<T>): boolean; } export interface IStyleController { style(styles: IListStyles): void; } export interface IListAccessibilityProvider<T> extends IListViewAccessibilityProvider<T> { getAriaLabel(element: T): string | null; getWidgetAriaLabel(): string; getWidgetRole?(): AriaRole; getAriaLevel?(element: T): number | undefined; onDidChangeActiveDescendant?: Event<void>; getActiveDescendantId?(element: T): string | undefined; } export class DefaultStyleController implements IStyleController { constructor(private styleElement: HTMLStyleElement, private selectorSuffix: string) { } style(styles: IListStyles): void { const suffix = this.selectorSuffix && `.${this.selectorSuffix}`; const content: string[] = []; if (styles.listBackground) { if (styles.listBackground.isOpaque()) { content.push(`.monaco-list${suffix} .monaco-list-rows { background: ${styles.listBackground}; }`); } else if (!platform.isMacintosh) { // subpixel AA doesn't exist in macOS console.warn(`List with id '${this.selectorSuffix}' was styled with a non-opaque background color. This will break sub-pixel antialiasing.`); } } if (styles.listFocusBackground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { background-color: ${styles.listFocusBackground}; }`); content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused:hover { background-color: ${styles.listFocusBackground}; }`); // overwrite :hover style in this case! } if (styles.listFocusForeground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { color: ${styles.listFocusForeground}; }`); } if (styles.listActiveSelectionBackground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { background-color: ${styles.listActiveSelectionBackground}; }`); content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected:hover { background-color: ${styles.listActiveSelectionBackground}; }`); // overwrite :hover style in this case! } if (styles.listActiveSelectionForeground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { color: ${styles.listActiveSelectionForeground}; }`); } if (styles.listActiveSelectionIconForeground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected .codicon { color: ${styles.listActiveSelectionIconForeground}; }`); } if (styles.listFocusAndSelectionOutline) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { outline-color: ${styles.listFocusAndSelectionOutline} !important; }`); } if (styles.listFocusAndSelectionBackground) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.selected.focused { background-color: ${styles.listFocusAndSelectionBackground}; } `); } if (styles.listFocusAndSelectionForeground) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.selected.focused { color: ${styles.listFocusAndSelectionForeground}; } `); } if (styles.listInactiveFocusForeground) { content.push(`.monaco-list${suffix} .monaco-list-row.focused { color: ${styles.listInactiveFocusForeground}; }`); content.push(`.monaco-list${suffix} .monaco-list-row.focused:hover { color: ${styles.listInactiveFocusForeground}; }`); // overwrite :hover style in this case! } if (styles.listInactiveSelectionIconForeground) { content.push(`.monaco-list${suffix} .monaco-list-row.focused .codicon { color: ${styles.listInactiveSelectionIconForeground}; }`); } if (styles.listInactiveFocusBackground) { content.push(`.monaco-list${suffix} .monaco-list-row.focused { background-color: ${styles.listInactiveFocusBackground}; }`); content.push(`.monaco-list${suffix} .monaco-list-row.focused:hover { background-color: ${styles.listInactiveFocusBackground}; }`); // overwrite :hover style in this case! } if (styles.listInactiveSelectionBackground) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { background-color: ${styles.listInactiveSelectionBackground}; }`); content.push(`.monaco-list${suffix} .monaco-list-row.selected:hover { background-color: ${styles.listInactiveSelectionBackground}; }`); // overwrite :hover style in this case! } if (styles.listInactiveSelectionForeground) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { color: ${styles.listInactiveSelectionForeground}; }`); } if (styles.listHoverBackground) { content.push(`.monaco-list${suffix}:not(.drop-target):not(.dragging) .monaco-list-row:hover:not(.selected):not(.focused) { background-color: ${styles.listHoverBackground}; }`); } if (styles.listHoverForeground) { content.push(`.monaco-list${suffix}:not(.drop-target):not(.dragging) .monaco-list-row:hover:not(.selected):not(.focused) { color: ${styles.listHoverForeground}; }`); } if (styles.listSelectionOutline) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { outline: 1px dotted ${styles.listSelectionOutline}; outline-offset: -1px; }`); } if (styles.listFocusOutline) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; } .monaco-workbench.context-menu-visible .monaco-list${suffix}.last-focused .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; } `); } if (styles.listInactiveFocusOutline) { content.push(`.monaco-list${suffix} .monaco-list-row.focused { outline: 1px dotted ${styles.listInactiveFocusOutline}; outline-offset: -1px; }`); } if (styles.listHoverOutline) { content.push(`.monaco-list${suffix} .monaco-list-row:hover { outline: 1px dashed ${styles.listHoverOutline}; outline-offset: -1px; }`); } if (styles.listDropBackground) { content.push(` .monaco-list${suffix}.drop-target, .monaco-list${suffix} .monaco-list-rows.drop-target, .monaco-list${suffix} .monaco-list-row.drop-target { background-color: ${styles.listDropBackground} !important; color: inherit !important; } `); } if (styles.tableColumnsBorder) { content.push(` .monaco-table > .monaco-split-view2, .monaco-table > .monaco-split-view2 .monaco-sash.vertical::before, .monaco-workbench:not(.reduce-motion) .monaco-table:hover > .monaco-split-view2, .monaco-workbench:not(.reduce-motion) .monaco-table:hover > .monaco-split-view2 .monaco-sash.vertical::before { border-color: ${styles.tableColumnsBorder}; } .monaco-workbench:not(.reduce-motion) .monaco-table > .monaco-split-view2, .monaco-workbench:not(.reduce-motion) .monaco-table > .monaco-split-view2 .monaco-sash.vertical::before { border-color: transparent; } `); } if (styles.tableOddRowsBackgroundColor) { content.push(` .monaco-table .monaco-list-row[data-parity=odd]:not(.focused):not(.selected):not(:hover) .monaco-table-tr, .monaco-table .monaco-list:not(:focus) .monaco-list-row[data-parity=odd].focused:not(.selected):not(:hover) .monaco-table-tr, .monaco-table .monaco-list:not(.focused) .monaco-list-row[data-parity=odd].focused:not(.selected):not(:hover) .monaco-table-tr { background-color: ${styles.tableOddRowsBackgroundColor}; } `); } this.styleElement.textContent = content.join('\n'); } } export interface IKeyboardNavigationEventFilter { (e: StandardKeyboardEvent): boolean; } export interface IListOptionsUpdate extends IListViewOptionsUpdate { readonly typeNavigationEnabled?: boolean; readonly typeNavigationMode?: TypeNavigationMode; readonly multipleSelectionSupport?: boolean; } export interface IListOptions<T> extends IListOptionsUpdate { readonly identityProvider?: IIdentityProvider<T>; readonly dnd?: IListDragAndDrop<T>; readonly keyboardNavigationLabelProvider?: IKeyboardNavigationLabelProvider<T>; readonly keyboardNavigationDelegate?: IKeyboardNavigationDelegate; readonly keyboardSupport?: boolean; readonly multipleSelectionController?: IMultipleSelectionController<T>; readonly styleController?: (suffix: string) => IStyleController; readonly accessibilityProvider?: IListAccessibilityProvider<T>; readonly keyboardNavigationEventFilter?: IKeyboardNavigationEventFilter; // list view options readonly useShadows?: boolean; readonly verticalScrollMode?: ScrollbarVisibility; readonly setRowLineHeight?: boolean; readonly setRowHeight?: boolean; readonly supportDynamicHeights?: boolean; readonly mouseSupport?: boolean; readonly horizontalScrolling?: boolean; readonly scrollByPage?: boolean; readonly additionalScrollHeight?: number; readonly transformOptimization?: boolean; readonly smoothScrolling?: boolean; readonly scrollableElementChangeOptions?: ScrollableElementChangeOptions; readonly alwaysConsumeMouseWheel?: boolean; readonly initialSize?: Dimension; } export interface IListStyles { listBackground?: Color; listFocusBackground?: Color; listFocusForeground?: Color; listActiveSelectionBackground?: Color; listActiveSelectionForeground?: Color; listActiveSelectionIconForeground?: Color; listFocusAndSelectionOutline?: Color; listFocusAndSelectionBackground?: Color; listFocusAndSelectionForeground?: Color; listInactiveSelectionBackground?: Color; listInactiveSelectionIconForeground?: Color; listInactiveSelectionForeground?: Color; listInactiveFocusForeground?: Color; listInactiveFocusBackground?: Color; listHoverBackground?: Color; listHoverForeground?: Color; listDropBackground?: Color; listFocusOutline?: Color; listInactiveFocusOutline?: Color; listSelectionOutline?: Color; listHoverOutline?: Color; treeIndentGuidesStroke?: Color; tableColumnsBorder?: Color; tableOddRowsBackgroundColor?: Color; } const defaultStyles: IListStyles = { listFocusBackground: Color.fromHex('#7FB0D0'), listActiveSelectionBackground: Color.fromHex('#0E639C'), listActiveSelectionForeground: Color.fromHex('#FFFFFF'), listActiveSelectionIconForeground: Color.fromHex('#FFFFFF'), listFocusAndSelectionOutline: Color.fromHex('#90C2F9'), listFocusAndSelectionBackground: Color.fromHex('#094771'), listFocusAndSelectionForeground: Color.fromHex('#FFFFFF'), listInactiveSelectionBackground: Color.fromHex('#3F3F46'), listInactiveSelectionIconForeground: Color.fromHex('#FFFFFF'), listHoverBackground: Color.fromHex('#2A2D2E'), listDropBackground: Color.fromHex('#383B3D'), treeIndentGuidesStroke: Color.fromHex('#a9a9a9'), tableColumnsBorder: Color.fromHex('#cccccc').transparent(0.2), tableOddRowsBackgroundColor: Color.fromHex('#cccccc').transparent(0.04) }; const DefaultOptions: IListOptions<any> = { keyboardSupport: true, mouseSupport: true, multipleSelectionSupport: true, dnd: { getDragURI() { return null; }, onDragStart(): void { }, onDragOver() { return false; }, drop() { } } }; // TODO@Joao: move these utils into a SortedArray class function getContiguousRangeContaining(range: number[], value: number): number[] { const index = range.indexOf(value); if (index === -1) { return []; } const result: number[] = []; let i = index - 1; while (i >= 0 && range[i] === value - (index - i)) { result.push(range[i--]); } result.reverse(); i = index; while (i < range.length && range[i] === value + (i - index)) { result.push(range[i++]); } return result; } /** * Given two sorted collections of numbers, returns the intersection * between them (OR). */ function disjunction(one: number[], other: number[]): number[] { const result: number[] = []; let i = 0, j = 0; while (i < one.length || j < other.length) { if (i >= one.length) { result.push(other[j++]); } else if (j >= other.length) { result.push(one[i++]); } else if (one[i] === other[j]) { result.push(one[i]); i++; j++; continue; } else if (one[i] < other[j]) { result.push(one[i++]); } else { result.push(other[j++]); } } return result; } /** * Given two sorted collections of numbers, returns the relative * complement between them (XOR). */ function relativeComplement(one: number[], other: number[]): number[] { const result: number[] = []; let i = 0, j = 0; while (i < one.length || j < other.length) { if (i >= one.length) { result.push(other[j++]); } else if (j >= other.length) { result.push(one[i++]); } else if (one[i] === other[j]) { i++; j++; continue; } else if (one[i] < other[j]) { result.push(one[i++]); } else { j++; } } return result; } const numericSort = (a: number, b: number) => a - b; class PipelineRenderer<T> implements IListRenderer<T, any> { constructor( private _templateId: string, private renderers: IListRenderer<any /* TODO@joao */, any>[] ) { } get templateId(): string { return this._templateId; } renderTemplate(container: HTMLElement): any[] { return this.renderers.map(r => r.renderTemplate(container)); } renderElement(element: T, index: number, templateData: any[], height: number | undefined): void { let i = 0; for (const renderer of this.renderers) { renderer.renderElement(element, index, templateData[i++], height); } } disposeElement(element: T, index: number, templateData: any[], height: number | undefined): void { let i = 0; for (const renderer of this.renderers) { renderer.disposeElement?.(element, index, templateData[i], height); i += 1; } } disposeTemplate(templateData: any[]): void { let i = 0; for (const renderer of this.renderers) { renderer.disposeTemplate(templateData[i++]); } } } class AccessibiltyRenderer<T> implements IListRenderer<T, HTMLElement> { templateId: string = 'a18n'; constructor(private accessibilityProvider: IListAccessibilityProvider<T>) { } renderTemplate(container: HTMLElement): HTMLElement { return container; } renderElement(element: T, index: number, container: HTMLElement): void { const ariaLabel = this.accessibilityProvider.getAriaLabel(element); if (ariaLabel) { container.setAttribute('aria-label', ariaLabel); } else { container.removeAttribute('aria-label'); } const ariaLevel = this.accessibilityProvider.getAriaLevel && this.accessibilityProvider.getAriaLevel(element); if (typeof ariaLevel === 'number') { container.setAttribute('aria-level', `${ariaLevel}`); } else { container.removeAttribute('aria-level'); } } disposeTemplate(templateData: any): void { // noop } } class ListViewDragAndDrop<T> implements IListViewDragAndDrop<T> { constructor(private list: List<T>, private dnd: IListDragAndDrop<T>) { } getDragElements(element: T): T[] { const selection = this.list.getSelectedElements(); const elements = selection.indexOf(element) > -1 ? selection : [element]; return elements; } getDragURI(element: T): string | null { return this.dnd.getDragURI(element); } getDragLabel?(elements: T[], originalEvent: DragEvent): string | undefined { if (this.dnd.getDragLabel) { return this.dnd.getDragLabel(elements, originalEvent); } return undefined; } onDragStart(data: IDragAndDropData, originalEvent: DragEvent): void { this.dnd.onDragStart?.(data, originalEvent); } onDragOver(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): boolean | IListDragOverReaction { return this.dnd.onDragOver(data, targetElement, targetIndex, originalEvent); } onDragLeave(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): void { this.dnd.onDragLeave?.(data, targetElement, targetIndex, originalEvent); } onDragEnd(originalEvent: DragEvent): void { this.dnd.onDragEnd?.(originalEvent); } drop(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): void { this.dnd.drop(data, targetElement, targetIndex, originalEvent); } } /** * The {@link List} is a virtual scrolling widget, built on top of the {@link ListView} * widget. * * Features: * - Customizable keyboard and mouse support * - Element traits: focus, selection, achor * - Accessibility support * - Touch support * - Performant template-based rendering * - Horizontal scrolling * - Variable element height support * - Dynamic element height support * - Drag-and-drop support */ export class List<T> implements ISpliceable<T>, IThemable, IDisposable { private focus = new Trait<T>('focused'); private selection: Trait<T>; private anchor = new Trait<T>('anchor'); private eventBufferer = new EventBufferer(); protected view: ListView<T>; private spliceable: ISpliceable<T>; private styleController: IStyleController; private typeNavigationController?: TypeNavigationController<T>; private accessibilityProvider?: IListAccessibilityProvider<T>; private keyboardController: KeyboardController<T> | undefined; private mouseController: MouseController<T>; private _ariaLabel: string = ''; protected readonly disposables = new DisposableStore(); @memoize get onDidChangeFocus(): Event<IListEvent<T>> { return Event.map(this.eventBufferer.wrapEvent(this.focus.onChange), e => this.toListEvent(e), this.disposables); } @memoize get onDidChangeSelection(): Event<IListEvent<T>> { return Event.map(this.eventBufferer.wrapEvent(this.selection.onChange), e => this.toListEvent(e), this.disposables); } get domId(): string { return this.view.domId; } get onDidScroll(): Event<ScrollEvent> { return this.view.onDidScroll; } get onMouseClick(): Event<IListMouseEvent<T>> { return this.view.onMouseClick; } get onMouseDblClick(): Event<IListMouseEvent<T>> { return this.view.onMouseDblClick; } get onMouseMiddleClick(): Event<IListMouseEvent<T>> { return this.view.onMouseMiddleClick; } get onPointer(): Event<IListMouseEvent<T>> { return this.mouseController.onPointer; } get onMouseUp(): Event<IListMouseEvent<T>> { return this.view.onMouseUp; } get onMouseDown(): Event<IListMouseEvent<T>> { return this.view.onMouseDown; } get onMouseOver(): Event<IListMouseEvent<T>> { return this.view.onMouseOver; } get onMouseMove(): Event<IListMouseEvent<T>> { return this.view.onMouseMove; } get onMouseOut(): Event<IListMouseEvent<T>> { return this.view.onMouseOut; } get onTouchStart(): Event<IListTouchEvent<T>> { return this.view.onTouchStart; } get onTap(): Event<IListGestureEvent<T>> { return this.view.onTap; } /** * Possible context menu trigger events: * - ContextMenu key * - Shift F10 * - Ctrl Option Shift M (macOS with VoiceOver) * - Mouse right click */ @memoize get onContextMenu(): Event<IListContextMenuEvent<T>> { let didJustPressContextMenuKey = false; const fromKeyDown = this.disposables.add(Event.chain(this.disposables.add(new DomEmitter(this.view.domNode, 'keydown')).event)) .map(e => new StandardKeyboardEvent(e)) .filter(e => didJustPressContextMenuKey = e.keyCode === KeyCode.ContextMenu || (e.shiftKey && e.keyCode === KeyCode.F10)) .map(e => EventHelper.stop(e, true)) .filter(() => false) .event as Event<any>; const fromKeyUp = this.disposables.add(Event.chain(this.disposables.add(new DomEmitter(this.view.domNode, 'keyup')).event)) .forEach(() => didJustPressContextMenuKey = false) .map(e => new StandardKeyboardEvent(e)) .filter(e => e.keyCode === KeyCode.ContextMenu || (e.shiftKey && e.keyCode === KeyCode.F10)) .map(e => EventHelper.stop(e, true)) .map(({ browserEvent }) => { const focus = this.getFocus(); const index = focus.length ? focus[0] : undefined; const element = typeof index !== 'undefined' ? this.view.element(index) : undefined; const anchor = typeof index !== 'undefined' ? this.view.domElement(index) as HTMLElement : this.view.domNode; return { index, element, anchor, browserEvent }; }) .event; const fromMouse = this.disposables.add(Event.chain(this.view.onContextMenu)) .filter(_ => !didJustPressContextMenuKey) .map(({ element, index, browserEvent }) => ({ element, index, anchor: { x: browserEvent.pageX + 1, y: browserEvent.pageY }, browserEvent })) .event; return Event.any<IListContextMenuEvent<T>>(fromKeyDown, fromKeyUp, fromMouse); } @memoize get onKeyDown(): Event<KeyboardEvent> { return this.disposables.add(new DomEmitter(this.view.domNode, 'keydown')).event; } @memoize get onKeyUp(): Event<KeyboardEvent> { return this.disposables.add(new DomEmitter(this.view.domNode, 'keyup')).event; } @memoize get onKeyPress(): Event<KeyboardEvent> { return this.disposables.add(new DomEmitter(this.view.domNode, 'keypress')).event; } @memoize get onDidFocus(): Event<void> { return Event.signal(this.disposables.add(new DomEmitter(this.view.domNode, 'focus', true)).event); } @memoize get onDidBlur(): Event<void> { return Event.signal(this.disposables.add(new DomEmitter(this.view.domNode, 'blur', true)).event); } private readonly _onDidDispose = new Emitter<void>(); readonly onDidDispose: Event<void> = this._onDidDispose.event; constructor( private user: string, container: HTMLElement, virtualDelegate: IListVirtualDelegate<T>, renderers: IListRenderer<any /* TODO@joao */, any>[], private _options: IListOptions<T> = DefaultOptions ) { const role = this._options.accessibilityProvider && this._options.accessibilityProvider.getWidgetRole ? this._options.accessibilityProvider?.getWidgetRole() : 'list'; this.selection = new SelectionTrait(role !== 'listbox'); mixin(_options, defaultStyles, false); const baseRenderers: IListRenderer<T, ITraitTemplateData>[] = [this.focus.renderer, this.selection.renderer]; this.accessibilityProvider = _options.accessibilityProvider; if (this.accessibilityProvider) { baseRenderers.push(new AccessibiltyRenderer<T>(this.accessibilityProvider)); this.accessibilityProvider.onDidChangeActiveDescendant?.(this.onDidChangeActiveDescendant, this, this.disposables); } renderers = renderers.map(r => new PipelineRenderer(r.templateId, [...baseRenderers, r])); const viewOptions: IListViewOptions<T> = { ..._options, dnd: _options.dnd && new ListViewDragAndDrop(this, _options.dnd) }; this.view = new ListView(container, virtualDelegate, renderers, viewOptions); this.view.domNode.setAttribute('role', role); if (_options.styleController) { this.styleController = _options.styleController(this.view.domId); } else { const styleElement = createStyleSheet(this.view.domNode); this.styleController = new DefaultStyleController(styleElement, this.view.domId); } this.spliceable = new CombinedSpliceable([ new TraitSpliceable(this.focus, this.view, _options.identityProvider), new TraitSpliceable(this.selection, this.view, _options.identityProvider), new TraitSpliceable(this.anchor, this.view, _options.identityProvider), this.view ]); this.disposables.add(this.focus); this.disposables.add(this.selection); this.disposables.add(this.anchor); this.disposables.add(this.view); this.disposables.add(this._onDidDispose); this.disposables.add(new DOMFocusController(this, this.view)); if (typeof _options.keyboardSupport !== 'boolean' || _options.keyboardSupport) { this.keyboardController = new KeyboardController(this, this.view, _options); this.disposables.add(this.keyboardController); } if (_options.keyboardNavigationLabelProvider) { const delegate = _options.keyboardNavigationDelegate || DefaultKeyboardNavigationDelegate; this.typeNavigationController = new TypeNavigationController(this, this.view, _options.keyboardNavigationLabelProvider, _options.keyboardNavigationEventFilter ?? (() => true), delegate); this.disposables.add(this.typeNavigationController); } this.mouseController = this.createMouseController(_options); this.disposables.add(this.mouseController); this.onDidChangeFocus(this._onFocusChange, this, this.disposables); this.onDidChangeSelection(this._onSelectionChange, this, this.disposables); if (this.accessibilityProvider) { this.ariaLabel = this.accessibilityProvider.getWidgetAriaLabel(); } if (this._options.multipleSelectionSupport !== false) { this.view.domNode.setAttribute('aria-multiselectable', 'true'); } } protected createMouseController(options: IListOptions<T>): MouseController<T> { return new MouseController(this); } updateOptions(optionsUpdate: IListOptionsUpdate = {}): void { this._options = { ...this._options, ...optionsUpdate }; this.typeNavigationController?.updateOptions(this._options); if (this._options.multipleSelectionController !== undefined) { if (this._options.multipleSelectionSupport) { this.view.domNode.setAttribute('aria-multiselectable', 'true'); } else { this.view.domNode.removeAttribute('aria-multiselectable'); } } this.mouseController.updateOptions(optionsUpdate); this.keyboardController?.updateOptions(optionsUpdate); this.view.updateOptions(optionsUpdate); } get options(): IListOptions<T> { return this._options; } splice(start: number, deleteCount: number, elements: readonly T[] = []): void { if (start < 0 || start > this.view.length) { throw new ListError(this.user, `Invalid start index: ${start}`); } if (deleteCount < 0) { throw new ListError(this.user, `Invalid delete count: ${deleteCount}`); } if (deleteCount === 0 && elements.length === 0) { return; } this.eventBufferer.bufferEvents(() => this.spliceable.splice(start, deleteCount, elements)); } updateWidth(index: number): void { this.view.updateWidth(index); } updateElementHeight(index: number, size: number): void { this.view.updateElementHeight(index, size, null); } rerender(): void { this.view.rerender(); } element(index: number): T { return this.view.element(index); } indexOf(element: T): number { return this.view.indexOf(element); } get length(): number { return this.view.length; } get contentHeight(): number { return this.view.contentHeight; } get onDidChangeContentHeight(): Event<number> { return this.view.onDidChangeContentHeight; } get scrollTop(): number { return this.view.getScrollTop(); } set scrollTop(scrollTop: number) { this.view.setScrollTop(scrollTop); } get scrollLeft(): number { return this.view.getScrollLeft(); } set scrollLeft(scrollLeft: number) { this.view.setScrollLeft(scrollLeft); } get scrollHeight(): number { return this.view.scrollHeight; } get renderHeight(): number { return this.view.renderHeight; } get firstVisibleIndex(): number { return this.view.firstVisibleIndex; } get lastVisibleIndex(): number { return this.view.lastVisibleIndex; } get ariaLabel(): string { return this._ariaLabel; } set ariaLabel(value: string) { this._ariaLabel = value; this.view.domNode.setAttribute('aria-label', value); } domFocus(): void { this.view.domNode.focus({ preventScroll: true }); } layout(height?: number, width?: number): void { this.view.layout(height, width); } triggerTypeNavigation(): void { this.typeNavigationController?.trigger(); } setSelection(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this.selection.set(indexes, browserEvent); } getSelection(): number[] { return this.selection.get(); } getSelectedElements(): T[] { return this.getSelection().map(i => this.view.element(i)); } setAnchor(index: number | undefined): void { if (typeof index === 'undefined') { this.anchor.set([]); return; } if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } this.anchor.set([index]); } getAnchor(): number | undefined { return firstOrDefault(this.anchor.get(), undefined); } getAnchorElement(): T | undefined { const anchor = this.getAnchor(); return typeof anchor === 'undefined' ? undefined : this.element(anchor); } setFocus(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this.focus.set(indexes, browserEvent); } focusNext(n = 1, loop = false, browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const focus = this.focus.get(); const index = this.findNextIndex(focus.length > 0 ? focus[0] + n : 0, loop, filter); if (index > -1) { this.setFocus([index], browserEvent); } } focusPrevious(n = 1, loop = false, browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const focus = this.focus.get(); const index = this.findPreviousIndex(focus.length > 0 ? focus[0] - n : 0, loop, filter); if (index > -1) { this.setFocus([index], browserEvent); } } async focusNextPage(browserEvent?: UIEvent, filter?: (element: T) => boolean): Promise<void> { let lastPageIndex = this.view.indexAt(this.view.getScrollTop() + this.view.renderHeight); lastPageIndex = lastPageIndex === 0 ? 0 : lastPageIndex - 1; const currentlyFocusedElementIndex = this.getFocus()[0]; if (currentlyFocusedElementIndex !== lastPageIndex && (currentlyFocusedElementIndex === undefined || lastPageIndex > currentlyFocusedElementIndex)) { const lastGoodPageIndex = this.findPreviousIndex(lastPageIndex, false, filter); if (lastGoodPageIndex > -1 && currentlyFocusedElementIndex !== lastGoodPageIndex) { this.setFocus([lastGoodPageIndex], browserEvent); } else { this.setFocus([lastPageIndex], browserEvent); } } else { const previousScrollTop = this.view.getScrollTop(); let nextpageScrollTop = previousScrollTop + this.view.renderHeight; if (lastPageIndex > currentlyFocusedElementIndex) { // scroll last page element to the top only if the last page element is below the focused element nextpageScrollTop -= this.view.elementHeight(lastPageIndex); } this.view.setScrollTop(nextpageScrollTop); if (this.view.getScrollTop() !== previousScrollTop) { this.setFocus([]); // Let the scroll event listener run await timeout(0); await this.focusNextPage(browserEvent, filter); } } } async focusPreviousPage(browserEvent?: UIEvent, filter?: (element: T) => boolean): Promise<void> { let firstPageIndex: number; const scrollTop = this.view.getScrollTop(); if (scrollTop === 0) { firstPageIndex = this.view.indexAt(scrollTop); } else { firstPageIndex = this.view.indexAfter(scrollTop - 1); } const currentlyFocusedElementIndex = this.getFocus()[0]; if (currentlyFocusedElementIndex !== firstPageIndex && (currentlyFocusedElementIndex === undefined || currentlyFocusedElementIndex >= firstPageIndex)) { const firstGoodPageIndex = this.findNextIndex(firstPageIndex, false, filter); if (firstGoodPageIndex > -1 && currentlyFocusedElementIndex !== firstGoodPageIndex) { this.setFocus([firstGoodPageIndex], browserEvent); } else { this.setFocus([firstPageIndex], browserEvent); } } else { const previousScrollTop = scrollTop; this.view.setScrollTop(scrollTop - this.view.renderHeight); if (this.view.getScrollTop() !== previousScrollTop) { this.setFocus([]); // Let the scroll event listener run await timeout(0); await this.focusPreviousPage(browserEvent, filter); } } } focusLast(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const index = this.findPreviousIndex(this.length - 1, false, filter); if (index > -1) { this.setFocus([index], browserEvent); } } focusFirst(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { this.focusNth(0, browserEvent, filter); } focusNth(n: number, browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const index = this.findNextIndex(n, false, filter); if (index > -1) { this.setFocus([index], browserEvent); } } private findNextIndex(index: number, loop = false, filter?: (element: T) => boolean): number { for (let i = 0; i < this.length; i++) { if (index >= this.length && !loop) { return -1; } index = index % this.length; if (!filter || filter(this.element(index))) { return index; } index++; } return -1; } private findPreviousIndex(index: number, loop = false, filter?: (element: T) => boolean): number { for (let i = 0; i < this.length; i++) { if (index < 0 && !loop) { return -1; } index = (this.length + (index % this.length)) % this.length; if (!filter || filter(this.element(index))) { return index; } index--; } return -1; } getFocus(): number[] { return this.focus.get(); } getFocusedElements(): T[] { return this.getFocus().map(i => this.view.element(i)); } reveal(index: number, relativeTop?: number): void { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } const scrollTop = this.view.getScrollTop(); const elementTop = this.view.elementTop(index); const elementHeight = this.view.elementHeight(index); if (isNumber(relativeTop)) { // y = mx + b const m = elementHeight - this.view.renderHeight; this.view.setScrollTop(m * clamp(relativeTop, 0, 1) + elementTop); } else { const viewItemBottom = elementTop + elementHeight; const scrollBottom = scrollTop + this.view.renderHeight; if (elementTop < scrollTop && viewItemBottom >= scrollBottom) { // The element is already overflowing the viewport, no-op } else if (elementTop < scrollTop || (viewItemBottom >= scrollBottom && elementHeight >= this.view.renderHeight)) { this.view.setScrollTop(elementTop); } else if (viewItemBottom >= scrollBottom) { this.view.setScrollTop(viewItemBottom - this.view.renderHeight); } } } /** * Returns the relative position of an element rendered in the list. * Returns `null` if the element isn't *entirely* in the visible viewport. */ getRelativeTop(index: number): number | null { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } const scrollTop = this.view.getScrollTop(); const elementTop = this.view.elementTop(index); const elementHeight = this.view.elementHeight(index); if (elementTop < scrollTop || elementTop + elementHeight > scrollTop + this.view.renderHeight) { return null; } // y = mx + b const m = elementHeight - this.view.renderHeight; return Math.abs((scrollTop - elementTop) / m); } isDOMFocused(): boolean { return this.view.domNode === document.activeElement; } getHTMLElement(): HTMLElement { return this.view.domNode; } getElementID(index: number): string { return this.view.getElementDomId(index); } style(styles: IListStyles): void { this.styleController.style(styles); } private toListEvent({ indexes, browserEvent }: ITraitChangeEvent) { return { indexes, elements: indexes.map(i => this.view.element(i)), browserEvent }; } private _onFocusChange(): void { const focus = this.focus.get(); this.view.domNode.classList.toggle('element-focused', focus.length > 0); this.onDidChangeActiveDescendant(); } private onDidChangeActiveDescendant(): void { const focus = this.focus.get(); if (focus.length > 0) { let id: string | undefined; if (this.accessibilityProvider?.getActiveDescendantId) { id = this.accessibilityProvider.getActiveDescendantId(this.view.element(focus[0])); } this.view.domNode.setAttribute('aria-activedescendant', id || this.view.getElementDomId(focus[0])); } else { this.view.domNode.removeAttribute('aria-activedescendant'); } } private _onSelectionChange(): void { const selection = this.selection.get(); this.view.domNode.classList.toggle('selection-none', selection.length === 0); this.view.domNode.classList.toggle('selection-single', selection.length === 1); this.view.domNode.classList.toggle('selection-multiple', selection.length > 1); } dispose(): void { this._onDidDispose.fire(); this.disposables.dispose(); this._onDidDispose.dispose(); } }
src/vs/base/browser/ui/list/listWidget.ts
1
https://github.com/microsoft/vscode/commit/f078e6db483250957314c56c3b12e23dae03d351
[ 0.9962232112884521, 0.017282648012042046, 0.00016364810289815068, 0.00017286266665905714, 0.1167396754026413 ]
{ "id": 4, "code_window": [ "\t\t\treturn;\n", "\t\t}\n", "\n", "\t\tconst node = e.element;\n", "\n", "\t\tif (!node) {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (e.browserEvent.defaultPrevented) {\n", "\t\t\treturn;\n", "\t\t}\n", "\n" ], "file_path": "src/vs/base/browser/ui/tree/abstractTree.ts", "type": "add", "edit_start_line_idx": 1000 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Schemas } from 'vs/base/common/network'; import { URI } from 'vs/base/common/uri'; import * as extHostProtocol from 'vs/workbench/api/common/extHost.protocol'; import { ExtHostDocuments } from 'vs/workbench/api/common/extHostDocuments'; import { ExtHostDocumentsAndEditors, IExtHostModelAddedData } from 'vs/workbench/api/common/extHostDocumentsAndEditors'; import * as extHostTypeConverters from 'vs/workbench/api/common/extHostTypeConverters'; import { NotebookRange } from 'vs/workbench/api/common/extHostTypes'; import * as notebookCommon from 'vs/workbench/contrib/notebook/common/notebookCommon'; import * as vscode from 'vscode'; class RawContentChangeEvent { constructor( readonly start: number, readonly deletedCount: number, readonly deletedItems: vscode.NotebookCell[], readonly items: ExtHostCell[] ) { } asApiEvent(): vscode.NotebookDocumentContentChange { return { range: new NotebookRange(this.start, this.start + this.deletedCount), addedCells: this.items.map(cell => cell.apiCell), removedCells: this.deletedItems, }; } } export class ExtHostCell { static asModelAddData(notebook: vscode.NotebookDocument, cell: extHostProtocol.NotebookCellDto): IExtHostModelAddedData { return { EOL: cell.eol, lines: cell.source, languageId: cell.language, uri: cell.uri, isDirty: false, versionId: 1, notebook }; } private _outputs: vscode.NotebookCellOutput[]; private _metadata: Readonly<notebookCommon.NotebookCellMetadata>; private _previousResult: Readonly<vscode.NotebookCellExecutionSummary | undefined>; private _internalMetadata: notebookCommon.NotebookCellInternalMetadata; readonly handle: number; readonly uri: URI; readonly cellKind: notebookCommon.CellKind; private _apiCell: vscode.NotebookCell | undefined; private _mime: string | undefined; constructor( readonly notebook: ExtHostNotebookDocument, private readonly _extHostDocument: ExtHostDocumentsAndEditors, private readonly _cellData: extHostProtocol.NotebookCellDto, ) { this.handle = _cellData.handle; this.uri = URI.revive(_cellData.uri); this.cellKind = _cellData.cellKind; this._outputs = _cellData.outputs.map(extHostTypeConverters.NotebookCellOutput.to); this._internalMetadata = _cellData.internalMetadata ?? {}; this._metadata = Object.freeze(_cellData.metadata ?? {}); this._previousResult = Object.freeze(extHostTypeConverters.NotebookCellExecutionSummary.to(_cellData.internalMetadata ?? {})); } get internalMetadata(): notebookCommon.NotebookCellInternalMetadata { return this._internalMetadata; } get apiCell(): vscode.NotebookCell { if (!this._apiCell) { const that = this; const data = this._extHostDocument.getDocument(this.uri); if (!data) { throw new Error(`MISSING extHostDocument for notebook cell: ${this.uri}`); } const apiCell: vscode.NotebookCell = { get index() { return that.notebook.getCellIndex(that); }, notebook: that.notebook.apiNotebook, kind: extHostTypeConverters.NotebookCellKind.to(this._cellData.cellKind), document: data.document, get mime() { return that._mime; }, set mime(value: string | undefined) { that._mime = value; }, get outputs() { return that._outputs.slice(0); }, get metadata() { return that._metadata; }, get executionSummary() { return that._previousResult; } }; this._apiCell = Object.freeze(apiCell); } return this._apiCell; } setOutputs(newOutputs: extHostProtocol.NotebookOutputDto[]): void { this._outputs = newOutputs.map(extHostTypeConverters.NotebookCellOutput.to); } setOutputItems(outputId: string, append: boolean, newOutputItems: extHostProtocol.NotebookOutputItemDto[]) { const newItems = newOutputItems.map(extHostTypeConverters.NotebookCellOutputItem.to); const output = this._outputs.find(op => op.id === outputId); if (output) { if (!append) { output.items.length = 0; } output.items.push(...newItems); if (output.items.length > 1 && output.items.every(item => notebookCommon.isTextStreamMime(item.mime))) { // Look for the mimes in the items, and keep track of their order. // Merge the streams into one output item, per mime type. const mimeOutputs = new Map<string, Uint8Array[]>(); const mimeTypes: string[] = []; output.items.forEach(item => { let items: Uint8Array[]; if (mimeOutputs.has(item.mime)) { items = mimeOutputs.get(item.mime)!; } else { items = []; mimeOutputs.set(item.mime, items); mimeTypes.push(item.mime); } items.push(item.data); }); output.items.length = 0; mimeTypes.forEach(mime => { const compressed = notebookCommon.compressOutputItemStreams(mimeOutputs.get(mime)!); output.items.push({ mime, data: compressed.buffer }); }); } } } setMetadata(newMetadata: notebookCommon.NotebookCellMetadata): void { this._metadata = Object.freeze(newMetadata); } setInternalMetadata(newInternalMetadata: notebookCommon.NotebookCellInternalMetadata): void { this._internalMetadata = newInternalMetadata; this._previousResult = Object.freeze(extHostTypeConverters.NotebookCellExecutionSummary.to(newInternalMetadata)); } setMime(newMime: string | undefined) { } } export class ExtHostNotebookDocument { private static _handlePool: number = 0; readonly handle = ExtHostNotebookDocument._handlePool++; private readonly _cells: ExtHostCell[] = []; private readonly _notebookType: string; private _notebook: vscode.NotebookDocument | undefined; private _metadata: Record<string, any>; private _versionId: number = 0; private _isDirty: boolean = false; private _disposed: boolean = false; constructor( private readonly _proxy: extHostProtocol.MainThreadNotebookDocumentsShape, private readonly _textDocumentsAndEditors: ExtHostDocumentsAndEditors, private readonly _textDocuments: ExtHostDocuments, readonly uri: URI, data: extHostProtocol.INotebookModelAddedData ) { this._notebookType = data.viewType; this._metadata = Object.freeze(data.metadata ?? Object.create(null)); this._spliceNotebookCells([[0, 0, data.cells]], true /* init -> no event*/, undefined); this._versionId = data.versionId; } dispose() { this._disposed = true; } get apiNotebook(): vscode.NotebookDocument { if (!this._notebook) { const that = this; const apiObject: vscode.NotebookDocument = { get uri() { return that.uri; }, get version() { return that._versionId; }, get notebookType() { return that._notebookType; }, get isDirty() { return that._isDirty; }, get isUntitled() { return that.uri.scheme === Schemas.untitled; }, get isClosed() { return that._disposed; }, get metadata() { return that._metadata; }, get cellCount() { return that._cells.length; }, cellAt(index) { index = that._validateIndex(index); return that._cells[index].apiCell; }, getCells(range) { const cells = range ? that._getCells(range) : that._cells; return cells.map(cell => cell.apiCell); }, save() { return that._save(); } }; this._notebook = Object.freeze(apiObject); } return this._notebook; } acceptDocumentPropertiesChanged(data: extHostProtocol.INotebookDocumentPropertiesChangeData) { if (data.metadata) { this._metadata = Object.freeze({ ...this._metadata, ...data.metadata }); } } acceptDirty(isDirty: boolean): void { this._isDirty = isDirty; } acceptModelChanged(event: extHostProtocol.NotebookCellsChangedEventDto, isDirty: boolean, newMetadata: notebookCommon.NotebookDocumentMetadata | undefined): vscode.NotebookDocumentChangeEvent { this._versionId = event.versionId; this._isDirty = isDirty; this.acceptDocumentPropertiesChanged({ metadata: newMetadata }); const result = { notebook: this.apiNotebook, metadata: newMetadata, cellChanges: <vscode.NotebookDocumentCellChange[]>[], contentChanges: <vscode.NotebookDocumentContentChange[]>[], }; type RelaxedCellChange = Partial<vscode.NotebookDocumentCellChange> & { cell: vscode.NotebookCell }; const relaxedCellChanges: RelaxedCellChange[] = []; // -- apply change and populate content changes for (const rawEvent of event.rawEvents) { if (rawEvent.kind === notebookCommon.NotebookCellsChangeType.ModelChange) { this._spliceNotebookCells(rawEvent.changes, false, result.contentChanges); } else if (rawEvent.kind === notebookCommon.NotebookCellsChangeType.Move) { this._moveCells(rawEvent.index, rawEvent.length, rawEvent.newIdx, result.contentChanges); } else if (rawEvent.kind === notebookCommon.NotebookCellsChangeType.Output) { this._setCellOutputs(rawEvent.index, rawEvent.outputs); relaxedCellChanges.push({ cell: this._cells[rawEvent.index].apiCell, outputs: this._cells[rawEvent.index].apiCell.outputs }); } else if (rawEvent.kind === notebookCommon.NotebookCellsChangeType.OutputItem) { this._setCellOutputItems(rawEvent.index, rawEvent.outputId, rawEvent.append, rawEvent.outputItems); relaxedCellChanges.push({ cell: this._cells[rawEvent.index].apiCell, outputs: this._cells[rawEvent.index].apiCell.outputs }); } else if (rawEvent.kind === notebookCommon.NotebookCellsChangeType.ChangeCellLanguage) { this._changeCellLanguage(rawEvent.index, rawEvent.language); relaxedCellChanges.push({ cell: this._cells[rawEvent.index].apiCell, document: this._cells[rawEvent.index].apiCell.document }); } else if (rawEvent.kind === notebookCommon.NotebookCellsChangeType.ChangeCellContent) { relaxedCellChanges.push({ cell: this._cells[rawEvent.index].apiCell, document: this._cells[rawEvent.index].apiCell.document }); } else if (rawEvent.kind === notebookCommon.NotebookCellsChangeType.ChangeCellMime) { this._changeCellMime(rawEvent.index, rawEvent.mime); } else if (rawEvent.kind === notebookCommon.NotebookCellsChangeType.ChangeCellMetadata) { this._changeCellMetadata(rawEvent.index, rawEvent.metadata); relaxedCellChanges.push({ cell: this._cells[rawEvent.index].apiCell, metadata: this._cells[rawEvent.index].apiCell.metadata }); } else if (rawEvent.kind === notebookCommon.NotebookCellsChangeType.ChangeCellInternalMetadata) { this._changeCellInternalMetadata(rawEvent.index, rawEvent.internalMetadata); relaxedCellChanges.push({ cell: this._cells[rawEvent.index].apiCell, executionSummary: this._cells[rawEvent.index].apiCell.executionSummary }); } } // -- compact cellChanges const map = new Map<vscode.NotebookCell, number>(); for (let i = 0; i < relaxedCellChanges.length; i++) { const relaxedCellChange = relaxedCellChanges[i]; const existing = map.get(relaxedCellChange.cell); if (existing === undefined) { const newLen = result.cellChanges.push({ document: undefined, executionSummary: undefined, metadata: undefined, outputs: undefined, ...relaxedCellChange, }); map.set(relaxedCellChange.cell, newLen - 1); } else { result.cellChanges[existing] = { ...result.cellChanges[existing], ...relaxedCellChange }; } } // Freeze event properties so handlers cannot accidentally modify them Object.freeze(result); Object.freeze(result.cellChanges); Object.freeze(result.contentChanges); return result; } private _validateIndex(index: number): number { index = index | 0; if (index < 0) { return 0; } else if (index >= this._cells.length) { return this._cells.length - 1; } else { return index; } } private _validateRange(range: vscode.NotebookRange): vscode.NotebookRange { let start = range.start | 0; let end = range.end | 0; if (start < 0) { start = 0; } if (end > this._cells.length) { end = this._cells.length; } return range.with({ start, end }); } private _getCells(range: vscode.NotebookRange): ExtHostCell[] { range = this._validateRange(range); const result: ExtHostCell[] = []; for (let i = range.start; i < range.end; i++) { result.push(this._cells[i]); } return result; } private async _save(): Promise<boolean> { if (this._disposed) { return Promise.reject(new Error('Notebook has been closed')); } return this._proxy.$trySaveNotebook(this.uri); } private _spliceNotebookCells(splices: notebookCommon.NotebookCellTextModelSplice<extHostProtocol.NotebookCellDto>[], initialization: boolean, bucket: vscode.NotebookDocumentContentChange[] | undefined): void { if (this._disposed) { return; } const contentChangeEvents: RawContentChangeEvent[] = []; const addedCellDocuments: IExtHostModelAddedData[] = []; const removedCellDocuments: URI[] = []; splices.reverse().forEach(splice => { const cellDtos = splice[2]; const newCells = cellDtos.map(cell => { const extCell = new ExtHostCell(this, this._textDocumentsAndEditors, cell); if (!initialization) { addedCellDocuments.push(ExtHostCell.asModelAddData(this.apiNotebook, cell)); } return extCell; }); const changeEvent = new RawContentChangeEvent(splice[0], splice[1], [], newCells); const deletedItems = this._cells.splice(splice[0], splice[1], ...newCells); for (const cell of deletedItems) { removedCellDocuments.push(cell.uri); changeEvent.deletedItems.push(cell.apiCell); } contentChangeEvents.push(changeEvent); }); this._textDocumentsAndEditors.acceptDocumentsAndEditorsDelta({ addedDocuments: addedCellDocuments, removedDocuments: removedCellDocuments }); if (bucket) { for (const changeEvent of contentChangeEvents) { bucket.push(changeEvent.asApiEvent()); } } } private _moveCells(index: number, length: number, newIdx: number, bucket: vscode.NotebookDocumentContentChange[]): void { const cells = this._cells.splice(index, length); this._cells.splice(newIdx, 0, ...cells); const changes = [ new RawContentChangeEvent(index, length, cells.map(c => c.apiCell), []), new RawContentChangeEvent(newIdx, 0, [], cells) ]; for (const change of changes) { bucket.push(change.asApiEvent()); } } private _setCellOutputs(index: number, outputs: extHostProtocol.NotebookOutputDto[]): void { const cell = this._cells[index]; cell.setOutputs(outputs); } private _setCellOutputItems(index: number, outputId: string, append: boolean, outputItems: extHostProtocol.NotebookOutputItemDto[]): void { const cell = this._cells[index]; cell.setOutputItems(outputId, append, outputItems); } private _changeCellLanguage(index: number, newLanguageId: string): void { const cell = this._cells[index]; if (cell.apiCell.document.languageId !== newLanguageId) { this._textDocuments.$acceptModelLanguageChanged(cell.uri, newLanguageId); } } private _changeCellMime(index: number, newMime: string | undefined): void { const cell = this._cells[index]; cell.apiCell.mime = newMime; } private _changeCellMetadata(index: number, newMetadata: notebookCommon.NotebookCellMetadata): void { const cell = this._cells[index]; cell.setMetadata(newMetadata); } private _changeCellInternalMetadata(index: number, newInternalMetadata: notebookCommon.NotebookCellInternalMetadata): void { const cell = this._cells[index]; cell.setInternalMetadata(newInternalMetadata); } getCellFromApiCell(apiCell: vscode.NotebookCell): ExtHostCell | undefined { return this._cells.find(cell => cell.apiCell === apiCell); } getCellFromIndex(index: number): ExtHostCell | undefined { return this._cells[index]; } getCell(cellHandle: number): ExtHostCell | undefined { return this._cells.find(cell => cell.handle === cellHandle); } getCellIndex(cell: ExtHostCell): number { return this._cells.indexOf(cell); } }
src/vs/workbench/api/common/extHostNotebookDocument.ts
0
https://github.com/microsoft/vscode/commit/f078e6db483250957314c56c3b12e23dae03d351
[ 0.0003178916231263429, 0.00017357920296490192, 0.00016504530503880233, 0.00016865339421201497, 0.00002255208346468862 ]
{ "id": 4, "code_window": [ "\t\t\treturn;\n", "\t\t}\n", "\n", "\t\tconst node = e.element;\n", "\n", "\t\tif (!node) {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (e.browserEvent.defaultPrevented) {\n", "\t\t\treturn;\n", "\t\t}\n", "\n" ], "file_path": "src/vs/base/browser/ui/tree/abstractTree.ts", "type": "add", "edit_start_line_idx": 1000 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; import { Categories } from 'vs/platform/action/common/actionCommonCategories'; import { Action2, IMenuService } from 'vs/platform/actions/common/actions'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { ILogService } from 'vs/platform/log/common/log'; export class MenuHiddenStatesReset extends Action2 { constructor() { super({ id: 'menu.resetHiddenStates', title: { value: localize('title', 'Reset All Menus'), original: 'Reset All Menus' }, category: Categories.View, f1: true }); } run(accessor: ServicesAccessor): void { accessor.get(IMenuService).resetHiddenStates(); accessor.get(ILogService).info('did RESET all menu hidden states'); } }
src/vs/platform/actions/common/menuResetAction.ts
0
https://github.com/microsoft/vscode/commit/f078e6db483250957314c56c3b12e23dae03d351
[ 0.00017995815142057836, 0.00017557773389853537, 0.00016922589566092938, 0.00017656342242844403, 0.000004002071364084259 ]
{ "id": 4, "code_window": [ "\t\t\treturn;\n", "\t\t}\n", "\n", "\t\tconst node = e.element;\n", "\n", "\t\tif (!node) {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (e.browserEvent.defaultPrevented) {\n", "\t\t\treturn;\n", "\t\t}\n", "\n" ], "file_path": "src/vs/base/browser/ui/tree/abstractTree.ts", "type": "add", "edit_start_line_idx": 1000 }
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1
extensions/docker/yarn.lock
0
https://github.com/microsoft/vscode/commit/f078e6db483250957314c56c3b12e23dae03d351
[ 0.00017175616812892258, 0.00017175616812892258, 0.00017175616812892258, 0.00017175616812892258, 0 ]
{ "id": 5, "code_window": [ "\n", "\t\tif (onTwistie || !this.tree.expandOnDoubleClick) {\n", "\t\t\treturn;\n", "\t\t}\n", "\n", "\t\tsuper.onDoubleClick(e);\n", "\t}\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (e.browserEvent.defaultPrevented) {\n", "\t\t\treturn;\n", "\t\t}\n", "\n" ], "file_path": "src/vs/base/browser/ui/tree/abstractTree.ts", "type": "add", "edit_start_line_idx": 1051 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IDragAndDropData } from 'vs/base/browser/dnd'; import { createStyleSheet, Dimension, EventHelper } from 'vs/base/browser/dom'; import { DomEmitter } from 'vs/base/browser/event'; import { IKeyboardEvent, StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { Gesture } from 'vs/base/browser/touch'; import { alert, AriaRole } from 'vs/base/browser/ui/aria/aria'; import { CombinedSpliceable } from 'vs/base/browser/ui/list/splice'; import { ScrollableElementChangeOptions } from 'vs/base/browser/ui/scrollbar/scrollableElementOptions'; import { binarySearch, firstOrDefault, range } from 'vs/base/common/arrays'; import { timeout } from 'vs/base/common/async'; import { Color } from 'vs/base/common/color'; import { memoize } from 'vs/base/common/decorators'; import { Emitter, Event, EventBufferer } from 'vs/base/common/event'; import { matchesPrefix } from 'vs/base/common/filters'; import { KeyCode } from 'vs/base/common/keyCodes'; import { DisposableStore, dispose, IDisposable } from 'vs/base/common/lifecycle'; import { clamp } from 'vs/base/common/numbers'; import { mixin } from 'vs/base/common/objects'; import * as platform from 'vs/base/common/platform'; import { ScrollbarVisibility, ScrollEvent } from 'vs/base/common/scrollable'; import { ISpliceable } from 'vs/base/common/sequence'; import { IThemable } from 'vs/base/common/styler'; import { isNumber } from 'vs/base/common/types'; import 'vs/css!./list'; import { IIdentityProvider, IKeyboardNavigationDelegate, IKeyboardNavigationLabelProvider, IListContextMenuEvent, IListDragAndDrop, IListDragOverReaction, IListEvent, IListGestureEvent, IListMouseEvent, IListRenderer, IListTouchEvent, IListVirtualDelegate, ListError } from './list'; import { IListViewAccessibilityProvider, IListViewDragAndDrop, IListViewOptions, IListViewOptionsUpdate, ListView } from './listView'; interface ITraitChangeEvent { indexes: number[]; browserEvent?: UIEvent; } type ITraitTemplateData = HTMLElement; interface IRenderedContainer { templateData: ITraitTemplateData; index: number; } class TraitRenderer<T> implements IListRenderer<T, ITraitTemplateData> { private renderedElements: IRenderedContainer[] = []; constructor(private trait: Trait<T>) { } get templateId(): string { return `template:${this.trait.name}`; } renderTemplate(container: HTMLElement): ITraitTemplateData { return container; } renderElement(element: T, index: number, templateData: ITraitTemplateData): void { const renderedElementIndex = this.renderedElements.findIndex(el => el.templateData === templateData); if (renderedElementIndex >= 0) { const rendered = this.renderedElements[renderedElementIndex]; this.trait.unrender(templateData); rendered.index = index; } else { const rendered = { index, templateData }; this.renderedElements.push(rendered); } this.trait.renderIndex(index, templateData); } splice(start: number, deleteCount: number, insertCount: number): void { const rendered: IRenderedContainer[] = []; for (const renderedElement of this.renderedElements) { if (renderedElement.index < start) { rendered.push(renderedElement); } else if (renderedElement.index >= start + deleteCount) { rendered.push({ index: renderedElement.index + insertCount - deleteCount, templateData: renderedElement.templateData }); } } this.renderedElements = rendered; } renderIndexes(indexes: number[]): void { for (const { index, templateData } of this.renderedElements) { if (indexes.indexOf(index) > -1) { this.trait.renderIndex(index, templateData); } } } disposeTemplate(templateData: ITraitTemplateData): void { const index = this.renderedElements.findIndex(el => el.templateData === templateData); if (index < 0) { return; } this.renderedElements.splice(index, 1); } } class Trait<T> implements ISpliceable<boolean>, IDisposable { private length = 0; private indexes: number[] = []; private sortedIndexes: number[] = []; private readonly _onChange = new Emitter<ITraitChangeEvent>(); readonly onChange: Event<ITraitChangeEvent> = this._onChange.event; get name(): string { return this._trait; } @memoize get renderer(): TraitRenderer<T> { return new TraitRenderer<T>(this); } constructor(private _trait: string) { } splice(start: number, deleteCount: number, elements: boolean[]): void { deleteCount = Math.max(0, Math.min(deleteCount, this.length - start)); const diff = elements.length - deleteCount; const end = start + deleteCount; const sortedIndexes = [ ...this.sortedIndexes.filter(i => i < start), ...elements.map((hasTrait, i) => hasTrait ? i + start : -1).filter(i => i !== -1), ...this.sortedIndexes.filter(i => i >= end).map(i => i + diff) ]; const length = this.length + diff; if (this.sortedIndexes.length > 0 && sortedIndexes.length === 0 && length > 0) { const first = this.sortedIndexes.find(index => index >= start) ?? length - 1; sortedIndexes.push(Math.min(first, length - 1)); } this.renderer.splice(start, deleteCount, elements.length); this._set(sortedIndexes, sortedIndexes); this.length = length; } renderIndex(index: number, container: HTMLElement): void { container.classList.toggle(this._trait, this.contains(index)); } unrender(container: HTMLElement): void { container.classList.remove(this._trait); } /** * Sets the indexes which should have this trait. * * @param indexes Indexes which should have this trait. * @return The old indexes which had this trait. */ set(indexes: number[], browserEvent?: UIEvent): number[] { return this._set(indexes, [...indexes].sort(numericSort), browserEvent); } private _set(indexes: number[], sortedIndexes: number[], browserEvent?: UIEvent): number[] { const result = this.indexes; const sortedResult = this.sortedIndexes; this.indexes = indexes; this.sortedIndexes = sortedIndexes; const toRender = disjunction(sortedResult, indexes); this.renderer.renderIndexes(toRender); this._onChange.fire({ indexes, browserEvent }); return result; } get(): number[] { return this.indexes; } contains(index: number): boolean { return binarySearch(this.sortedIndexes, index, numericSort) >= 0; } dispose() { dispose(this._onChange); } } class SelectionTrait<T> extends Trait<T> { constructor(private setAriaSelected: boolean) { super('selected'); } override renderIndex(index: number, container: HTMLElement): void { super.renderIndex(index, container); if (this.setAriaSelected) { if (this.contains(index)) { container.setAttribute('aria-selected', 'true'); } else { container.setAttribute('aria-selected', 'false'); } } } } /** * The TraitSpliceable is used as a util class to be able * to preserve traits across splice calls, given an identity * provider. */ class TraitSpliceable<T> implements ISpliceable<T> { constructor( private trait: Trait<T>, private view: ListView<T>, private identityProvider?: IIdentityProvider<T> ) { } splice(start: number, deleteCount: number, elements: T[]): void { if (!this.identityProvider) { return this.trait.splice(start, deleteCount, elements.map(() => false)); } const pastElementsWithTrait = this.trait.get().map(i => this.identityProvider!.getId(this.view.element(i)).toString()); const elementsWithTrait = elements.map(e => pastElementsWithTrait.indexOf(this.identityProvider!.getId(e).toString()) > -1); this.trait.splice(start, deleteCount, elementsWithTrait); } } export function isInputElement(e: HTMLElement): boolean { return e.tagName === 'INPUT' || e.tagName === 'TEXTAREA'; } export function isMonacoEditor(e: HTMLElement): boolean { if (e.classList.contains('monaco-editor')) { return true; } if (e.classList.contains('monaco-list')) { return false; } if (!e.parentElement) { return false; } return isMonacoEditor(e.parentElement); } export function isButton(e: HTMLElement): boolean { if ((e.tagName === 'A' && e.classList.contains('monaco-button')) || (e.tagName === 'DIV' && e.classList.contains('monaco-button-dropdown'))) { return true; } if (e.classList.contains('monaco-list')) { return false; } if (!e.parentElement) { return false; } return isButton(e.parentElement); } class KeyboardController<T> implements IDisposable { private readonly disposables = new DisposableStore(); private readonly multipleSelectionDisposables = new DisposableStore(); @memoize private get onKeyDown(): Event.IChainableEvent<StandardKeyboardEvent> { return this.disposables.add(Event.chain(this.disposables.add(new DomEmitter(this.view.domNode, 'keydown')).event) .filter(e => !isInputElement(e.target as HTMLElement)) .map(e => new StandardKeyboardEvent(e))); } constructor( private list: List<T>, private view: ListView<T>, options: IListOptions<T> ) { this.onKeyDown.filter(e => e.keyCode === KeyCode.Enter).on(this.onEnter, this, this.disposables); this.onKeyDown.filter(e => e.keyCode === KeyCode.UpArrow).on(this.onUpArrow, this, this.disposables); this.onKeyDown.filter(e => e.keyCode === KeyCode.DownArrow).on(this.onDownArrow, this, this.disposables); this.onKeyDown.filter(e => e.keyCode === KeyCode.PageUp).on(this.onPageUpArrow, this, this.disposables); this.onKeyDown.filter(e => e.keyCode === KeyCode.PageDown).on(this.onPageDownArrow, this, this.disposables); this.onKeyDown.filter(e => e.keyCode === KeyCode.Escape).on(this.onEscape, this, this.disposables); if (options.multipleSelectionSupport !== false) { this.onKeyDown.filter(e => (platform.isMacintosh ? e.metaKey : e.ctrlKey) && e.keyCode === KeyCode.KeyA).on(this.onCtrlA, this, this.multipleSelectionDisposables); } } updateOptions(optionsUpdate: IListOptionsUpdate): void { if (optionsUpdate.multipleSelectionSupport !== undefined) { this.multipleSelectionDisposables.clear(); if (optionsUpdate.multipleSelectionSupport) { this.onKeyDown.filter(e => (platform.isMacintosh ? e.metaKey : e.ctrlKey) && e.keyCode === KeyCode.KeyA).on(this.onCtrlA, this, this.multipleSelectionDisposables); } } } private onEnter(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.setSelection(this.list.getFocus(), e.browserEvent); } private onUpArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusPrevious(1, false, e.browserEvent); const el = this.list.getFocus()[0]; this.list.setAnchor(el); this.list.reveal(el); this.view.domNode.focus(); } private onDownArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusNext(1, false, e.browserEvent); const el = this.list.getFocus()[0]; this.list.setAnchor(el); this.list.reveal(el); this.view.domNode.focus(); } private onPageUpArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusPreviousPage(e.browserEvent); const el = this.list.getFocus()[0]; this.list.setAnchor(el); this.list.reveal(el); this.view.domNode.focus(); } private onPageDownArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusNextPage(e.browserEvent); const el = this.list.getFocus()[0]; this.list.setAnchor(el); this.list.reveal(el); this.view.domNode.focus(); } private onCtrlA(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.setSelection(range(this.list.length), e.browserEvent); this.list.setAnchor(undefined); this.view.domNode.focus(); } private onEscape(e: StandardKeyboardEvent): void { if (this.list.getSelection().length) { e.preventDefault(); e.stopPropagation(); this.list.setSelection([], e.browserEvent); this.list.setAnchor(undefined); this.view.domNode.focus(); } } dispose() { this.disposables.dispose(); this.multipleSelectionDisposables.dispose(); } } export enum TypeNavigationMode { Automatic, Trigger } enum TypeNavigationControllerState { Idle, Typing } export const DefaultKeyboardNavigationDelegate = new class implements IKeyboardNavigationDelegate { mightProducePrintableCharacter(event: IKeyboardEvent): boolean { if (event.ctrlKey || event.metaKey || event.altKey) { return false; } return (event.keyCode >= KeyCode.KeyA && event.keyCode <= KeyCode.KeyZ) || (event.keyCode >= KeyCode.Digit0 && event.keyCode <= KeyCode.Digit9) || (event.keyCode >= KeyCode.Numpad0 && event.keyCode <= KeyCode.Numpad9) || (event.keyCode >= KeyCode.Semicolon && event.keyCode <= KeyCode.Quote); } }; class TypeNavigationController<T> implements IDisposable { private enabled = false; private state: TypeNavigationControllerState = TypeNavigationControllerState.Idle; private mode = TypeNavigationMode.Automatic; private triggered = false; private previouslyFocused = -1; private readonly enabledDisposables = new DisposableStore(); private readonly disposables = new DisposableStore(); constructor( private list: List<T>, private view: ListView<T>, private keyboardNavigationLabelProvider: IKeyboardNavigationLabelProvider<T>, private keyboardNavigationEventFilter: IKeyboardNavigationEventFilter, private delegate: IKeyboardNavigationDelegate ) { this.updateOptions(list.options); } updateOptions(options: IListOptions<T>): void { if (options.typeNavigationEnabled ?? true) { this.enable(); } else { this.disable(); } this.mode = options.typeNavigationMode ?? TypeNavigationMode.Automatic; } trigger(): void { this.triggered = !this.triggered; } private enable(): void { if (this.enabled) { return; } let typing = false; const onChar = this.enabledDisposables.add(Event.chain(this.enabledDisposables.add(new DomEmitter(this.view.domNode, 'keydown')).event)) .filter(e => !isInputElement(e.target as HTMLElement)) .filter(() => this.mode === TypeNavigationMode.Automatic || this.triggered) .map(event => new StandardKeyboardEvent(event)) .filter(e => typing || this.keyboardNavigationEventFilter(e)) .filter(e => this.delegate.mightProducePrintableCharacter(e)) .forEach(e => EventHelper.stop(e, true)) .map(event => event.browserEvent.key) .event; const onClear = Event.debounce<string, null>(onChar, () => null, 800, undefined, undefined, this.enabledDisposables); const onInput = Event.reduce<string | null, string | null>(Event.any(onChar, onClear), (r, i) => i === null ? null : ((r || '') + i), undefined, this.enabledDisposables); onInput(this.onInput, this, this.enabledDisposables); onClear(this.onClear, this, this.enabledDisposables); onChar(() => typing = true, undefined, this.enabledDisposables); onClear(() => typing = false, undefined, this.enabledDisposables); this.enabled = true; this.triggered = false; } private disable(): void { if (!this.enabled) { return; } this.enabledDisposables.clear(); this.enabled = false; this.triggered = false; } private onClear(): void { const focus = this.list.getFocus(); if (focus.length > 0 && focus[0] === this.previouslyFocused) { // List: re-announce element on typing end since typed keys will interrupt aria label of focused element // Do not announce if there was a focus change at the end to prevent duplication https://github.com/microsoft/vscode/issues/95961 const ariaLabel = this.list.options.accessibilityProvider?.getAriaLabel(this.list.element(focus[0])); if (ariaLabel) { alert(ariaLabel); } } this.previouslyFocused = -1; } private onInput(word: string | null): void { if (!word) { this.state = TypeNavigationControllerState.Idle; this.triggered = false; return; } const focus = this.list.getFocus(); const start = focus.length > 0 ? focus[0] : 0; const delta = this.state === TypeNavigationControllerState.Idle ? 1 : 0; this.state = TypeNavigationControllerState.Typing; for (let i = 0; i < this.list.length; i++) { const index = (start + i + delta) % this.list.length; const label = this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(this.view.element(index)); const labelStr = label && label.toString(); if (typeof labelStr === 'undefined' || matchesPrefix(word, labelStr)) { this.previouslyFocused = start; this.list.setFocus([index]); this.list.reveal(index); return; } } } dispose() { this.disable(); this.enabledDisposables.dispose(); this.disposables.dispose(); } } class DOMFocusController<T> implements IDisposable { private readonly disposables = new DisposableStore(); constructor( private list: List<T>, private view: ListView<T> ) { const onKeyDown = this.disposables.add(Event.chain(this.disposables.add(new DomEmitter(view.domNode, 'keydown')).event)) .filter(e => !isInputElement(e.target as HTMLElement)) .map(e => new StandardKeyboardEvent(e)); onKeyDown.filter(e => e.keyCode === KeyCode.Tab && !e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey) .on(this.onTab, this, this.disposables); } private onTab(e: StandardKeyboardEvent): void { if (e.target !== this.view.domNode) { return; } const focus = this.list.getFocus(); if (focus.length === 0) { return; } const focusedDomElement = this.view.domElement(focus[0]); if (!focusedDomElement) { return; } const tabIndexElement = focusedDomElement.querySelector('[tabIndex]'); if (!tabIndexElement || !(tabIndexElement instanceof HTMLElement) || tabIndexElement.tabIndex === -1) { return; } const style = window.getComputedStyle(tabIndexElement); if (style.visibility === 'hidden' || style.display === 'none') { return; } e.preventDefault(); e.stopPropagation(); tabIndexElement.focus(); } dispose() { this.disposables.dispose(); } } export function isSelectionSingleChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return platform.isMacintosh ? event.browserEvent.metaKey : event.browserEvent.ctrlKey; } export function isSelectionRangeChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return event.browserEvent.shiftKey; } function isMouseRightClick(event: UIEvent): boolean { return event instanceof MouseEvent && event.button === 2; } const DefaultMultipleSelectionController = { isSelectionSingleChangeEvent, isSelectionRangeChangeEvent }; export class MouseController<T> implements IDisposable { private multipleSelectionController: IMultipleSelectionController<T> | undefined; private mouseSupport: boolean; private readonly disposables = new DisposableStore(); private _onPointer = new Emitter<IListMouseEvent<T>>(); readonly onPointer: Event<IListMouseEvent<T>> = this._onPointer.event; constructor(protected list: List<T>) { if (list.options.multipleSelectionSupport !== false) { this.multipleSelectionController = this.list.options.multipleSelectionController || DefaultMultipleSelectionController; } this.mouseSupport = typeof list.options.mouseSupport === 'undefined' || !!list.options.mouseSupport; if (this.mouseSupport) { list.onMouseDown(this.onMouseDown, this, this.disposables); list.onContextMenu(this.onContextMenu, this, this.disposables); list.onMouseDblClick(this.onDoubleClick, this, this.disposables); list.onTouchStart(this.onMouseDown, this, this.disposables); this.disposables.add(Gesture.addTarget(list.getHTMLElement())); } Event.any(list.onMouseClick, list.onMouseMiddleClick, list.onTap)(this.onViewPointer, this, this.disposables); } updateOptions(optionsUpdate: IListOptionsUpdate): void { if (optionsUpdate.multipleSelectionSupport !== undefined) { this.multipleSelectionController = undefined; if (optionsUpdate.multipleSelectionSupport) { this.multipleSelectionController = this.list.options.multipleSelectionController || DefaultMultipleSelectionController; } } } protected isSelectionSingleChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { if (!this.multipleSelectionController) { return false; } return this.multipleSelectionController.isSelectionSingleChangeEvent(event); } protected isSelectionRangeChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { if (!this.multipleSelectionController) { return false; } return this.multipleSelectionController.isSelectionRangeChangeEvent(event); } private isSelectionChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return this.isSelectionSingleChangeEvent(event) || this.isSelectionRangeChangeEvent(event); } private onMouseDown(e: IListMouseEvent<T> | IListTouchEvent<T>): void { if (isMonacoEditor(e.browserEvent.target as HTMLElement)) { return; } if (document.activeElement !== e.browserEvent.target) { this.list.domFocus(); } } private onContextMenu(e: IListContextMenuEvent<T>): void { if (isInputElement(e.browserEvent.target as HTMLElement) || isMonacoEditor(e.browserEvent.target as HTMLElement)) { return; } const focus = typeof e.index === 'undefined' ? [] : [e.index]; this.list.setFocus(focus, e.browserEvent); } protected onViewPointer(e: IListMouseEvent<T>): void { if (!this.mouseSupport) { return; } if (isInputElement(e.browserEvent.target as HTMLElement) || isMonacoEditor(e.browserEvent.target as HTMLElement)) { return; } const focus = e.index; if (typeof focus === 'undefined') { this.list.setFocus([], e.browserEvent); this.list.setSelection([], e.browserEvent); this.list.setAnchor(undefined); return; } if (this.isSelectionRangeChangeEvent(e)) { return this.changeSelection(e); } if (this.isSelectionChangeEvent(e)) { return this.changeSelection(e); } this.list.setFocus([focus], e.browserEvent); this.list.setAnchor(focus); if (!isMouseRightClick(e.browserEvent)) { this.list.setSelection([focus], e.browserEvent); } this._onPointer.fire(e); } protected onDoubleClick(e: IListMouseEvent<T>): void { if (isInputElement(e.browserEvent.target as HTMLElement) || isMonacoEditor(e.browserEvent.target as HTMLElement)) { return; } if (this.isSelectionChangeEvent(e)) { return; } const focus = this.list.getFocus(); this.list.setSelection(focus, e.browserEvent); } private changeSelection(e: IListMouseEvent<T> | IListTouchEvent<T>): void { const focus = e.index!; let anchor = this.list.getAnchor(); if (this.isSelectionRangeChangeEvent(e)) { if (typeof anchor === 'undefined') { const currentFocus = this.list.getFocus()[0]; anchor = currentFocus ?? focus; this.list.setAnchor(anchor); } const min = Math.min(anchor, focus); const max = Math.max(anchor, focus); const rangeSelection = range(min, max + 1); const selection = this.list.getSelection(); const contiguousRange = getContiguousRangeContaining(disjunction(selection, [anchor]), anchor); if (contiguousRange.length === 0) { return; } const newSelection = disjunction(rangeSelection, relativeComplement(selection, contiguousRange)); this.list.setSelection(newSelection, e.browserEvent); this.list.setFocus([focus], e.browserEvent); } else if (this.isSelectionSingleChangeEvent(e)) { const selection = this.list.getSelection(); const newSelection = selection.filter(i => i !== focus); this.list.setFocus([focus]); this.list.setAnchor(focus); if (selection.length === newSelection.length) { this.list.setSelection([...newSelection, focus], e.browserEvent); } else { this.list.setSelection(newSelection, e.browserEvent); } } } dispose() { this.disposables.dispose(); } } export interface IMultipleSelectionController<T> { isSelectionSingleChangeEvent(event: IListMouseEvent<T> | IListTouchEvent<T>): boolean; isSelectionRangeChangeEvent(event: IListMouseEvent<T> | IListTouchEvent<T>): boolean; } export interface IStyleController { style(styles: IListStyles): void; } export interface IListAccessibilityProvider<T> extends IListViewAccessibilityProvider<T> { getAriaLabel(element: T): string | null; getWidgetAriaLabel(): string; getWidgetRole?(): AriaRole; getAriaLevel?(element: T): number | undefined; onDidChangeActiveDescendant?: Event<void>; getActiveDescendantId?(element: T): string | undefined; } export class DefaultStyleController implements IStyleController { constructor(private styleElement: HTMLStyleElement, private selectorSuffix: string) { } style(styles: IListStyles): void { const suffix = this.selectorSuffix && `.${this.selectorSuffix}`; const content: string[] = []; if (styles.listBackground) { if (styles.listBackground.isOpaque()) { content.push(`.monaco-list${suffix} .monaco-list-rows { background: ${styles.listBackground}; }`); } else if (!platform.isMacintosh) { // subpixel AA doesn't exist in macOS console.warn(`List with id '${this.selectorSuffix}' was styled with a non-opaque background color. This will break sub-pixel antialiasing.`); } } if (styles.listFocusBackground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { background-color: ${styles.listFocusBackground}; }`); content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused:hover { background-color: ${styles.listFocusBackground}; }`); // overwrite :hover style in this case! } if (styles.listFocusForeground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { color: ${styles.listFocusForeground}; }`); } if (styles.listActiveSelectionBackground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { background-color: ${styles.listActiveSelectionBackground}; }`); content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected:hover { background-color: ${styles.listActiveSelectionBackground}; }`); // overwrite :hover style in this case! } if (styles.listActiveSelectionForeground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { color: ${styles.listActiveSelectionForeground}; }`); } if (styles.listActiveSelectionIconForeground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected .codicon { color: ${styles.listActiveSelectionIconForeground}; }`); } if (styles.listFocusAndSelectionOutline) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { outline-color: ${styles.listFocusAndSelectionOutline} !important; }`); } if (styles.listFocusAndSelectionBackground) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.selected.focused { background-color: ${styles.listFocusAndSelectionBackground}; } `); } if (styles.listFocusAndSelectionForeground) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.selected.focused { color: ${styles.listFocusAndSelectionForeground}; } `); } if (styles.listInactiveFocusForeground) { content.push(`.monaco-list${suffix} .monaco-list-row.focused { color: ${styles.listInactiveFocusForeground}; }`); content.push(`.monaco-list${suffix} .monaco-list-row.focused:hover { color: ${styles.listInactiveFocusForeground}; }`); // overwrite :hover style in this case! } if (styles.listInactiveSelectionIconForeground) { content.push(`.monaco-list${suffix} .monaco-list-row.focused .codicon { color: ${styles.listInactiveSelectionIconForeground}; }`); } if (styles.listInactiveFocusBackground) { content.push(`.monaco-list${suffix} .monaco-list-row.focused { background-color: ${styles.listInactiveFocusBackground}; }`); content.push(`.monaco-list${suffix} .monaco-list-row.focused:hover { background-color: ${styles.listInactiveFocusBackground}; }`); // overwrite :hover style in this case! } if (styles.listInactiveSelectionBackground) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { background-color: ${styles.listInactiveSelectionBackground}; }`); content.push(`.monaco-list${suffix} .monaco-list-row.selected:hover { background-color: ${styles.listInactiveSelectionBackground}; }`); // overwrite :hover style in this case! } if (styles.listInactiveSelectionForeground) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { color: ${styles.listInactiveSelectionForeground}; }`); } if (styles.listHoverBackground) { content.push(`.monaco-list${suffix}:not(.drop-target):not(.dragging) .monaco-list-row:hover:not(.selected):not(.focused) { background-color: ${styles.listHoverBackground}; }`); } if (styles.listHoverForeground) { content.push(`.monaco-list${suffix}:not(.drop-target):not(.dragging) .monaco-list-row:hover:not(.selected):not(.focused) { color: ${styles.listHoverForeground}; }`); } if (styles.listSelectionOutline) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { outline: 1px dotted ${styles.listSelectionOutline}; outline-offset: -1px; }`); } if (styles.listFocusOutline) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; } .monaco-workbench.context-menu-visible .monaco-list${suffix}.last-focused .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; } `); } if (styles.listInactiveFocusOutline) { content.push(`.monaco-list${suffix} .monaco-list-row.focused { outline: 1px dotted ${styles.listInactiveFocusOutline}; outline-offset: -1px; }`); } if (styles.listHoverOutline) { content.push(`.monaco-list${suffix} .monaco-list-row:hover { outline: 1px dashed ${styles.listHoverOutline}; outline-offset: -1px; }`); } if (styles.listDropBackground) { content.push(` .monaco-list${suffix}.drop-target, .monaco-list${suffix} .monaco-list-rows.drop-target, .monaco-list${suffix} .monaco-list-row.drop-target { background-color: ${styles.listDropBackground} !important; color: inherit !important; } `); } if (styles.tableColumnsBorder) { content.push(` .monaco-table > .monaco-split-view2, .monaco-table > .monaco-split-view2 .monaco-sash.vertical::before, .monaco-workbench:not(.reduce-motion) .monaco-table:hover > .monaco-split-view2, .monaco-workbench:not(.reduce-motion) .monaco-table:hover > .monaco-split-view2 .monaco-sash.vertical::before { border-color: ${styles.tableColumnsBorder}; } .monaco-workbench:not(.reduce-motion) .monaco-table > .monaco-split-view2, .monaco-workbench:not(.reduce-motion) .monaco-table > .monaco-split-view2 .monaco-sash.vertical::before { border-color: transparent; } `); } if (styles.tableOddRowsBackgroundColor) { content.push(` .monaco-table .monaco-list-row[data-parity=odd]:not(.focused):not(.selected):not(:hover) .monaco-table-tr, .monaco-table .monaco-list:not(:focus) .monaco-list-row[data-parity=odd].focused:not(.selected):not(:hover) .monaco-table-tr, .monaco-table .monaco-list:not(.focused) .monaco-list-row[data-parity=odd].focused:not(.selected):not(:hover) .monaco-table-tr { background-color: ${styles.tableOddRowsBackgroundColor}; } `); } this.styleElement.textContent = content.join('\n'); } } export interface IKeyboardNavigationEventFilter { (e: StandardKeyboardEvent): boolean; } export interface IListOptionsUpdate extends IListViewOptionsUpdate { readonly typeNavigationEnabled?: boolean; readonly typeNavigationMode?: TypeNavigationMode; readonly multipleSelectionSupport?: boolean; } export interface IListOptions<T> extends IListOptionsUpdate { readonly identityProvider?: IIdentityProvider<T>; readonly dnd?: IListDragAndDrop<T>; readonly keyboardNavigationLabelProvider?: IKeyboardNavigationLabelProvider<T>; readonly keyboardNavigationDelegate?: IKeyboardNavigationDelegate; readonly keyboardSupport?: boolean; readonly multipleSelectionController?: IMultipleSelectionController<T>; readonly styleController?: (suffix: string) => IStyleController; readonly accessibilityProvider?: IListAccessibilityProvider<T>; readonly keyboardNavigationEventFilter?: IKeyboardNavigationEventFilter; // list view options readonly useShadows?: boolean; readonly verticalScrollMode?: ScrollbarVisibility; readonly setRowLineHeight?: boolean; readonly setRowHeight?: boolean; readonly supportDynamicHeights?: boolean; readonly mouseSupport?: boolean; readonly horizontalScrolling?: boolean; readonly scrollByPage?: boolean; readonly additionalScrollHeight?: number; readonly transformOptimization?: boolean; readonly smoothScrolling?: boolean; readonly scrollableElementChangeOptions?: ScrollableElementChangeOptions; readonly alwaysConsumeMouseWheel?: boolean; readonly initialSize?: Dimension; } export interface IListStyles { listBackground?: Color; listFocusBackground?: Color; listFocusForeground?: Color; listActiveSelectionBackground?: Color; listActiveSelectionForeground?: Color; listActiveSelectionIconForeground?: Color; listFocusAndSelectionOutline?: Color; listFocusAndSelectionBackground?: Color; listFocusAndSelectionForeground?: Color; listInactiveSelectionBackground?: Color; listInactiveSelectionIconForeground?: Color; listInactiveSelectionForeground?: Color; listInactiveFocusForeground?: Color; listInactiveFocusBackground?: Color; listHoverBackground?: Color; listHoverForeground?: Color; listDropBackground?: Color; listFocusOutline?: Color; listInactiveFocusOutline?: Color; listSelectionOutline?: Color; listHoverOutline?: Color; treeIndentGuidesStroke?: Color; tableColumnsBorder?: Color; tableOddRowsBackgroundColor?: Color; } const defaultStyles: IListStyles = { listFocusBackground: Color.fromHex('#7FB0D0'), listActiveSelectionBackground: Color.fromHex('#0E639C'), listActiveSelectionForeground: Color.fromHex('#FFFFFF'), listActiveSelectionIconForeground: Color.fromHex('#FFFFFF'), listFocusAndSelectionOutline: Color.fromHex('#90C2F9'), listFocusAndSelectionBackground: Color.fromHex('#094771'), listFocusAndSelectionForeground: Color.fromHex('#FFFFFF'), listInactiveSelectionBackground: Color.fromHex('#3F3F46'), listInactiveSelectionIconForeground: Color.fromHex('#FFFFFF'), listHoverBackground: Color.fromHex('#2A2D2E'), listDropBackground: Color.fromHex('#383B3D'), treeIndentGuidesStroke: Color.fromHex('#a9a9a9'), tableColumnsBorder: Color.fromHex('#cccccc').transparent(0.2), tableOddRowsBackgroundColor: Color.fromHex('#cccccc').transparent(0.04) }; const DefaultOptions: IListOptions<any> = { keyboardSupport: true, mouseSupport: true, multipleSelectionSupport: true, dnd: { getDragURI() { return null; }, onDragStart(): void { }, onDragOver() { return false; }, drop() { } } }; // TODO@Joao: move these utils into a SortedArray class function getContiguousRangeContaining(range: number[], value: number): number[] { const index = range.indexOf(value); if (index === -1) { return []; } const result: number[] = []; let i = index - 1; while (i >= 0 && range[i] === value - (index - i)) { result.push(range[i--]); } result.reverse(); i = index; while (i < range.length && range[i] === value + (i - index)) { result.push(range[i++]); } return result; } /** * Given two sorted collections of numbers, returns the intersection * between them (OR). */ function disjunction(one: number[], other: number[]): number[] { const result: number[] = []; let i = 0, j = 0; while (i < one.length || j < other.length) { if (i >= one.length) { result.push(other[j++]); } else if (j >= other.length) { result.push(one[i++]); } else if (one[i] === other[j]) { result.push(one[i]); i++; j++; continue; } else if (one[i] < other[j]) { result.push(one[i++]); } else { result.push(other[j++]); } } return result; } /** * Given two sorted collections of numbers, returns the relative * complement between them (XOR). */ function relativeComplement(one: number[], other: number[]): number[] { const result: number[] = []; let i = 0, j = 0; while (i < one.length || j < other.length) { if (i >= one.length) { result.push(other[j++]); } else if (j >= other.length) { result.push(one[i++]); } else if (one[i] === other[j]) { i++; j++; continue; } else if (one[i] < other[j]) { result.push(one[i++]); } else { j++; } } return result; } const numericSort = (a: number, b: number) => a - b; class PipelineRenderer<T> implements IListRenderer<T, any> { constructor( private _templateId: string, private renderers: IListRenderer<any /* TODO@joao */, any>[] ) { } get templateId(): string { return this._templateId; } renderTemplate(container: HTMLElement): any[] { return this.renderers.map(r => r.renderTemplate(container)); } renderElement(element: T, index: number, templateData: any[], height: number | undefined): void { let i = 0; for (const renderer of this.renderers) { renderer.renderElement(element, index, templateData[i++], height); } } disposeElement(element: T, index: number, templateData: any[], height: number | undefined): void { let i = 0; for (const renderer of this.renderers) { renderer.disposeElement?.(element, index, templateData[i], height); i += 1; } } disposeTemplate(templateData: any[]): void { let i = 0; for (const renderer of this.renderers) { renderer.disposeTemplate(templateData[i++]); } } } class AccessibiltyRenderer<T> implements IListRenderer<T, HTMLElement> { templateId: string = 'a18n'; constructor(private accessibilityProvider: IListAccessibilityProvider<T>) { } renderTemplate(container: HTMLElement): HTMLElement { return container; } renderElement(element: T, index: number, container: HTMLElement): void { const ariaLabel = this.accessibilityProvider.getAriaLabel(element); if (ariaLabel) { container.setAttribute('aria-label', ariaLabel); } else { container.removeAttribute('aria-label'); } const ariaLevel = this.accessibilityProvider.getAriaLevel && this.accessibilityProvider.getAriaLevel(element); if (typeof ariaLevel === 'number') { container.setAttribute('aria-level', `${ariaLevel}`); } else { container.removeAttribute('aria-level'); } } disposeTemplate(templateData: any): void { // noop } } class ListViewDragAndDrop<T> implements IListViewDragAndDrop<T> { constructor(private list: List<T>, private dnd: IListDragAndDrop<T>) { } getDragElements(element: T): T[] { const selection = this.list.getSelectedElements(); const elements = selection.indexOf(element) > -1 ? selection : [element]; return elements; } getDragURI(element: T): string | null { return this.dnd.getDragURI(element); } getDragLabel?(elements: T[], originalEvent: DragEvent): string | undefined { if (this.dnd.getDragLabel) { return this.dnd.getDragLabel(elements, originalEvent); } return undefined; } onDragStart(data: IDragAndDropData, originalEvent: DragEvent): void { this.dnd.onDragStart?.(data, originalEvent); } onDragOver(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): boolean | IListDragOverReaction { return this.dnd.onDragOver(data, targetElement, targetIndex, originalEvent); } onDragLeave(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): void { this.dnd.onDragLeave?.(data, targetElement, targetIndex, originalEvent); } onDragEnd(originalEvent: DragEvent): void { this.dnd.onDragEnd?.(originalEvent); } drop(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): void { this.dnd.drop(data, targetElement, targetIndex, originalEvent); } } /** * The {@link List} is a virtual scrolling widget, built on top of the {@link ListView} * widget. * * Features: * - Customizable keyboard and mouse support * - Element traits: focus, selection, achor * - Accessibility support * - Touch support * - Performant template-based rendering * - Horizontal scrolling * - Variable element height support * - Dynamic element height support * - Drag-and-drop support */ export class List<T> implements ISpliceable<T>, IThemable, IDisposable { private focus = new Trait<T>('focused'); private selection: Trait<T>; private anchor = new Trait<T>('anchor'); private eventBufferer = new EventBufferer(); protected view: ListView<T>; private spliceable: ISpliceable<T>; private styleController: IStyleController; private typeNavigationController?: TypeNavigationController<T>; private accessibilityProvider?: IListAccessibilityProvider<T>; private keyboardController: KeyboardController<T> | undefined; private mouseController: MouseController<T>; private _ariaLabel: string = ''; protected readonly disposables = new DisposableStore(); @memoize get onDidChangeFocus(): Event<IListEvent<T>> { return Event.map(this.eventBufferer.wrapEvent(this.focus.onChange), e => this.toListEvent(e), this.disposables); } @memoize get onDidChangeSelection(): Event<IListEvent<T>> { return Event.map(this.eventBufferer.wrapEvent(this.selection.onChange), e => this.toListEvent(e), this.disposables); } get domId(): string { return this.view.domId; } get onDidScroll(): Event<ScrollEvent> { return this.view.onDidScroll; } get onMouseClick(): Event<IListMouseEvent<T>> { return this.view.onMouseClick; } get onMouseDblClick(): Event<IListMouseEvent<T>> { return this.view.onMouseDblClick; } get onMouseMiddleClick(): Event<IListMouseEvent<T>> { return this.view.onMouseMiddleClick; } get onPointer(): Event<IListMouseEvent<T>> { return this.mouseController.onPointer; } get onMouseUp(): Event<IListMouseEvent<T>> { return this.view.onMouseUp; } get onMouseDown(): Event<IListMouseEvent<T>> { return this.view.onMouseDown; } get onMouseOver(): Event<IListMouseEvent<T>> { return this.view.onMouseOver; } get onMouseMove(): Event<IListMouseEvent<T>> { return this.view.onMouseMove; } get onMouseOut(): Event<IListMouseEvent<T>> { return this.view.onMouseOut; } get onTouchStart(): Event<IListTouchEvent<T>> { return this.view.onTouchStart; } get onTap(): Event<IListGestureEvent<T>> { return this.view.onTap; } /** * Possible context menu trigger events: * - ContextMenu key * - Shift F10 * - Ctrl Option Shift M (macOS with VoiceOver) * - Mouse right click */ @memoize get onContextMenu(): Event<IListContextMenuEvent<T>> { let didJustPressContextMenuKey = false; const fromKeyDown = this.disposables.add(Event.chain(this.disposables.add(new DomEmitter(this.view.domNode, 'keydown')).event)) .map(e => new StandardKeyboardEvent(e)) .filter(e => didJustPressContextMenuKey = e.keyCode === KeyCode.ContextMenu || (e.shiftKey && e.keyCode === KeyCode.F10)) .map(e => EventHelper.stop(e, true)) .filter(() => false) .event as Event<any>; const fromKeyUp = this.disposables.add(Event.chain(this.disposables.add(new DomEmitter(this.view.domNode, 'keyup')).event)) .forEach(() => didJustPressContextMenuKey = false) .map(e => new StandardKeyboardEvent(e)) .filter(e => e.keyCode === KeyCode.ContextMenu || (e.shiftKey && e.keyCode === KeyCode.F10)) .map(e => EventHelper.stop(e, true)) .map(({ browserEvent }) => { const focus = this.getFocus(); const index = focus.length ? focus[0] : undefined; const element = typeof index !== 'undefined' ? this.view.element(index) : undefined; const anchor = typeof index !== 'undefined' ? this.view.domElement(index) as HTMLElement : this.view.domNode; return { index, element, anchor, browserEvent }; }) .event; const fromMouse = this.disposables.add(Event.chain(this.view.onContextMenu)) .filter(_ => !didJustPressContextMenuKey) .map(({ element, index, browserEvent }) => ({ element, index, anchor: { x: browserEvent.pageX + 1, y: browserEvent.pageY }, browserEvent })) .event; return Event.any<IListContextMenuEvent<T>>(fromKeyDown, fromKeyUp, fromMouse); } @memoize get onKeyDown(): Event<KeyboardEvent> { return this.disposables.add(new DomEmitter(this.view.domNode, 'keydown')).event; } @memoize get onKeyUp(): Event<KeyboardEvent> { return this.disposables.add(new DomEmitter(this.view.domNode, 'keyup')).event; } @memoize get onKeyPress(): Event<KeyboardEvent> { return this.disposables.add(new DomEmitter(this.view.domNode, 'keypress')).event; } @memoize get onDidFocus(): Event<void> { return Event.signal(this.disposables.add(new DomEmitter(this.view.domNode, 'focus', true)).event); } @memoize get onDidBlur(): Event<void> { return Event.signal(this.disposables.add(new DomEmitter(this.view.domNode, 'blur', true)).event); } private readonly _onDidDispose = new Emitter<void>(); readonly onDidDispose: Event<void> = this._onDidDispose.event; constructor( private user: string, container: HTMLElement, virtualDelegate: IListVirtualDelegate<T>, renderers: IListRenderer<any /* TODO@joao */, any>[], private _options: IListOptions<T> = DefaultOptions ) { const role = this._options.accessibilityProvider && this._options.accessibilityProvider.getWidgetRole ? this._options.accessibilityProvider?.getWidgetRole() : 'list'; this.selection = new SelectionTrait(role !== 'listbox'); mixin(_options, defaultStyles, false); const baseRenderers: IListRenderer<T, ITraitTemplateData>[] = [this.focus.renderer, this.selection.renderer]; this.accessibilityProvider = _options.accessibilityProvider; if (this.accessibilityProvider) { baseRenderers.push(new AccessibiltyRenderer<T>(this.accessibilityProvider)); this.accessibilityProvider.onDidChangeActiveDescendant?.(this.onDidChangeActiveDescendant, this, this.disposables); } renderers = renderers.map(r => new PipelineRenderer(r.templateId, [...baseRenderers, r])); const viewOptions: IListViewOptions<T> = { ..._options, dnd: _options.dnd && new ListViewDragAndDrop(this, _options.dnd) }; this.view = new ListView(container, virtualDelegate, renderers, viewOptions); this.view.domNode.setAttribute('role', role); if (_options.styleController) { this.styleController = _options.styleController(this.view.domId); } else { const styleElement = createStyleSheet(this.view.domNode); this.styleController = new DefaultStyleController(styleElement, this.view.domId); } this.spliceable = new CombinedSpliceable([ new TraitSpliceable(this.focus, this.view, _options.identityProvider), new TraitSpliceable(this.selection, this.view, _options.identityProvider), new TraitSpliceable(this.anchor, this.view, _options.identityProvider), this.view ]); this.disposables.add(this.focus); this.disposables.add(this.selection); this.disposables.add(this.anchor); this.disposables.add(this.view); this.disposables.add(this._onDidDispose); this.disposables.add(new DOMFocusController(this, this.view)); if (typeof _options.keyboardSupport !== 'boolean' || _options.keyboardSupport) { this.keyboardController = new KeyboardController(this, this.view, _options); this.disposables.add(this.keyboardController); } if (_options.keyboardNavigationLabelProvider) { const delegate = _options.keyboardNavigationDelegate || DefaultKeyboardNavigationDelegate; this.typeNavigationController = new TypeNavigationController(this, this.view, _options.keyboardNavigationLabelProvider, _options.keyboardNavigationEventFilter ?? (() => true), delegate); this.disposables.add(this.typeNavigationController); } this.mouseController = this.createMouseController(_options); this.disposables.add(this.mouseController); this.onDidChangeFocus(this._onFocusChange, this, this.disposables); this.onDidChangeSelection(this._onSelectionChange, this, this.disposables); if (this.accessibilityProvider) { this.ariaLabel = this.accessibilityProvider.getWidgetAriaLabel(); } if (this._options.multipleSelectionSupport !== false) { this.view.domNode.setAttribute('aria-multiselectable', 'true'); } } protected createMouseController(options: IListOptions<T>): MouseController<T> { return new MouseController(this); } updateOptions(optionsUpdate: IListOptionsUpdate = {}): void { this._options = { ...this._options, ...optionsUpdate }; this.typeNavigationController?.updateOptions(this._options); if (this._options.multipleSelectionController !== undefined) { if (this._options.multipleSelectionSupport) { this.view.domNode.setAttribute('aria-multiselectable', 'true'); } else { this.view.domNode.removeAttribute('aria-multiselectable'); } } this.mouseController.updateOptions(optionsUpdate); this.keyboardController?.updateOptions(optionsUpdate); this.view.updateOptions(optionsUpdate); } get options(): IListOptions<T> { return this._options; } splice(start: number, deleteCount: number, elements: readonly T[] = []): void { if (start < 0 || start > this.view.length) { throw new ListError(this.user, `Invalid start index: ${start}`); } if (deleteCount < 0) { throw new ListError(this.user, `Invalid delete count: ${deleteCount}`); } if (deleteCount === 0 && elements.length === 0) { return; } this.eventBufferer.bufferEvents(() => this.spliceable.splice(start, deleteCount, elements)); } updateWidth(index: number): void { this.view.updateWidth(index); } updateElementHeight(index: number, size: number): void { this.view.updateElementHeight(index, size, null); } rerender(): void { this.view.rerender(); } element(index: number): T { return this.view.element(index); } indexOf(element: T): number { return this.view.indexOf(element); } get length(): number { return this.view.length; } get contentHeight(): number { return this.view.contentHeight; } get onDidChangeContentHeight(): Event<number> { return this.view.onDidChangeContentHeight; } get scrollTop(): number { return this.view.getScrollTop(); } set scrollTop(scrollTop: number) { this.view.setScrollTop(scrollTop); } get scrollLeft(): number { return this.view.getScrollLeft(); } set scrollLeft(scrollLeft: number) { this.view.setScrollLeft(scrollLeft); } get scrollHeight(): number { return this.view.scrollHeight; } get renderHeight(): number { return this.view.renderHeight; } get firstVisibleIndex(): number { return this.view.firstVisibleIndex; } get lastVisibleIndex(): number { return this.view.lastVisibleIndex; } get ariaLabel(): string { return this._ariaLabel; } set ariaLabel(value: string) { this._ariaLabel = value; this.view.domNode.setAttribute('aria-label', value); } domFocus(): void { this.view.domNode.focus({ preventScroll: true }); } layout(height?: number, width?: number): void { this.view.layout(height, width); } triggerTypeNavigation(): void { this.typeNavigationController?.trigger(); } setSelection(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this.selection.set(indexes, browserEvent); } getSelection(): number[] { return this.selection.get(); } getSelectedElements(): T[] { return this.getSelection().map(i => this.view.element(i)); } setAnchor(index: number | undefined): void { if (typeof index === 'undefined') { this.anchor.set([]); return; } if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } this.anchor.set([index]); } getAnchor(): number | undefined { return firstOrDefault(this.anchor.get(), undefined); } getAnchorElement(): T | undefined { const anchor = this.getAnchor(); return typeof anchor === 'undefined' ? undefined : this.element(anchor); } setFocus(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this.focus.set(indexes, browserEvent); } focusNext(n = 1, loop = false, browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const focus = this.focus.get(); const index = this.findNextIndex(focus.length > 0 ? focus[0] + n : 0, loop, filter); if (index > -1) { this.setFocus([index], browserEvent); } } focusPrevious(n = 1, loop = false, browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const focus = this.focus.get(); const index = this.findPreviousIndex(focus.length > 0 ? focus[0] - n : 0, loop, filter); if (index > -1) { this.setFocus([index], browserEvent); } } async focusNextPage(browserEvent?: UIEvent, filter?: (element: T) => boolean): Promise<void> { let lastPageIndex = this.view.indexAt(this.view.getScrollTop() + this.view.renderHeight); lastPageIndex = lastPageIndex === 0 ? 0 : lastPageIndex - 1; const currentlyFocusedElementIndex = this.getFocus()[0]; if (currentlyFocusedElementIndex !== lastPageIndex && (currentlyFocusedElementIndex === undefined || lastPageIndex > currentlyFocusedElementIndex)) { const lastGoodPageIndex = this.findPreviousIndex(lastPageIndex, false, filter); if (lastGoodPageIndex > -1 && currentlyFocusedElementIndex !== lastGoodPageIndex) { this.setFocus([lastGoodPageIndex], browserEvent); } else { this.setFocus([lastPageIndex], browserEvent); } } else { const previousScrollTop = this.view.getScrollTop(); let nextpageScrollTop = previousScrollTop + this.view.renderHeight; if (lastPageIndex > currentlyFocusedElementIndex) { // scroll last page element to the top only if the last page element is below the focused element nextpageScrollTop -= this.view.elementHeight(lastPageIndex); } this.view.setScrollTop(nextpageScrollTop); if (this.view.getScrollTop() !== previousScrollTop) { this.setFocus([]); // Let the scroll event listener run await timeout(0); await this.focusNextPage(browserEvent, filter); } } } async focusPreviousPage(browserEvent?: UIEvent, filter?: (element: T) => boolean): Promise<void> { let firstPageIndex: number; const scrollTop = this.view.getScrollTop(); if (scrollTop === 0) { firstPageIndex = this.view.indexAt(scrollTop); } else { firstPageIndex = this.view.indexAfter(scrollTop - 1); } const currentlyFocusedElementIndex = this.getFocus()[0]; if (currentlyFocusedElementIndex !== firstPageIndex && (currentlyFocusedElementIndex === undefined || currentlyFocusedElementIndex >= firstPageIndex)) { const firstGoodPageIndex = this.findNextIndex(firstPageIndex, false, filter); if (firstGoodPageIndex > -1 && currentlyFocusedElementIndex !== firstGoodPageIndex) { this.setFocus([firstGoodPageIndex], browserEvent); } else { this.setFocus([firstPageIndex], browserEvent); } } else { const previousScrollTop = scrollTop; this.view.setScrollTop(scrollTop - this.view.renderHeight); if (this.view.getScrollTop() !== previousScrollTop) { this.setFocus([]); // Let the scroll event listener run await timeout(0); await this.focusPreviousPage(browserEvent, filter); } } } focusLast(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const index = this.findPreviousIndex(this.length - 1, false, filter); if (index > -1) { this.setFocus([index], browserEvent); } } focusFirst(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { this.focusNth(0, browserEvent, filter); } focusNth(n: number, browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const index = this.findNextIndex(n, false, filter); if (index > -1) { this.setFocus([index], browserEvent); } } private findNextIndex(index: number, loop = false, filter?: (element: T) => boolean): number { for (let i = 0; i < this.length; i++) { if (index >= this.length && !loop) { return -1; } index = index % this.length; if (!filter || filter(this.element(index))) { return index; } index++; } return -1; } private findPreviousIndex(index: number, loop = false, filter?: (element: T) => boolean): number { for (let i = 0; i < this.length; i++) { if (index < 0 && !loop) { return -1; } index = (this.length + (index % this.length)) % this.length; if (!filter || filter(this.element(index))) { return index; } index--; } return -1; } getFocus(): number[] { return this.focus.get(); } getFocusedElements(): T[] { return this.getFocus().map(i => this.view.element(i)); } reveal(index: number, relativeTop?: number): void { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } const scrollTop = this.view.getScrollTop(); const elementTop = this.view.elementTop(index); const elementHeight = this.view.elementHeight(index); if (isNumber(relativeTop)) { // y = mx + b const m = elementHeight - this.view.renderHeight; this.view.setScrollTop(m * clamp(relativeTop, 0, 1) + elementTop); } else { const viewItemBottom = elementTop + elementHeight; const scrollBottom = scrollTop + this.view.renderHeight; if (elementTop < scrollTop && viewItemBottom >= scrollBottom) { // The element is already overflowing the viewport, no-op } else if (elementTop < scrollTop || (viewItemBottom >= scrollBottom && elementHeight >= this.view.renderHeight)) { this.view.setScrollTop(elementTop); } else if (viewItemBottom >= scrollBottom) { this.view.setScrollTop(viewItemBottom - this.view.renderHeight); } } } /** * Returns the relative position of an element rendered in the list. * Returns `null` if the element isn't *entirely* in the visible viewport. */ getRelativeTop(index: number): number | null { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } const scrollTop = this.view.getScrollTop(); const elementTop = this.view.elementTop(index); const elementHeight = this.view.elementHeight(index); if (elementTop < scrollTop || elementTop + elementHeight > scrollTop + this.view.renderHeight) { return null; } // y = mx + b const m = elementHeight - this.view.renderHeight; return Math.abs((scrollTop - elementTop) / m); } isDOMFocused(): boolean { return this.view.domNode === document.activeElement; } getHTMLElement(): HTMLElement { return this.view.domNode; } getElementID(index: number): string { return this.view.getElementDomId(index); } style(styles: IListStyles): void { this.styleController.style(styles); } private toListEvent({ indexes, browserEvent }: ITraitChangeEvent) { return { indexes, elements: indexes.map(i => this.view.element(i)), browserEvent }; } private _onFocusChange(): void { const focus = this.focus.get(); this.view.domNode.classList.toggle('element-focused', focus.length > 0); this.onDidChangeActiveDescendant(); } private onDidChangeActiveDescendant(): void { const focus = this.focus.get(); if (focus.length > 0) { let id: string | undefined; if (this.accessibilityProvider?.getActiveDescendantId) { id = this.accessibilityProvider.getActiveDescendantId(this.view.element(focus[0])); } this.view.domNode.setAttribute('aria-activedescendant', id || this.view.getElementDomId(focus[0])); } else { this.view.domNode.removeAttribute('aria-activedescendant'); } } private _onSelectionChange(): void { const selection = this.selection.get(); this.view.domNode.classList.toggle('selection-none', selection.length === 0); this.view.domNode.classList.toggle('selection-single', selection.length === 1); this.view.domNode.classList.toggle('selection-multiple', selection.length > 1); } dispose(): void { this._onDidDispose.fire(); this.disposables.dispose(); this._onDidDispose.dispose(); } }
src/vs/base/browser/ui/list/listWidget.ts
1
https://github.com/microsoft/vscode/commit/f078e6db483250957314c56c3b12e23dae03d351
[ 0.0014158855192363262, 0.0001830480614444241, 0.00016193689953070134, 0.00016940056229941547, 0.00009636596223572269 ]
{ "id": 5, "code_window": [ "\n", "\t\tif (onTwistie || !this.tree.expandOnDoubleClick) {\n", "\t\t\treturn;\n", "\t\t}\n", "\n", "\t\tsuper.onDoubleClick(e);\n", "\t}\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (e.browserEvent.defaultPrevented) {\n", "\t\t\treturn;\n", "\t\t}\n", "\n" ], "file_path": "src/vs/base/browser/ui/tree/abstractTree.ts", "type": "add", "edit_start_line_idx": 1051 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Lazy } from 'vs/base/common/lazy'; /** * A regex that extracts the link suffix which contains line and column information. */ const linkSuffixRegex = new Lazy<RegExp>(() => { let ri = 0; let ci = 0; function l(): string { return `(?<row${ri++}>\\d+)`; } function c(): string { return `(?<col${ci++}>\\d+)`; } // The comments in the regex below use real strings/numbers for better readability, here's // the legend: // - Path = foo // - Row = 339 // - Col = 12 // // These all support single quote ' in the place of " and [] in the place of () const lineAndColumnRegexClauses = [ // foo:339 // foo:339:12 // foo 339 // foo 339:12 [#140780] // "foo",339 // "foo",339:12 `(?::| |['"],)${l()}(:${c()})?$`, // "foo", line 339 [#40468] // "foo", line 339, col 12 // "foo", line 339, column 12 // "foo":line 339 // "foo":line 339, col 12 // "foo":line 339, column 12 // "foo": line 339 // "foo": line 339, col 12 // "foo": line 339, column 12 // "foo" on line 339 // "foo" on line 339, col 12 // "foo" on line 339, column 12 `['"](?:, |: ?| on )line ${l()}(, col(?:umn)? ${c()})?$`, // foo(339) // foo(339,12) // foo(339, 12) // foo (339) // foo (339,12) // foo (339, 12) ` ?[\\[\\(]${l()}(?:, ?${c()})?[\\]\\)]$`, ]; const suffixClause = lineAndColumnRegexClauses // Join all clauses together .join('|') // Convert spaces to allow the non-breaking space char (ascii 160) .replace(/ /g, `[${'\u00A0'} ]`); return new RegExp(`(${suffixClause})`); }); /** * Removes the optional link suffix which contains line and column information. * @param link The link to parse. */ export function removeLinkSuffix(link: string): string { const suffix = getLinkSuffix(link)?.suffix; if (!suffix) { return link; } return link.substring(0, suffix.index); } /** * Returns the optional link suffix which contains line and column information. * @param link The link to parse. */ export function getLinkSuffix(link: string): { row: number | undefined; col: number | undefined; suffix: { index: number; text: string } } | null { const matches = linkSuffixRegex.getValue().exec(link); const groups = matches?.groups; if (!groups || matches.length < 1) { return null; } const rowString = groups.row0 || groups.row1 || groups.row2; const colString = groups.col0 || groups.col1 || groups.col2; return { row: rowString !== undefined ? parseInt(rowString) : undefined, col: colString !== undefined ? parseInt(colString) : undefined, suffix: { index: matches.index, text: matches[0] } }; }
src/vs/workbench/contrib/terminal/browser/links/terminalLinkParsing.ts
0
https://github.com/microsoft/vscode/commit/f078e6db483250957314c56c3b12e23dae03d351
[ 0.00017680649762041867, 0.0001718820712994784, 0.00016681000124663115, 0.0001724062894936651, 0.0000032321454455086496 ]
{ "id": 5, "code_window": [ "\n", "\t\tif (onTwistie || !this.tree.expandOnDoubleClick) {\n", "\t\t\treturn;\n", "\t\t}\n", "\n", "\t\tsuper.onDoubleClick(e);\n", "\t}\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (e.browserEvent.defaultPrevented) {\n", "\t\t\treturn;\n", "\t\t}\n", "\n" ], "file_path": "src/vs/base/browser/ui/tree/abstractTree.ts", "type": "add", "edit_start_line_idx": 1051 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Connection, TextDocuments, InitializeParams, InitializeResult, ServerCapabilities, ConfigurationRequest, WorkspaceFolder, TextDocumentSyncKind, NotificationType, Disposable, TextDocumentIdentifier, Range, FormattingOptions, TextEdit, Diagnostic } from 'vscode-languageserver'; import { URI } from 'vscode-uri'; import { getCSSLanguageService, getSCSSLanguageService, getLESSLanguageService, LanguageSettings, LanguageService, Stylesheet, TextDocument, Position } from 'vscode-css-languageservice'; import { getLanguageModelCache } from './languageModelCache'; import { runSafeAsync } from './utils/runner'; import { DiagnosticsSupport, registerDiagnosticsPullSupport, registerDiagnosticsPushSupport } from './utils/validation'; import { getDocumentContext } from './utils/documentContext'; import { fetchDataProviders } from './customData'; import { RequestService, getRequestService } from './requests'; namespace CustomDataChangedNotification { export const type: NotificationType<string[]> = new NotificationType('css/customDataChanged'); } export interface Settings { css: LanguageSettings; less: LanguageSettings; scss: LanguageSettings; } export interface RuntimeEnvironment { readonly file?: RequestService; readonly http?: RequestService; readonly timer: { setImmediate(callback: (...args: any[]) => void, ...args: any[]): Disposable; setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): Disposable; }; } export function startServer(connection: Connection, runtime: RuntimeEnvironment) { // Create a text document manager. const documents = new TextDocuments(TextDocument); // Make the text document manager listen on the connection // for open, change and close text document events documents.listen(connection); const stylesheets = getLanguageModelCache<Stylesheet>(10, 60, document => getLanguageService(document).parseStylesheet(document)); documents.onDidClose(e => { stylesheets.onDocumentRemoved(e.document); }); connection.onShutdown(() => { stylesheets.dispose(); }); let scopedSettingsSupport = false; let foldingRangeLimit = Number.MAX_VALUE; let workspaceFolders: WorkspaceFolder[]; let formatterMaxNumberOfEdits = Number.MAX_VALUE; let dataProvidersReady: Promise<any> = Promise.resolve(); let diagnosticsSupport: DiagnosticsSupport | undefined; const languageServices: { [id: string]: LanguageService } = {}; const notReady = () => Promise.reject('Not Ready'); let requestService: RequestService = { getContent: notReady, stat: notReady, readDirectory: notReady }; // After the server has started the client sends an initialize request. The server receives // in the passed params the rootPath of the workspace plus the client capabilities. connection.onInitialize((params: InitializeParams): InitializeResult => { const initializationOptions = params.initializationOptions as any || {}; workspaceFolders = (<any>params).workspaceFolders; if (!Array.isArray(workspaceFolders)) { workspaceFolders = []; if (params.rootPath) { workspaceFolders.push({ name: '', uri: URI.file(params.rootPath).toString(true) }); } } requestService = getRequestService(initializationOptions?.handledSchemas || ['file'], connection, runtime); function getClientCapability<T>(name: string, def: T) { const keys = name.split('.'); let c: any = params.capabilities; for (let i = 0; c && i < keys.length; i++) { if (!c.hasOwnProperty(keys[i])) { return def; } c = c[keys[i]]; } return c; } const snippetSupport = !!getClientCapability('textDocument.completion.completionItem.snippetSupport', false); scopedSettingsSupport = !!getClientCapability('workspace.configuration', false); foldingRangeLimit = getClientCapability('textDocument.foldingRange.rangeLimit', Number.MAX_VALUE); formatterMaxNumberOfEdits = initializationOptions?.customCapabilities?.rangeFormatting?.editLimit || Number.MAX_VALUE; languageServices.css = getCSSLanguageService({ fileSystemProvider: requestService, clientCapabilities: params.capabilities }); languageServices.scss = getSCSSLanguageService({ fileSystemProvider: requestService, clientCapabilities: params.capabilities }); languageServices.less = getLESSLanguageService({ fileSystemProvider: requestService, clientCapabilities: params.capabilities }); const supportsDiagnosticPull = getClientCapability('textDocument.diagnostic', undefined); if (supportsDiagnosticPull === undefined) { diagnosticsSupport = registerDiagnosticsPushSupport(documents, connection, runtime, validateTextDocument); } else { diagnosticsSupport = registerDiagnosticsPullSupport(documents, connection, runtime, validateTextDocument); } const capabilities: ServerCapabilities = { textDocumentSync: TextDocumentSyncKind.Incremental, completionProvider: snippetSupport ? { resolveProvider: false, triggerCharacters: ['/', '-', ':'] } : undefined, hoverProvider: true, documentSymbolProvider: true, referencesProvider: true, definitionProvider: true, documentHighlightProvider: true, documentLinkProvider: { resolveProvider: false }, codeActionProvider: true, renameProvider: true, colorProvider: {}, foldingRangeProvider: true, selectionRangeProvider: true, diagnosticProvider: { documentSelector: null, interFileDependencies: false, workspaceDiagnostics: false }, documentRangeFormattingProvider: initializationOptions?.provideFormatter === true, documentFormattingProvider: initializationOptions?.provideFormatter === true, }; return { capabilities }; }); function getLanguageService(document: TextDocument) { let service = languageServices[document.languageId]; if (!service) { connection.console.log('Document type is ' + document.languageId + ', using css instead.'); service = languageServices['css']; } return service; } let documentSettings: { [key: string]: Thenable<LanguageSettings | undefined> } = {}; // remove document settings on close documents.onDidClose(e => { delete documentSettings[e.document.uri]; }); function getDocumentSettings(textDocument: TextDocument): Thenable<LanguageSettings | undefined> { if (scopedSettingsSupport) { let promise = documentSettings[textDocument.uri]; if (!promise) { const configRequestParam = { items: [{ scopeUri: textDocument.uri, section: textDocument.languageId }] }; promise = connection.sendRequest(ConfigurationRequest.type, configRequestParam).then(s => s[0] as LanguageSettings | undefined); documentSettings[textDocument.uri] = promise; } return promise; } return Promise.resolve(undefined); } // The settings have changed. Is send on server activation as well. connection.onDidChangeConfiguration(change => { updateConfiguration(change.settings as any); }); function updateConfiguration(settings: any) { for (const languageId in languageServices) { languageServices[languageId].configure(settings[languageId]); } // reset all document settings documentSettings = {}; diagnosticsSupport?.requestRefresh(); } async function validateTextDocument(textDocument: TextDocument): Promise<Diagnostic[]> { const settingsPromise = getDocumentSettings(textDocument); const [settings] = await Promise.all([settingsPromise, dataProvidersReady]); const stylesheet = stylesheets.get(textDocument); return getLanguageService(textDocument).doValidation(textDocument, stylesheet, settings); } function updateDataProviders(dataPaths: string[]) { dataProvidersReady = fetchDataProviders(dataPaths, requestService).then(customDataProviders => { for (const lang in languageServices) { languageServices[lang].setDataProviders(true, customDataProviders); } }); } connection.onCompletion((textDocumentPosition, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(textDocumentPosition.textDocument.uri); if (document) { const [settings,] = await Promise.all([getDocumentSettings(document), dataProvidersReady]); const styleSheet = stylesheets.get(document); const documentContext = getDocumentContext(document.uri, workspaceFolders); return getLanguageService(document).doComplete2(document, textDocumentPosition.position, styleSheet, documentContext, settings?.completion); } return null; }, null, `Error while computing completions for ${textDocumentPosition.textDocument.uri}`, token); }); connection.onHover((textDocumentPosition, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(textDocumentPosition.textDocument.uri); if (document) { const [settings,] = await Promise.all([getDocumentSettings(document), dataProvidersReady]); const styleSheet = stylesheets.get(document); return getLanguageService(document).doHover(document, textDocumentPosition.position, styleSheet, settings?.hover); } return null; }, null, `Error while computing hover for ${textDocumentPosition.textDocument.uri}`, token); }); connection.onDocumentSymbol((documentSymbolParams, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(documentSymbolParams.textDocument.uri); if (document) { await dataProvidersReady; const stylesheet = stylesheets.get(document); return getLanguageService(document).findDocumentSymbols2(document, stylesheet); } return []; }, [], `Error while computing document symbols for ${documentSymbolParams.textDocument.uri}`, token); }); connection.onDefinition((documentDefinitionParams, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(documentDefinitionParams.textDocument.uri); if (document) { await dataProvidersReady; const stylesheet = stylesheets.get(document); return getLanguageService(document).findDefinition(document, documentDefinitionParams.position, stylesheet); } return null; }, null, `Error while computing definitions for ${documentDefinitionParams.textDocument.uri}`, token); }); connection.onDocumentHighlight((documentHighlightParams, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(documentHighlightParams.textDocument.uri); if (document) { await dataProvidersReady; const stylesheet = stylesheets.get(document); return getLanguageService(document).findDocumentHighlights(document, documentHighlightParams.position, stylesheet); } return []; }, [], `Error while computing document highlights for ${documentHighlightParams.textDocument.uri}`, token); }); connection.onDocumentLinks(async (documentLinkParams, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(documentLinkParams.textDocument.uri); if (document) { await dataProvidersReady; const documentContext = getDocumentContext(document.uri, workspaceFolders); const stylesheet = stylesheets.get(document); return getLanguageService(document).findDocumentLinks2(document, stylesheet, documentContext); } return []; }, [], `Error while computing document links for ${documentLinkParams.textDocument.uri}`, token); }); connection.onReferences((referenceParams, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(referenceParams.textDocument.uri); if (document) { await dataProvidersReady; const stylesheet = stylesheets.get(document); return getLanguageService(document).findReferences(document, referenceParams.position, stylesheet); } return []; }, [], `Error while computing references for ${referenceParams.textDocument.uri}`, token); }); connection.onCodeAction((codeActionParams, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(codeActionParams.textDocument.uri); if (document) { await dataProvidersReady; const stylesheet = stylesheets.get(document); return getLanguageService(document).doCodeActions(document, codeActionParams.range, codeActionParams.context, stylesheet); } return []; }, [], `Error while computing code actions for ${codeActionParams.textDocument.uri}`, token); }); connection.onDocumentColor((params, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(params.textDocument.uri); if (document) { await dataProvidersReady; const stylesheet = stylesheets.get(document); return getLanguageService(document).findDocumentColors(document, stylesheet); } return []; }, [], `Error while computing document colors for ${params.textDocument.uri}`, token); }); connection.onColorPresentation((params, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(params.textDocument.uri); if (document) { await dataProvidersReady; const stylesheet = stylesheets.get(document); return getLanguageService(document).getColorPresentations(document, stylesheet, params.color, params.range); } return []; }, [], `Error while computing color presentations for ${params.textDocument.uri}`, token); }); connection.onRenameRequest((renameParameters, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(renameParameters.textDocument.uri); if (document) { await dataProvidersReady; const stylesheet = stylesheets.get(document); return getLanguageService(document).doRename(document, renameParameters.position, renameParameters.newName, stylesheet); } return null; }, null, `Error while computing renames for ${renameParameters.textDocument.uri}`, token); }); connection.onFoldingRanges((params, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(params.textDocument.uri); if (document) { await dataProvidersReady; return getLanguageService(document).getFoldingRanges(document, { rangeLimit: foldingRangeLimit }); } return null; }, null, `Error while computing folding ranges for ${params.textDocument.uri}`, token); }); connection.onSelectionRanges((params, token) => { return runSafeAsync(runtime, async () => { const document = documents.get(params.textDocument.uri); const positions: Position[] = params.positions; if (document) { await dataProvidersReady; const stylesheet = stylesheets.get(document); return getLanguageService(document).getSelectionRanges(document, positions, stylesheet); } return []; }, [], `Error while computing selection ranges for ${params.textDocument.uri}`, token); }); async function onFormat(textDocument: TextDocumentIdentifier, range: Range | undefined, options: FormattingOptions): Promise<TextEdit[]> { const document = documents.get(textDocument.uri); if (document) { const edits = getLanguageService(document).format(document, range ?? getFullRange(document), options); if (edits.length > formatterMaxNumberOfEdits) { const newText = TextDocument.applyEdits(document, edits); return [TextEdit.replace(getFullRange(document), newText)]; } return edits; } return []; } connection.onDocumentRangeFormatting((formatParams, token) => { return runSafeAsync(runtime, () => onFormat(formatParams.textDocument, formatParams.range, formatParams.options), [], `Error while formatting range for ${formatParams.textDocument.uri}`, token); }); connection.onDocumentFormatting((formatParams, token) => { return runSafeAsync(runtime, () => onFormat(formatParams.textDocument, undefined, formatParams.options), [], `Error while formatting ${formatParams.textDocument.uri}`, token); }); connection.onNotification(CustomDataChangedNotification.type, updateDataProviders); // Listen on the connection connection.listen(); } function getFullRange(document: TextDocument): Range { return Range.create(Position.create(0, 0), document.positionAt(document.getText().length)); }
extensions/css-language-features/server/src/cssServer.ts
0
https://github.com/microsoft/vscode/commit/f078e6db483250957314c56c3b12e23dae03d351
[ 0.00017517691594548523, 0.000171330088051036, 0.00016435509314760566, 0.0001718897110549733, 0.000002439340960336267 ]
{ "id": 5, "code_window": [ "\n", "\t\tif (onTwistie || !this.tree.expandOnDoubleClick) {\n", "\t\t\treturn;\n", "\t\t}\n", "\n", "\t\tsuper.onDoubleClick(e);\n", "\t}\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (e.browserEvent.defaultPrevented) {\n", "\t\t\treturn;\n", "\t\t}\n", "\n" ], "file_path": "src/vs/base/browser/ui/tree/abstractTree.ts", "type": "add", "edit_start_line_idx": 1051 }
code-processed.iss
build/win32/.gitignore
0
https://github.com/microsoft/vscode/commit/f078e6db483250957314c56c3b12e23dae03d351
[ 0.00017503164417576045, 0.00017503164417576045, 0.00017503164417576045, 0.00017503164417576045, 0 ]
{ "id": 0, "code_window": [ " source: string | Function,\n", " cb: Function,\n", " options?: WatchOptions\n", "): () => void {\n", " const ctx = this.renderProxy!\n", " const getter = isString(source) ? () => ctx[source] : source.bind(ctx)\n", " const stop = watch(getter, cb.bind(ctx), options)\n", " onBeforeUnmount(stop, this)\n", " return stop\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "): StopHandle {\n" ], "file_path": "packages/runtime-core/src/apiWatch.ts", "type": "replace", "edit_start_line_idx": 211 }
import { ComponentInternalInstance, Data } from './component' import { nextTick } from './scheduler' import { instanceWatch } from './apiWatch' import { EMPTY_OBJ, hasOwn, globalsWhitelist } from '@vue/shared' import { ExtractComputedReturns } from './apiOptions' import { UnwrapRef } from '@vue/reactivity' import { warn } from './warning' // public properties exposed on the proxy, which is used as the render context // in templates (as `this` in the render option) export type ComponentPublicInstance< P = {}, B = {}, D = {}, C = {}, M = {}, PublicProps = P > = { [key: string]: any $data: D $props: PublicProps $attrs: Data $refs: Data $slots: Data $root: ComponentInternalInstance | null $parent: ComponentInternalInstance | null $emit: (event: string, ...args: unknown[]) => void } & P & UnwrapRef<B> & D & ExtractComputedReturns<C> & M export const PublicInstanceProxyHandlers = { get(target: ComponentInternalInstance, key: string) { const { renderContext, data, props, propsProxy } = target if (data !== EMPTY_OBJ && hasOwn(data, key)) { return data[key] } else if (hasOwn(renderContext, key)) { return renderContext[key] } else if (hasOwn(props, key)) { // return the value from propsProxy for ref unwrapping and readonly return propsProxy![key] } else { // TODO simplify this? switch (key) { case '$data': return data case '$props': return propsProxy case '$attrs': return target.attrs case '$slots': return target.slots case '$refs': return target.refs case '$parent': return target.parent case '$root': return target.root case '$emit': return target.emit case '$el': return target.vnode.el case '$options': return target.type default: // methods are only exposed when options are supported if (__FEATURE_OPTIONS__) { switch (key) { case '$forceUpdate': return target.update case '$nextTick': return nextTick case '$watch': return instanceWatch.bind(target) } } return target.user[key] } } }, // this trap is only called in browser-compiled render functions that use // `with (this) {}` has(_: any, key: string): boolean { return key[0] !== '_' && !globalsWhitelist.has(key) }, set(target: ComponentInternalInstance, key: string, value: any): boolean { const { data, renderContext } = target if (data !== EMPTY_OBJ && hasOwn(data, key)) { data[key] = value } else if (hasOwn(renderContext, key)) { renderContext[key] = value } else if (key[0] === '$' && key.slice(1) in target) { __DEV__ && warn( `Attempting to mutate public property "${key}". ` + `Properties starting with $ are reserved and readonly.`, target ) return false } else if (key in target.props) { __DEV__ && warn(`Attempting to mutate prop "${key}". Props are readonly.`, target) return false } else { target.user[key] = value } return true } }
packages/runtime-core/src/componentProxy.ts
1
https://github.com/vuejs/core/commit/f3760f7d34b8aeeebd96bf224d805b22baf6c11f
[ 0.00017833983292803168, 0.000173101550899446, 0.00016549347492400557, 0.0001735507685225457, 0.0000045005376705375966 ]
{ "id": 0, "code_window": [ " source: string | Function,\n", " cb: Function,\n", " options?: WatchOptions\n", "): () => void {\n", " const ctx = this.renderProxy!\n", " const getter = isString(source) ? () => ctx[source] : source.bind(ctx)\n", " const stop = watch(getter, cb.bind(ctx), options)\n", " onBeforeUnmount(stop, this)\n", " return stop\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "): StopHandle {\n" ], "file_path": "packages/runtime-core/src/apiWatch.ts", "type": "replace", "edit_start_line_idx": 211 }
'use strict' if (process.env.NODE_ENV === 'production') { module.exports = require('./dist/server-renderer.cjs.prod.js') } else { module.exports = require('./dist/server-renderer.cjs.js') }
packages/server-renderer/index.js
0
https://github.com/vuejs/core/commit/f3760f7d34b8aeeebd96bf224d805b22baf6c11f
[ 0.00017544554430060089, 0.00017544554430060089, 0.00017544554430060089, 0.00017544554430060089, 0 ]
{ "id": 0, "code_window": [ " source: string | Function,\n", " cb: Function,\n", " options?: WatchOptions\n", "): () => void {\n", " const ctx = this.renderProxy!\n", " const getter = isString(source) ? () => ctx[source] : source.bind(ctx)\n", " const stop = watch(getter, cb.bind(ctx), options)\n", " onBeforeUnmount(stop, this)\n", " return stop\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "): StopHandle {\n" ], "file_path": "packages/runtime-core/src/apiWatch.ts", "type": "replace", "edit_start_line_idx": 211 }
import { h, render, nodeOps, NodeTypes, TestElement, TestText, ref, reactive, dumpOps, resetOps, NodeOpTypes, nextTick, serialize, triggerEvent, mockWarn } from '../src' describe('test renderer', () => { mockWarn() it('should work', () => { const root = nodeOps.createElement('div') render( h( 'div', { id: 'test' }, 'hello' ), root ) expect(root.children.length).toBe(1) const el = root.children[0] as TestElement expect(el.type).toBe(NodeTypes.ELEMENT) expect(el.props.id).toBe('test') expect(el.children.length).toBe(1) const text = el.children[0] as TestText expect(text.type).toBe(NodeTypes.TEXT) expect(text.text).toBe('hello') }) it('should record ops', async () => { const state = reactive({ id: 'test', text: 'hello' }) const App = { render() { return h( 'div', { id: state.id }, state.text ) } } const root = nodeOps.createElement('div') resetOps() render(h(App), root) const ops = dumpOps() expect(ops.length).toBe(4) expect(ops[0]).toEqual({ type: NodeOpTypes.CREATE, nodeType: NodeTypes.ELEMENT, tag: 'div', targetNode: root.children[0] }) expect(ops[1]).toEqual({ type: NodeOpTypes.PATCH, targetNode: root.children[0], propKey: 'id', propPrevValue: null, propNextValue: 'test' }) expect(ops[2]).toEqual({ type: NodeOpTypes.SET_ELEMENT_TEXT, text: 'hello', targetNode: root.children[0] }) expect(ops[3]).toEqual({ type: NodeOpTypes.INSERT, targetNode: root.children[0], parentNode: root, refNode: null }) // test update ops state.id = 'foo' state.text = 'bar' await nextTick() const updateOps = dumpOps() expect(updateOps.length).toBe(2) expect(updateOps[0]).toEqual({ type: NodeOpTypes.PATCH, targetNode: root.children[0], propKey: 'id', propPrevValue: 'test', propNextValue: 'foo' }) expect(updateOps[1]).toEqual({ type: NodeOpTypes.SET_ELEMENT_TEXT, targetNode: root.children[0], text: 'bar' }) }) it('should be able to serialize nodes', () => { const App = { render() { return h( 'div', { id: 'test' }, [h('span', 'foo'), 'hello'] ) } } const root = nodeOps.createElement('div') render(h(App), root) expect(serialize(root)).toEqual( `<div><div id="test"><span>foo</span>hello</div></div>` ) // indented output expect(serialize(root, 2)).toEqual( `<div> <div id="test"> <span> foo </span> hello </div> </div>` ) }) it('should be able to trigger events', async () => { const count = ref(0) const App = () => { return h( 'span', { onClick: () => { count.value++ } }, count.value ) } const root = nodeOps.createElement('div') render(h(App), root) triggerEvent(root.children[0] as TestElement, 'click') expect(count.value).toBe(1) await nextTick() expect(serialize(root)).toBe(`<div><span>1</span></div>`) }) it('should be able to trigger events with muliple listeners', async () => { const count = ref(0) const count2 = ref(1) const App = () => { return h( 'span', { onClick: [ () => { count.value++ }, () => { count2.value++ } ] }, `${count.value}, ${count2.value}` ) } const root = nodeOps.createElement('div') render(h(App), root) triggerEvent(root.children[0] as TestElement, 'click') expect(count.value).toBe(1) expect(count2.value).toBe(2) await nextTick() expect(serialize(root)).toBe(`<div><span>1, 2</span></div>`) }) it('should mock warn', () => { console.warn('warn!!!') expect('warn!!!').toHaveBeenWarned() expect('warn!!!').toHaveBeenWarnedTimes(1) console.warn('warn!!!') expect('warn!!!').toHaveBeenWarnedTimes(2) console.warn('warning') expect('warn!!!').toHaveBeenWarnedTimes(2) expect('warning').toHaveBeenWarnedLast() }) })
packages/runtime-test/__tests__/testRuntime.spec.ts
0
https://github.com/vuejs/core/commit/f3760f7d34b8aeeebd96bf224d805b22baf6c11f
[ 0.00018128597002942115, 0.00017564363952260464, 0.00016842182958498597, 0.00017645749903749675, 0.000003940911938116187 ]
{ "id": 0, "code_window": [ " source: string | Function,\n", " cb: Function,\n", " options?: WatchOptions\n", "): () => void {\n", " const ctx = this.renderProxy!\n", " const getter = isString(source) ? () => ctx[source] : source.bind(ctx)\n", " const stop = watch(getter, cb.bind(ctx), options)\n", " onBeforeUnmount(stop, this)\n", " return stop\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "): StopHandle {\n" ], "file_path": "packages/runtime-core/src/apiWatch.ts", "type": "replace", "edit_start_line_idx": 211 }
import { Position, NodeTypes } from '../src/ast' import { getInnerRange, advancePositionWithClone, isEmptyExpression } from '../src/utils' function p(line: number, column: number, offset: number): Position { return { column, line, offset } } describe('advancePositionWithClone', () => { test('same line', () => { const pos = p(1, 1, 0) const newPos = advancePositionWithClone(pos, 'foo\nbar', 2) expect(newPos.column).toBe(3) expect(newPos.line).toBe(1) expect(newPos.offset).toBe(2) }) test('same line', () => { const pos = p(1, 1, 0) const newPos = advancePositionWithClone(pos, 'foo\nbar', 4) expect(newPos.column).toBe(1) expect(newPos.line).toBe(2) expect(newPos.offset).toBe(4) }) test('multiple lines', () => { const pos = p(1, 1, 0) const newPos = advancePositionWithClone(pos, 'foo\nbar\nbaz', 10) expect(newPos.column).toBe(3) expect(newPos.line).toBe(3) expect(newPos.offset).toBe(10) }) }) describe('getInnerRange', () => { const loc1 = { source: 'foo\nbar\nbaz', start: p(1, 1, 0), end: p(3, 3, 11) } test('at start', () => { const loc2 = getInnerRange(loc1, 0, 4) expect(loc2.start).toEqual(loc1.start) expect(loc2.end.column).toBe(1) expect(loc2.end.line).toBe(2) expect(loc2.end.offset).toBe(4) }) test('at end', () => { const loc2 = getInnerRange(loc1, 4) expect(loc2.start.column).toBe(1) expect(loc2.start.line).toBe(2) expect(loc2.start.offset).toBe(4) expect(loc2.end).toEqual(loc1.end) }) test('in between', () => { const loc2 = getInnerRange(loc1, 4, 3) expect(loc2.start.column).toBe(1) expect(loc2.start.line).toBe(2) expect(loc2.start.offset).toBe(4) expect(loc2.end.column).toBe(4) expect(loc2.end.line).toBe(2) expect(loc2.end.offset).toBe(7) }) }) describe('isEmptyExpression', () => { test('empty', () => { expect( isEmptyExpression({ content: '', type: NodeTypes.SIMPLE_EXPRESSION, isStatic: true, loc: null as any }) ).toBe(true) }) test('spaces', () => { expect( isEmptyExpression({ content: ' \t ', type: NodeTypes.SIMPLE_EXPRESSION, isStatic: true, loc: null as any }) ).toBe(true) }) test('identifier', () => { expect( isEmptyExpression({ content: 'foo', type: NodeTypes.SIMPLE_EXPRESSION, isStatic: true, loc: null as any }) ).toBe(false) }) })
packages/compiler-core/__tests__/utils.spec.ts
0
https://github.com/vuejs/core/commit/f3760f7d34b8aeeebd96bf224d805b22baf6c11f
[ 0.0001809022796805948, 0.00017736271547619253, 0.00017458494403399527, 0.00017761638446245342, 0.0000019323967990203528 ]
{ "id": 1, "code_window": [ "import { ComponentInternalInstance, Data } from './component'\n", "import { nextTick } from './scheduler'\n", "import { instanceWatch } from './apiWatch'\n", "import { EMPTY_OBJ, hasOwn, globalsWhitelist } from '@vue/shared'\n", "import { ExtractComputedReturns } from './apiOptions'\n", "import { UnwrapRef } from '@vue/reactivity'\n", "import { warn } from './warning'\n", "\n", "// public properties exposed on the proxy, which is used as the render context\n", "// in templates (as `this` in the render option)\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { UnwrapRef, ReactiveEffect } from '@vue/reactivity'\n" ], "file_path": "packages/runtime-core/src/componentProxy.ts", "type": "replace", "edit_start_line_idx": 5 }
import { ComponentInternalInstance, Data } from './component' import { nextTick } from './scheduler' import { instanceWatch } from './apiWatch' import { EMPTY_OBJ, hasOwn, globalsWhitelist } from '@vue/shared' import { ExtractComputedReturns } from './apiOptions' import { UnwrapRef } from '@vue/reactivity' import { warn } from './warning' // public properties exposed on the proxy, which is used as the render context // in templates (as `this` in the render option) export type ComponentPublicInstance< P = {}, B = {}, D = {}, C = {}, M = {}, PublicProps = P > = { [key: string]: any $data: D $props: PublicProps $attrs: Data $refs: Data $slots: Data $root: ComponentInternalInstance | null $parent: ComponentInternalInstance | null $emit: (event: string, ...args: unknown[]) => void } & P & UnwrapRef<B> & D & ExtractComputedReturns<C> & M export const PublicInstanceProxyHandlers = { get(target: ComponentInternalInstance, key: string) { const { renderContext, data, props, propsProxy } = target if (data !== EMPTY_OBJ && hasOwn(data, key)) { return data[key] } else if (hasOwn(renderContext, key)) { return renderContext[key] } else if (hasOwn(props, key)) { // return the value from propsProxy for ref unwrapping and readonly return propsProxy![key] } else { // TODO simplify this? switch (key) { case '$data': return data case '$props': return propsProxy case '$attrs': return target.attrs case '$slots': return target.slots case '$refs': return target.refs case '$parent': return target.parent case '$root': return target.root case '$emit': return target.emit case '$el': return target.vnode.el case '$options': return target.type default: // methods are only exposed when options are supported if (__FEATURE_OPTIONS__) { switch (key) { case '$forceUpdate': return target.update case '$nextTick': return nextTick case '$watch': return instanceWatch.bind(target) } } return target.user[key] } } }, // this trap is only called in browser-compiled render functions that use // `with (this) {}` has(_: any, key: string): boolean { return key[0] !== '_' && !globalsWhitelist.has(key) }, set(target: ComponentInternalInstance, key: string, value: any): boolean { const { data, renderContext } = target if (data !== EMPTY_OBJ && hasOwn(data, key)) { data[key] = value } else if (hasOwn(renderContext, key)) { renderContext[key] = value } else if (key[0] === '$' && key.slice(1) in target) { __DEV__ && warn( `Attempting to mutate public property "${key}". ` + `Properties starting with $ are reserved and readonly.`, target ) return false } else if (key in target.props) { __DEV__ && warn(`Attempting to mutate prop "${key}". Props are readonly.`, target) return false } else { target.user[key] = value } return true } }
packages/runtime-core/src/componentProxy.ts
1
https://github.com/vuejs/core/commit/f3760f7d34b8aeeebd96bf224d805b22baf6c11f
[ 0.9967051148414612, 0.08356302231550217, 0.00016823066107463092, 0.0003354086074978113, 0.2753234803676605 ]
{ "id": 1, "code_window": [ "import { ComponentInternalInstance, Data } from './component'\n", "import { nextTick } from './scheduler'\n", "import { instanceWatch } from './apiWatch'\n", "import { EMPTY_OBJ, hasOwn, globalsWhitelist } from '@vue/shared'\n", "import { ExtractComputedReturns } from './apiOptions'\n", "import { UnwrapRef } from '@vue/reactivity'\n", "import { warn } from './warning'\n", "\n", "// public properties exposed on the proxy, which is used as the render context\n", "// in templates (as `this` in the render option)\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { UnwrapRef, ReactiveEffect } from '@vue/reactivity'\n" ], "file_path": "packages/runtime-core/src/componentProxy.ts", "type": "replace", "edit_start_line_idx": 5 }
import { Position, NodeTypes } from '../src/ast' import { getInnerRange, advancePositionWithClone, isEmptyExpression } from '../src/utils' function p(line: number, column: number, offset: number): Position { return { column, line, offset } } describe('advancePositionWithClone', () => { test('same line', () => { const pos = p(1, 1, 0) const newPos = advancePositionWithClone(pos, 'foo\nbar', 2) expect(newPos.column).toBe(3) expect(newPos.line).toBe(1) expect(newPos.offset).toBe(2) }) test('same line', () => { const pos = p(1, 1, 0) const newPos = advancePositionWithClone(pos, 'foo\nbar', 4) expect(newPos.column).toBe(1) expect(newPos.line).toBe(2) expect(newPos.offset).toBe(4) }) test('multiple lines', () => { const pos = p(1, 1, 0) const newPos = advancePositionWithClone(pos, 'foo\nbar\nbaz', 10) expect(newPos.column).toBe(3) expect(newPos.line).toBe(3) expect(newPos.offset).toBe(10) }) }) describe('getInnerRange', () => { const loc1 = { source: 'foo\nbar\nbaz', start: p(1, 1, 0), end: p(3, 3, 11) } test('at start', () => { const loc2 = getInnerRange(loc1, 0, 4) expect(loc2.start).toEqual(loc1.start) expect(loc2.end.column).toBe(1) expect(loc2.end.line).toBe(2) expect(loc2.end.offset).toBe(4) }) test('at end', () => { const loc2 = getInnerRange(loc1, 4) expect(loc2.start.column).toBe(1) expect(loc2.start.line).toBe(2) expect(loc2.start.offset).toBe(4) expect(loc2.end).toEqual(loc1.end) }) test('in between', () => { const loc2 = getInnerRange(loc1, 4, 3) expect(loc2.start.column).toBe(1) expect(loc2.start.line).toBe(2) expect(loc2.start.offset).toBe(4) expect(loc2.end.column).toBe(4) expect(loc2.end.line).toBe(2) expect(loc2.end.offset).toBe(7) }) }) describe('isEmptyExpression', () => { test('empty', () => { expect( isEmptyExpression({ content: '', type: NodeTypes.SIMPLE_EXPRESSION, isStatic: true, loc: null as any }) ).toBe(true) }) test('spaces', () => { expect( isEmptyExpression({ content: ' \t ', type: NodeTypes.SIMPLE_EXPRESSION, isStatic: true, loc: null as any }) ).toBe(true) }) test('identifier', () => { expect( isEmptyExpression({ content: 'foo', type: NodeTypes.SIMPLE_EXPRESSION, isStatic: true, loc: null as any }) ).toBe(false) }) })
packages/compiler-core/__tests__/utils.spec.ts
0
https://github.com/vuejs/core/commit/f3760f7d34b8aeeebd96bf224d805b22baf6c11f
[ 0.00017557975661475211, 0.00017299667524639517, 0.0001703733141766861, 0.00017268826195504516, 0.000001956720780071919 ]
{ "id": 1, "code_window": [ "import { ComponentInternalInstance, Data } from './component'\n", "import { nextTick } from './scheduler'\n", "import { instanceWatch } from './apiWatch'\n", "import { EMPTY_OBJ, hasOwn, globalsWhitelist } from '@vue/shared'\n", "import { ExtractComputedReturns } from './apiOptions'\n", "import { UnwrapRef } from '@vue/reactivity'\n", "import { warn } from './warning'\n", "\n", "// public properties exposed on the proxy, which is used as the render context\n", "// in templates (as `this` in the render option)\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { UnwrapRef, ReactiveEffect } from '@vue/reactivity'\n" ], "file_path": "packages/runtime-core/src/componentProxy.ts", "type": "replace", "edit_start_line_idx": 5 }
import { ref, reactive } from '@vue/reactivity' import { renderToString, h, nodeOps, render, serializeInner, nextTick, watch, createComponent, triggerEvent, TestElement } from '@vue/runtime-test' // reference: https://vue-composition-api-rfc.netlify.com/api.html#setup describe('api: setup context', () => { it('should expose return values to template render context', () => { const Comp = createComponent({ setup() { return { // ref should auto-unwrap ref: ref('foo'), // object exposed as-is object: reactive({ msg: 'bar' }), // primitive value exposed as-is value: 'baz' } }, render() { return `${this.ref} ${this.object.msg} ${this.value}` } }) expect(renderToString(h(Comp))).toMatch(`foo bar baz`) }) it('should support returning render function', () => { const Comp = { setup() { return () => { return h('div', 'hello') } } } expect(renderToString(h(Comp))).toMatch(`hello`) }) it('props', async () => { const count = ref(0) let dummy const Parent = { render: () => h(Child, { count: count.value }) } const Child = createComponent({ setup(props: { count: number }) { watch(() => { dummy = props.count }) return () => h('div', props.count) } }) const root = nodeOps.createElement('div') render(h(Parent), root) expect(serializeInner(root)).toMatch(`<div>0</div>`) expect(dummy).toBe(0) // props should be reactive count.value++ await nextTick() expect(serializeInner(root)).toMatch(`<div>1</div>`) expect(dummy).toBe(1) }) it('setup props should resolve the correct types from props object', async () => { const count = ref(0) let dummy const Parent = { render: () => h(Child, { count: count.value }) } const Child = createComponent({ props: { count: Number }, setup(props) { watch(() => { dummy = props.count }) return () => h('div', props.count) } }) const root = nodeOps.createElement('div') render(h(Parent), root) expect(serializeInner(root)).toMatch(`<div>0</div>`) expect(dummy).toBe(0) // props should be reactive count.value++ await nextTick() expect(serializeInner(root)).toMatch(`<div>1</div>`) expect(dummy).toBe(1) }) it('context.attrs', async () => { const toggle = ref(true) const Parent = { render: () => h(Child, toggle.value ? { id: 'foo' } : { class: 'baz' }) } const Child = { // explicit empty props declaration // puts everything received in attrs props: {}, setup(props: any, { attrs }: any) { return () => h('div', attrs) } } const root = nodeOps.createElement('div') render(h(Parent), root) expect(serializeInner(root)).toMatch(`<div id="foo"></div>`) // should update even though it's not reactive toggle.value = false await nextTick() expect(serializeInner(root)).toMatch(`<div class="baz"></div>`) }) it('context.slots', async () => { const id = ref('foo') const Parent = { render: () => h(Child, null, { foo: () => id.value, bar: () => 'bar' }) } const Child = { setup(props: any, { slots }: any) { return () => h('div', [...slots.foo(), ...slots.bar()]) } } const root = nodeOps.createElement('div') render(h(Parent), root) expect(serializeInner(root)).toMatch(`<div>foobar</div>`) // should update even though it's not reactive id.value = 'baz' await nextTick() expect(serializeInner(root)).toMatch(`<div>bazbar</div>`) }) it('context.emit', async () => { const count = ref(0) const spy = jest.fn() const Parent = { render: () => h(Child, { count: count.value, onInc: (newVal: number) => { spy() count.value = newVal } }) } const Child = createComponent({ props: { count: { type: Number, default: 1 } }, setup(props, { emit }) { return () => h( 'div', { onClick: () => emit('inc', props.count + 1) }, props.count ) } }) const root = nodeOps.createElement('div') render(h(Parent), root) expect(serializeInner(root)).toMatch(`<div>0</div>`) // emit should trigger parent handler triggerEvent(root.children[0] as TestElement, 'click') expect(spy).toHaveBeenCalled() await nextTick() expect(serializeInner(root)).toMatch(`<div>1</div>`) }) })
packages/runtime-core/__tests__/apiSetupContext.spec.ts
0
https://github.com/vuejs/core/commit/f3760f7d34b8aeeebd96bf224d805b22baf6c11f
[ 0.0003610900021158159, 0.00017865042900666595, 0.00016272554057650268, 0.00016824911290314049, 0.00004102378443349153 ]
{ "id": 1, "code_window": [ "import { ComponentInternalInstance, Data } from './component'\n", "import { nextTick } from './scheduler'\n", "import { instanceWatch } from './apiWatch'\n", "import { EMPTY_OBJ, hasOwn, globalsWhitelist } from '@vue/shared'\n", "import { ExtractComputedReturns } from './apiOptions'\n", "import { UnwrapRef } from '@vue/reactivity'\n", "import { warn } from './warning'\n", "\n", "// public properties exposed on the proxy, which is used as the render context\n", "// in templates (as `this` in the render option)\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { UnwrapRef, ReactiveEffect } from '@vue/reactivity'\n" ], "file_path": "packages/runtime-core/src/componentProxy.ts", "type": "replace", "edit_start_line_idx": 5 }
import { isArray, isPlainObject, objectToString } from '@vue/shared' // for converting {{ interpolation }} values to displayed strings. export function toString(val: any): string { return val == null ? '' : isArray(val) || (isPlainObject(val) && val.toString === objectToString) ? JSON.stringify(val, null, 2) : String(val) }
packages/runtime-core/src/helpers/toString.ts
0
https://github.com/vuejs/core/commit/f3760f7d34b8aeeebd96bf224d805b22baf6c11f
[ 0.00016762972518336028, 0.0001666327880229801, 0.00016563586541451514, 0.0001666327880229801, 9.969298844225705e-7 ]
{ "id": 2, "code_window": [ " $root: ComponentInternalInstance | null\n", " $parent: ComponentInternalInstance | null\n", " $emit: (event: string, ...args: unknown[]) => void\n", "} & P &\n", " UnwrapRef<B> &\n", " D &\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " $el: any\n", " $options: any\n", " $forceUpdate: ReactiveEffect\n", " $nextTick: typeof nextTick\n", " $watch: typeof instanceWatch\n" ], "file_path": "packages/runtime-core/src/componentProxy.ts", "type": "add", "edit_start_line_idx": 27 }
import { ComponentInternalInstance, Data } from './component' import { nextTick } from './scheduler' import { instanceWatch } from './apiWatch' import { EMPTY_OBJ, hasOwn, globalsWhitelist } from '@vue/shared' import { ExtractComputedReturns } from './apiOptions' import { UnwrapRef } from '@vue/reactivity' import { warn } from './warning' // public properties exposed on the proxy, which is used as the render context // in templates (as `this` in the render option) export type ComponentPublicInstance< P = {}, B = {}, D = {}, C = {}, M = {}, PublicProps = P > = { [key: string]: any $data: D $props: PublicProps $attrs: Data $refs: Data $slots: Data $root: ComponentInternalInstance | null $parent: ComponentInternalInstance | null $emit: (event: string, ...args: unknown[]) => void } & P & UnwrapRef<B> & D & ExtractComputedReturns<C> & M export const PublicInstanceProxyHandlers = { get(target: ComponentInternalInstance, key: string) { const { renderContext, data, props, propsProxy } = target if (data !== EMPTY_OBJ && hasOwn(data, key)) { return data[key] } else if (hasOwn(renderContext, key)) { return renderContext[key] } else if (hasOwn(props, key)) { // return the value from propsProxy for ref unwrapping and readonly return propsProxy![key] } else { // TODO simplify this? switch (key) { case '$data': return data case '$props': return propsProxy case '$attrs': return target.attrs case '$slots': return target.slots case '$refs': return target.refs case '$parent': return target.parent case '$root': return target.root case '$emit': return target.emit case '$el': return target.vnode.el case '$options': return target.type default: // methods are only exposed when options are supported if (__FEATURE_OPTIONS__) { switch (key) { case '$forceUpdate': return target.update case '$nextTick': return nextTick case '$watch': return instanceWatch.bind(target) } } return target.user[key] } } }, // this trap is only called in browser-compiled render functions that use // `with (this) {}` has(_: any, key: string): boolean { return key[0] !== '_' && !globalsWhitelist.has(key) }, set(target: ComponentInternalInstance, key: string, value: any): boolean { const { data, renderContext } = target if (data !== EMPTY_OBJ && hasOwn(data, key)) { data[key] = value } else if (hasOwn(renderContext, key)) { renderContext[key] = value } else if (key[0] === '$' && key.slice(1) in target) { __DEV__ && warn( `Attempting to mutate public property "${key}". ` + `Properties starting with $ are reserved and readonly.`, target ) return false } else if (key in target.props) { __DEV__ && warn(`Attempting to mutate prop "${key}". Props are readonly.`, target) return false } else { target.user[key] = value } return true } }
packages/runtime-core/src/componentProxy.ts
1
https://github.com/vuejs/core/commit/f3760f7d34b8aeeebd96bf224d805b22baf6c11f
[ 0.9618868827819824, 0.08087696135044098, 0.0001686987525317818, 0.00021055180695839226, 0.26563695073127747 ]
{ "id": 2, "code_window": [ " $root: ComponentInternalInstance | null\n", " $parent: ComponentInternalInstance | null\n", " $emit: (event: string, ...args: unknown[]) => void\n", "} & P &\n", " UnwrapRef<B> &\n", " D &\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " $el: any\n", " $options: any\n", " $forceUpdate: ReactiveEffect\n", " $nextTick: typeof nextTick\n", " $watch: typeof instanceWatch\n" ], "file_path": "packages/runtime-core/src/componentProxy.ts", "type": "add", "edit_start_line_idx": 27 }
// This package is the "full-build" that includes both the runtime // and the compiler, and supports on-the-fly compilation of the template option. import { compile, CompilerOptions } from '@vue/compiler-dom' import { registerRuntimeCompiler, RenderFunction } from '@vue/runtime-dom' import * as runtimeDom from '@vue/runtime-dom' function compileToFunction( template: string, options?: CompilerOptions ): RenderFunction { const { code } = compile(template, { hoistStatic: true, ...options }) return new Function('Vue', code)(runtimeDom) as RenderFunction } registerRuntimeCompiler(compileToFunction) export { compileToFunction as compile } export * from '@vue/runtime-dom' if (__BROWSER__ && __DEV__) { console[console.info ? 'info' : 'log']( `You are running a development build of Vue.\n` + `Make sure to use the production build (*.prod.js) when deploying for production.` ) }
packages/vue/src/index.ts
0
https://github.com/vuejs/core/commit/f3760f7d34b8aeeebd96bf224d805b22baf6c11f
[ 0.0001756785495672375, 0.00017288920935243368, 0.00016996279009617865, 0.00017302630294580013, 0.0000023354616587312194 ]
{ "id": 2, "code_window": [ " $root: ComponentInternalInstance | null\n", " $parent: ComponentInternalInstance | null\n", " $emit: (event: string, ...args: unknown[]) => void\n", "} & P &\n", " UnwrapRef<B> &\n", " D &\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " $el: any\n", " $options: any\n", " $forceUpdate: ReactiveEffect\n", " $nextTick: typeof nextTick\n", " $watch: typeof instanceWatch\n" ], "file_path": "packages/runtime-core/src/componentProxy.ts", "type": "add", "edit_start_line_idx": 27 }
import { TextModes, ParserOptions, ElementNode, Namespaces, NodeTypes } from '@vue/compiler-core' import { isVoidTag, isHTMLTag, isSVGTag } from '@vue/shared' export const enum DOMNamespaces { HTML = Namespaces.HTML, SVG, MATH_ML } export const parserOptionsMinimal: ParserOptions = { isVoidTag, isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag), // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher getNamespace(tag: string, parent: ElementNode | undefined): DOMNamespaces { let ns = parent ? parent.ns : DOMNamespaces.HTML if (parent && ns === DOMNamespaces.MATH_ML) { if (parent.tag === 'annotation-xml') { if (tag === 'svg') { return DOMNamespaces.SVG } if ( parent.props.some( a => a.type === NodeTypes.ATTRIBUTE && a.name === 'encoding' && a.value != null && (a.value.content === 'text/html' || a.value.content === 'application/xhtml+xml') ) ) { ns = DOMNamespaces.HTML } } else if ( /^m(?:[ions]|text)$/.test(parent.tag) && tag !== 'mglyph' && tag !== 'malignmark' ) { ns = DOMNamespaces.HTML } } else if (parent && ns === DOMNamespaces.SVG) { if ( parent.tag === 'foreignObject' || parent.tag === 'desc' || parent.tag === 'title' ) { ns = DOMNamespaces.HTML } } if (ns === DOMNamespaces.HTML) { if (tag === 'svg') { return DOMNamespaces.SVG } if (tag === 'math') { return DOMNamespaces.MATH_ML } } return ns }, // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments getTextMode(tag: string, ns: DOMNamespaces): TextModes { if (ns === DOMNamespaces.HTML) { if (tag === 'textarea' || tag === 'title') { return TextModes.RCDATA } if ( /^(?:style|xmp|iframe|noembed|noframes|script|noscript)$/i.test(tag) ) { return TextModes.RAWTEXT } } return TextModes.DATA } }
packages/compiler-dom/src/parserOptionsMinimal.ts
0
https://github.com/vuejs/core/commit/f3760f7d34b8aeeebd96bf224d805b22baf6c11f
[ 0.0012215658789500594, 0.00030144478660076857, 0.00017039719386957586, 0.00017476099310442805, 0.0003260413941461593 ]
{ "id": 2, "code_window": [ " $root: ComponentInternalInstance | null\n", " $parent: ComponentInternalInstance | null\n", " $emit: (event: string, ...args: unknown[]) => void\n", "} & P &\n", " UnwrapRef<B> &\n", " D &\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " $el: any\n", " $options: any\n", " $forceUpdate: ReactiveEffect\n", " $nextTick: typeof nextTick\n", " $watch: typeof instanceWatch\n" ], "file_path": "packages/runtime-core/src/componentProxy.ts", "type": "add", "edit_start_line_idx": 27 }
import { ComponentInternalInstance, LifecycleHooks, currentInstance, setCurrentInstance } from './component' import { ComponentPublicInstance } from './componentProxy' import { callWithAsyncErrorHandling, ErrorTypeStrings } from './errorHandling' import { warn } from './warning' import { capitalize } from '@vue/shared' import { pauseTracking, resumeTracking } from '@vue/reactivity' function injectHook( type: LifecycleHooks, hook: Function, target: ComponentInternalInstance | null ) { if (target) { ;(target[type] || (target[type] = [])).push((...args: any[]) => { if (target.isUnmounted) { return } // disable tracking inside all lifecycle hooks // since they can potentially be called inside effects. pauseTracking() // Set currentInstance during hook invocation. // This assumes the hook does not synchronously trigger other hooks, which // can only be false when the user does something really funky. setCurrentInstance(target) const res = callWithAsyncErrorHandling(hook, target, type, args) setCurrentInstance(null) resumeTracking() return res }) } else if (__DEV__) { const apiName = `on${capitalize( ErrorTypeStrings[type].replace(/ hook$/, '') )}` warn( `${apiName} is called when there is no active component instance to be ` + `associated with. ` + `Lifecycle injection APIs can only be used during execution of setup().` + (__FEATURE_SUSPENSE__ ? ` If you are using async setup(), make sure to register lifecycle ` + `hooks before the first await statement.` : ``) ) } } export function onBeforeMount( hook: Function, target: ComponentInternalInstance | null = currentInstance ) { injectHook(LifecycleHooks.BEFORE_MOUNT, hook, target) } export function onMounted( hook: Function, target: ComponentInternalInstance | null = currentInstance ) { injectHook(LifecycleHooks.MOUNTED, hook, target) } export function onBeforeUpdate( hook: Function, target: ComponentInternalInstance | null = currentInstance ) { injectHook(LifecycleHooks.BEFORE_UPDATE, hook, target) } export function onUpdated( hook: Function, target: ComponentInternalInstance | null = currentInstance ) { injectHook(LifecycleHooks.UPDATED, hook, target) } export function onBeforeUnmount( hook: Function, target: ComponentInternalInstance | null = currentInstance ) { injectHook(LifecycleHooks.BEFORE_UNMOUNT, hook, target) } export function onUnmounted( hook: Function, target: ComponentInternalInstance | null = currentInstance ) { injectHook(LifecycleHooks.UNMOUNTED, hook, target) } export function onRenderTriggered( hook: Function, target: ComponentInternalInstance | null = currentInstance ) { injectHook(LifecycleHooks.RENDER_TRIGGERED, hook, target) } export function onRenderTracked( hook: Function, target: ComponentInternalInstance | null = currentInstance ) { injectHook(LifecycleHooks.RENDER_TRACKED, hook, target) } export function onErrorCaptured( hook: ( err: Error, instance: ComponentPublicInstance | null, info: string ) => boolean | void, target: ComponentInternalInstance | null = currentInstance ) { injectHook(LifecycleHooks.ERROR_CAPTURED, hook, target) }
packages/runtime-core/src/apiLifecycle.ts
0
https://github.com/vuejs/core/commit/f3760f7d34b8aeeebd96bf224d805b22baf6c11f
[ 0.004326573573052883, 0.0010305539472028613, 0.00017216347623616457, 0.0006627020193263888, 0.001114563550800085 ]
{ "id": 0, "code_window": [ " expect(isReactive(value)).toBe(true)\n", " }\n", " })\n", " }\n", " })\n", " })\n", "\n", " const sets = [Set, WeakSet]\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " test('should return undefined from Map.clear() call', () => {\n", " const wrapped = readonly(new Collection())\n", " expect(wrapped.clear()).toBeUndefined()\n", " expect(\n", " `Clear operation failed: target is readonly.`\n", " ).toHaveBeenWarned()\n", " })\n" ], "file_path": "packages/reactivity/__tests__/readonly.spec.ts", "type": "add", "edit_start_line_idx": 277 }
import { isReactive, isReadonly, readonly, shallowReadonly } from '../src' describe('reactivity/shallowReadonly', () => { test('should not make non-reactive properties reactive', () => { const props = shallowReadonly({ n: { foo: 1 } }) expect(isReactive(props.n)).toBe(false) }) test('should make root level properties readonly', () => { const props = shallowReadonly({ n: 1 }) // @ts-expect-error props.n = 2 expect(props.n).toBe(1) expect( `Set operation on key "n" failed: target is readonly.` ).toHaveBeenWarned() }) // to retain 2.x behavior. test('should NOT make nested properties readonly', () => { const props = shallowReadonly({ n: { foo: 1 } }) props.n.foo = 2 expect(props.n.foo).toBe(2) expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() }) // #2843 test('should differentiate from normal readonly calls', () => { const original = { foo: {} } const shallowProxy = shallowReadonly(original) const reactiveProxy = readonly(original) expect(shallowProxy).not.toBe(reactiveProxy) expect(isReadonly(shallowProxy.foo)).toBe(false) expect(isReadonly(reactiveProxy.foo)).toBe(true) }) describe('collection/Map', () => { ;[Map, WeakMap].forEach(Collection => { test('should make the map/weak-map readonly', () => { const key = {} const val = { foo: 1 } const original = new Collection([[key, val]]) const sroMap = shallowReadonly(original) expect(isReadonly(sroMap)).toBe(true) expect(isReactive(sroMap)).toBe(false) expect(sroMap.get(key)).toBe(val) sroMap.set(key, {} as any) expect( `Set operation on key "[object Object]" failed: target is readonly.` ).toHaveBeenWarned() }) test('should not make nested values readonly', () => { const key = {} const val = { foo: 1 } const original = new Collection([[key, val]]) const sroMap = shallowReadonly(original) expect(isReadonly(sroMap.get(key))).toBe(false) expect(isReactive(sroMap.get(key))).toBe(false) sroMap.get(key)!.foo = 2 expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() }) }) test('should not make the value generated by the iterable method readonly', () => { const key = {} const val = { foo: 1 } const original = new Map([[key, val]]) const sroMap = shallowReadonly(original) const values1 = [...sroMap.values()] const values2 = [...sroMap.entries()] expect(isReadonly(values1[0])).toBe(false) expect(isReactive(values1[0])).toBe(false) expect(values1[0]).toBe(val) values1[0].foo = 2 expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() expect(isReadonly(values2[0][1])).toBe(false) expect(isReactive(values2[0][1])).toBe(false) expect(values2[0][1]).toBe(val) values2[0][1].foo = 2 expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() }) test('should not make the value generated by the forEach method readonly', () => { const val = { foo: 1 } const original = new Map([['key', val]]) const sroMap = shallowReadonly(original) sroMap.forEach(val => { expect(isReadonly(val)).toBe(false) expect(isReactive(val)).toBe(false) expect(val).toBe(val) val.foo = 2 expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() }) }) }) describe('collection/Set', () => { test('should make the set/weak-set readonly', () => { ;[Set, WeakSet].forEach(Collection => { const obj = { foo: 1 } const original = new Collection([obj]) const sroSet = shallowReadonly(original) expect(isReadonly(sroSet)).toBe(true) expect(isReactive(sroSet)).toBe(false) expect(sroSet.has(obj)).toBe(true) sroSet.add({} as any) expect( `Add operation on key "[object Object]" failed: target is readonly.` ).toHaveBeenWarned() }) }) test('should not make nested values readonly', () => { const obj = { foo: 1 } const original = new Set([obj]) const sroSet = shallowReadonly(original) const values = [...sroSet.values()] expect(values[0]).toBe(obj) expect(isReadonly(values[0])).toBe(false) expect(isReactive(values[0])).toBe(false) sroSet.add({} as any) expect( `Add operation on key "[object Object]" failed: target is readonly.` ).toHaveBeenWarned() values[0].foo = 2 expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() }) test('should not make the value generated by the iterable method readonly', () => { const val = { foo: 1 } const original = new Set([val]) const sroSet = shallowReadonly(original) const values1 = [...sroSet.values()] const values2 = [...sroSet.entries()] expect(isReadonly(values1[0])).toBe(false) expect(isReactive(values1[0])).toBe(false) expect(values1[0]).toBe(val) values1[0].foo = 2 expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() expect(isReadonly(values2[0][1])).toBe(false) expect(isReactive(values2[0][1])).toBe(false) expect(values2[0][1]).toBe(val) values2[0][1].foo = 2 expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() }) test('should not make the value generated by the forEach method readonly', () => { const val = { foo: 1 } const original = new Set([val]) const sroSet = shallowReadonly(original) sroSet.forEach(val => { expect(isReadonly(val)).toBe(false) expect(isReactive(val)).toBe(false) expect(val).toBe(val) val.foo = 2 expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() }) }) }) })
packages/reactivity/__tests__/shallowReadonly.spec.ts
1
https://github.com/vuejs/core/commit/657476dcdb964be4fbb1277c215c073f3275728e
[ 0.003326819045469165, 0.0004272240912541747, 0.00016551050066482276, 0.00019905422232113779, 0.000688191968947649 ]
{ "id": 0, "code_window": [ " expect(isReactive(value)).toBe(true)\n", " }\n", " })\n", " }\n", " })\n", " })\n", "\n", " const sets = [Set, WeakSet]\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " test('should return undefined from Map.clear() call', () => {\n", " const wrapped = readonly(new Collection())\n", " expect(wrapped.clear()).toBeUndefined()\n", " expect(\n", " `Clear operation failed: target is readonly.`\n", " ).toHaveBeenWarned()\n", " })\n" ], "file_path": "packages/reactivity/__tests__/readonly.spec.ts", "type": "add", "edit_start_line_idx": 277 }
import { createBlock, createVNode, openBlock, Comment, Fragment, Text, cloneVNode, mergeProps, normalizeVNode, transformVNodeArgs, isBlockTreeEnabled } from '../src/vnode' import { Data } from '../src/component' import { ShapeFlags, PatchFlags } from '@vue/shared' import { h, reactive, isReactive, setBlockTracking, ref, withCtx } from '../src' import { createApp, nodeOps, serializeInner } from '@vue/runtime-test' import { setCurrentRenderingInstance } from '../src/componentRenderContext' describe('vnode', () => { test('create with just tag', () => { const vnode = createVNode('p') expect(vnode.type).toBe('p') expect(vnode.props).toBe(null) }) test('create with tag and props', () => { const vnode = createVNode('p', {}) expect(vnode.type).toBe('p') expect(vnode.props).toMatchObject({}) }) test('create with tag, props and children', () => { const vnode = createVNode('p', {}, ['foo']) expect(vnode.type).toBe('p') expect(vnode.props).toMatchObject({}) expect(vnode.children).toMatchObject(['foo']) }) test('create with 0 as props', () => { const vnode = createVNode('p', null) expect(vnode.type).toBe('p') expect(vnode.props).toBe(null) }) test('show warn when create with invalid type', () => { const vnode = createVNode('') expect('Invalid vnode type when creating vnode').toHaveBeenWarned() expect(vnode.type).toBe(Comment) }) test('create from an existing vnode', () => { const vnode1 = createVNode('p', { id: 'foo' }) const vnode2 = createVNode(vnode1, { class: 'bar' }, 'baz') expect(vnode2).toMatchObject({ type: 'p', props: { id: 'foo', class: 'bar' }, children: 'baz', shapeFlag: ShapeFlags.ELEMENT | ShapeFlags.TEXT_CHILDREN }) }) test('vnode keys', () => { for (const key of ['', 'a', 0, 1, NaN]) { expect(createVNode('div', { key }).key).toBe(key) } expect(createVNode('div').key).toBe(null) expect(createVNode('div', { key: undefined }).key).toBe(null) expect(`VNode created with invalid key (NaN)`).toHaveBeenWarned() }) test('create with class component', () => { class Component { $props: any static __vccOpts = { template: '<div />' } } const vnode = createVNode(Component) expect(vnode.type).toEqual(Component.__vccOpts) }) describe('class normalization', () => { test('string', () => { const vnode = createVNode('p', { class: 'foo baz' }) expect(vnode.props).toMatchObject({ class: 'foo baz' }) }) test('array<string>', () => { const vnode = createVNode('p', { class: ['foo', 'baz'] }) expect(vnode.props).toMatchObject({ class: 'foo baz' }) }) test('array<object>', () => { const vnode = createVNode('p', { class: [{ foo: 'foo' }, { baz: 'baz' }] }) expect(vnode.props).toMatchObject({ class: 'foo baz' }) }) test('object', () => { const vnode = createVNode('p', { class: { foo: 'foo', baz: 'baz' } }) expect(vnode.props).toMatchObject({ class: 'foo baz' }) }) }) describe('style normalization', () => { test('array', () => { const vnode = createVNode('p', { style: [{ foo: 'foo' }, { baz: 'baz' }] }) expect(vnode.props).toMatchObject({ style: { foo: 'foo', baz: 'baz' } }) }) test('object', () => { const vnode = createVNode('p', { style: { foo: 'foo', baz: 'baz' } }) expect(vnode.props).toMatchObject({ style: { foo: 'foo', baz: 'baz' } }) }) }) describe('children normalization', () => { const nop = vi.fn test('null', () => { const vnode = createVNode('p', null, null) expect(vnode.children).toBe(null) expect(vnode.shapeFlag).toBe(ShapeFlags.ELEMENT) }) test('array', () => { const vnode = createVNode('p', null, ['foo']) expect(vnode.children).toMatchObject(['foo']) expect(vnode.shapeFlag).toBe( ShapeFlags.ELEMENT | ShapeFlags.ARRAY_CHILDREN ) }) test('object', () => { const vnode = createVNode({}, null, { foo: 'foo' }) expect(vnode.children).toMatchObject({ foo: 'foo' }) expect(vnode.shapeFlag).toBe( ShapeFlags.STATEFUL_COMPONENT | ShapeFlags.SLOTS_CHILDREN ) }) test('function', () => { const vnode = createVNode('p', null, nop) expect(vnode.children).toMatchObject({ default: nop }) expect(vnode.shapeFlag).toBe( ShapeFlags.ELEMENT | ShapeFlags.SLOTS_CHILDREN ) }) test('string', () => { const vnode = createVNode('p', null, 'foo') expect(vnode.children).toBe('foo') expect(vnode.shapeFlag).toBe( ShapeFlags.ELEMENT | ShapeFlags.TEXT_CHILDREN ) }) test('element with slots', () => { const children = [createVNode('span', null, 'hello')] const vnode = createVNode('div', null, { default: () => children }) expect(vnode.children).toBe(children) expect(vnode.shapeFlag).toBe( ShapeFlags.ELEMENT | ShapeFlags.ARRAY_CHILDREN ) }) }) test('normalizeVNode', () => { // null / undefined -> Comment expect(normalizeVNode(null)).toMatchObject({ type: Comment }) expect(normalizeVNode(undefined)).toMatchObject({ type: Comment }) // boolean -> Comment // this is for usage like `someBoolean && h('div')` and behavior consistency // with 2.x (#574) expect(normalizeVNode(true)).toMatchObject({ type: Comment }) expect(normalizeVNode(false)).toMatchObject({ type: Comment }) // array -> Fragment expect(normalizeVNode(['foo'])).toMatchObject({ type: Fragment }) // VNode -> VNode const vnode = createVNode('div') expect(normalizeVNode(vnode)).toBe(vnode) // mounted VNode -> cloned VNode const mounted = createVNode('div') mounted.el = {} const normalized = normalizeVNode(mounted) expect(normalized).not.toBe(mounted) expect(normalized).toEqual(mounted) // primitive types expect(normalizeVNode('foo')).toMatchObject({ type: Text, children: `foo` }) expect(normalizeVNode(1)).toMatchObject({ type: Text, children: `1` }) }) test('type shapeFlag inference', () => { expect(createVNode('div').shapeFlag).toBe(ShapeFlags.ELEMENT) expect(createVNode({}).shapeFlag).toBe(ShapeFlags.STATEFUL_COMPONENT) expect(createVNode(() => {}).shapeFlag).toBe( ShapeFlags.FUNCTIONAL_COMPONENT ) expect(createVNode(Text).shapeFlag).toBe(0) }) test('cloneVNode', () => { const node1 = createVNode('div', { foo: 1 }, null) expect(cloneVNode(node1)).toEqual(node1) const node2 = createVNode({}, null, [node1]) const cloned2 = cloneVNode(node2) expect(cloned2).toEqual(node2) expect(cloneVNode(node2)).toEqual(cloned2) }) test('cloneVNode key normalization', () => { // #1041 should use resolved key/ref expect(cloneVNode(createVNode('div', { key: 1 })).key).toBe(1) expect(cloneVNode(createVNode('div', { key: 1 }), { key: 2 }).key).toBe(2) expect(cloneVNode(createVNode('div'), { key: 2 }).key).toBe(2) }) // ref normalizes to [currentRenderingInstance, ref] test('cloneVNode ref normalization', () => { const mockInstance1 = { type: {} } as any const mockInstance2 = { type: {} } as any setCurrentRenderingInstance(mockInstance1) const original = createVNode('div', { ref: 'foo' }) expect(original.ref).toMatchObject({ i: mockInstance1, r: 'foo', f: false }) // clone and preserve original ref const cloned1 = cloneVNode(original) expect(cloned1.ref).toMatchObject({ i: mockInstance1, r: 'foo', f: false }) // cloning with new ref, but with same context instance const cloned2 = cloneVNode(original, { ref: 'bar' }) expect(cloned2.ref).toMatchObject({ i: mockInstance1, r: 'bar', f: false }) // cloning and adding ref to original that has no ref const original2 = createVNode('div') const cloned3 = cloneVNode(original2, { ref: 'bar' }) expect(cloned3.ref).toMatchObject({ i: mockInstance1, r: 'bar', f: false }) // cloning with different context instance setCurrentRenderingInstance(mockInstance2) // clone and preserve original ref const cloned4 = cloneVNode(original) // #1311 should preserve original context instance! expect(cloned4.ref).toMatchObject({ i: mockInstance1, r: 'foo', f: false }) // cloning with new ref, but with same context instance const cloned5 = cloneVNode(original, { ref: 'bar' }) // new ref should use current context instance and overwrite original expect(cloned5.ref).toMatchObject({ i: mockInstance2, r: 'bar', f: false }) // cloning and adding ref to original that has no ref const cloned6 = cloneVNode(original2, { ref: 'bar' }) expect(cloned6.ref).toMatchObject({ i: mockInstance2, r: 'bar', f: false }) const original3 = createVNode('div', { ref: 'foo', ref_for: true }) expect(original3.ref).toMatchObject({ i: mockInstance2, r: 'foo', f: true }) const cloned7 = cloneVNode(original3, { ref: 'bar', ref_for: true }) expect(cloned7.ref).toMatchObject({ i: mockInstance2, r: 'bar', f: true }) const r = ref() const original4 = createVNode('div', { ref: r, ref_key: 'foo' }) expect(original4.ref).toMatchObject({ i: mockInstance2, r, k: 'foo' }) const cloned8 = cloneVNode(original4) expect(cloned8.ref).toMatchObject({ i: mockInstance2, r, k: 'foo' }) setCurrentRenderingInstance(null) }) test('cloneVNode ref merging', () => { const mockInstance1 = { type: {} } as any const mockInstance2 = { type: {} } as any setCurrentRenderingInstance(mockInstance1) const original = createVNode('div', { ref: 'foo' }) expect(original.ref).toMatchObject({ i: mockInstance1, r: 'foo', f: false }) // clone and preserve original ref setCurrentRenderingInstance(mockInstance2) const cloned1 = cloneVNode(original, { ref: 'bar' }, true) expect(cloned1.ref).toMatchObject([ { i: mockInstance1, r: 'foo', f: false }, { i: mockInstance2, r: 'bar', f: false } ]) setCurrentRenderingInstance(null) }) test('cloneVNode class normalization', () => { const vnode = createVNode('div') const expectedProps = { class: 'a b' } expect(cloneVNode(vnode, { class: 'a b' }).props).toMatchObject( expectedProps ) expect(cloneVNode(vnode, { class: ['a', 'b'] }).props).toMatchObject( expectedProps ) expect( cloneVNode(vnode, { class: { a: true, b: true } }).props ).toMatchObject(expectedProps) expect( cloneVNode(vnode, { class: [{ a: true, b: true }] }).props ).toMatchObject(expectedProps) }) test('cloneVNode style normalization', () => { const vnode = createVNode('div') const expectedProps = { style: { color: 'blue', width: '300px' } } expect( cloneVNode(vnode, { style: 'color: blue; width: 300px;' }).props ).toMatchObject(expectedProps) expect( cloneVNode(vnode, { style: { color: 'blue', width: '300px' } }).props ).toMatchObject(expectedProps) expect( cloneVNode(vnode, { style: [ { color: 'blue', width: '300px' } ] }).props ).toMatchObject(expectedProps) }) describe('mergeProps', () => { test('class', () => { let props1: Data = { class: { c: true } } let props2: Data = { class: ['cc'] } let props3: Data = { class: [{ ccc: true }] } let props4: Data = { class: { cccc: true } } expect(mergeProps(props1, props2, props3, props4)).toMatchObject({ class: 'c cc ccc cccc' }) }) test('style', () => { let props1: Data = { style: [ { color: 'red', fontSize: 10 } ] } let props2: Data = { style: [ { color: 'blue', width: '200px' }, { width: '300px', height: '300px', fontSize: 30 } ] } expect(mergeProps(props1, props2)).toMatchObject({ style: { color: 'blue', width: '300px', height: '300px', fontSize: 30 } }) }) test('style w/ strings', () => { let props1: Data = { style: 'width:100px;right:10;top:10' } let props2: Data = { style: [ { color: 'blue', width: '200px' }, { width: '300px', height: '300px', fontSize: 30 } ] } expect(mergeProps(props1, props2)).toMatchObject({ style: { color: 'blue', width: '300px', height: '300px', fontSize: 30, right: '10', top: '10' } }) }) test('handlers', () => { let clickHandler1 = function () {} let clickHandler2 = function () {} let focusHandler2 = function () {} let props1: Data = { onClick: clickHandler1 } let props2: Data = { onClick: clickHandler2, onFocus: focusHandler2 } expect(mergeProps(props1, props2)).toMatchObject({ onClick: [clickHandler1, clickHandler2], onFocus: focusHandler2 }) let props3: Data = { onClick: undefined } expect(mergeProps(props1, props3)).toMatchObject({ onClick: clickHandler1 }) }) test('default', () => { let props1: Data = { foo: 'c' } let props2: Data = { foo: {}, bar: ['cc'] } let props3: Data = { baz: { ccc: true } } expect(mergeProps(props1, props2, props3)).toMatchObject({ foo: {}, bar: ['cc'], baz: { ccc: true } }) }) }) describe('dynamic children', () => { test('with patchFlags', () => { const hoist = createVNode('div') let vnode1 const vnode = (openBlock(), createBlock('div', null, [ hoist, (vnode1 = createVNode('div', null, 'text', PatchFlags.TEXT)) ])) expect(vnode.dynamicChildren).toStrictEqual([vnode1]) }) test('should not track vnodes with only HYDRATE_EVENTS flag', () => { const hoist = createVNode('div') const vnode = (openBlock(), createBlock('div', null, [ hoist, createVNode('div', null, 'text', PatchFlags.HYDRATE_EVENTS) ])) expect(vnode.dynamicChildren).toStrictEqual([]) }) test('many times call openBlock', () => { const hoist = createVNode('div') let vnode1, vnode2, vnode3 const vnode = (openBlock(), createBlock('div', null, [ hoist, (vnode1 = createVNode('div', null, 'text', PatchFlags.TEXT)), (vnode2 = (openBlock(), createBlock('div', null, [ hoist, (vnode3 = createVNode('div', null, 'text', PatchFlags.TEXT)) ]))) ])) expect(vnode.dynamicChildren).toStrictEqual([vnode1, vnode2]) expect(vnode2.dynamicChildren).toStrictEqual([vnode3]) }) test('with stateful component', () => { const hoist = createVNode('div') let vnode1 const vnode = (openBlock(), createBlock('div', null, [ hoist, (vnode1 = createVNode({}, null, 'text')) ])) expect(vnode.dynamicChildren).toStrictEqual([vnode1]) }) test('with functional component', () => { const hoist = createVNode('div') let vnode1 const vnode = (openBlock(), createBlock('div', null, [ hoist, (vnode1 = createVNode(() => {}, null, 'text')) ])) expect(vnode.dynamicChildren).toStrictEqual([vnode1]) }) test('with suspense', () => { const hoist = createVNode('div') let vnode1 const vnode = (openBlock(), createBlock('div', null, [ hoist, (vnode1 = createVNode(() => {}, null, 'text')) ])) expect(vnode.dynamicChildren).toStrictEqual([vnode1]) }) // #1039 // <component :is="foo">{{ bar }}</component> // - content is compiled as slot // - dynamic component resolves to plain element, but as a block // - block creation disables its own tracking, accidentally causing the // slot content (called during the block node creation) to be missed test('element block should track normalized slot children', () => { const hoist = createVNode('div') let vnode1: any const vnode = (openBlock(), createBlock('div', null, { default: () => { return [ hoist, (vnode1 = createVNode('div', null, 'text', PatchFlags.TEXT)) ] } })) expect(vnode.dynamicChildren).toStrictEqual([vnode1]) }) test('openBlock w/ disableTracking: true', () => { const hoist = createVNode('div') let vnode1 const vnode = (openBlock(), createBlock('div', null, [ // a v-for fragment block generated by the compiler // disables tracking because it always diffs its // children. (vnode1 = (openBlock(true), createBlock(Fragment, null, [ hoist, /*vnode2*/ createVNode(() => {}, null, 'text') ]))) ])) expect(vnode.dynamicChildren).toStrictEqual([vnode1]) expect(vnode1.dynamicChildren).toStrictEqual([]) }) test('openBlock without disableTracking: true', () => { const hoist = createVNode('div') let vnode1, vnode2 const vnode = (openBlock(), createBlock('div', null, [ (vnode1 = (openBlock(), createBlock(Fragment, null, [ hoist, (vnode2 = createVNode(() => {}, null, 'text')) ]))) ])) expect(vnode.dynamicChildren).toStrictEqual([vnode1]) expect(vnode1.dynamicChildren).toStrictEqual([vnode2]) }) test('should not track openBlock() when tracking is disabled', () => { let vnode1 const vnode = (openBlock(), createBlock('div', null, [ setBlockTracking(-1), (vnode1 = (openBlock(), createBlock('div'))), setBlockTracking(1), vnode1 ])) expect(vnode.dynamicChildren).toStrictEqual([]) }) // #5657 test('error of slot function execution should not affect block tracking', () => { expect(isBlockTreeEnabled).toStrictEqual(1) const slotFn = withCtx( () => { throw new Error('slot execution error') }, { type: {}, appContext: {} } as any ) const Parent = { setup(_: any, { slots }: any) { return () => { try { slots.default() } catch (e) {} } } } const vnode = (openBlock(), createBlock(Parent, null, { default: slotFn })) createApp(vnode).mount(nodeOps.createElement('div')) expect(isBlockTreeEnabled).toStrictEqual(1) }) }) describe('transformVNodeArgs', () => { afterEach(() => { // reset transformVNodeArgs() }) test('no-op pass through', () => { transformVNodeArgs(args => args) const vnode = createVNode('div', { id: 'foo' }, 'hello') expect(vnode).toMatchObject({ type: 'div', props: { id: 'foo' }, children: 'hello', shapeFlag: ShapeFlags.ELEMENT | ShapeFlags.TEXT_CHILDREN }) }) test('direct override', () => { transformVNodeArgs(() => ['div', { id: 'foo' }, 'hello']) const vnode = createVNode('p') expect(vnode).toMatchObject({ type: 'div', props: { id: 'foo' }, children: 'hello', shapeFlag: ShapeFlags.ELEMENT | ShapeFlags.TEXT_CHILDREN }) }) test('receive component instance as 2nd arg', () => { transformVNodeArgs((args, instance) => { if (instance) { return ['h1', null, instance.type.name] } else { return args } }) const App = { // this will be the name of the component in the h1 name: 'Root Component', render() { return h('p') // this will be overwritten by the transform } } const root = nodeOps.createElement('div') createApp(App).mount(root) expect(serializeInner(root)).toBe('<h1>Root Component</h1>') }) test('should not be observable', () => { const a = createVNode('div') const b = reactive(a) expect(b).toBe(a) expect(isReactive(b)).toBe(false) }) }) })
packages/runtime-core/__tests__/vnode.spec.ts
0
https://github.com/vuejs/core/commit/657476dcdb964be4fbb1277c215c073f3275728e
[ 0.000267653726041317, 0.00017384339298587292, 0.00016633668565191329, 0.00017225986812263727, 0.000011681572686939035 ]
{ "id": 0, "code_window": [ " expect(isReactive(value)).toBe(true)\n", " }\n", " })\n", " }\n", " })\n", " })\n", "\n", " const sets = [Set, WeakSet]\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " test('should return undefined from Map.clear() call', () => {\n", " const wrapped = readonly(new Collection())\n", " expect(wrapped.clear()).toBeUndefined()\n", " expect(\n", " `Clear operation failed: target is readonly.`\n", " ).toHaveBeenWarned()\n", " })\n" ], "file_path": "packages/reactivity/__tests__/readonly.spec.ts", "type": "add", "edit_start_line_idx": 277 }
import { E2E_TIMEOUT, setupPuppeteer } from './e2eUtils' import path from 'path' import { createApp, ref } from 'vue' describe('e2e: TransitionGroup', () => { const { page, html, nextFrame, timeout } = setupPuppeteer() const baseUrl = `file://${path.resolve(__dirname, './transition.html')}` const duration = process.env.CI ? 200 : 50 const buffer = process.env.CI ? 20 : 5 const htmlWhenTransitionStart = () => page().evaluate(() => { ;(document.querySelector('#toggleBtn') as any)!.click() return Promise.resolve().then(() => { return document.querySelector('#container')!.innerHTML }) }) const transitionFinish = (time = duration) => timeout(time + buffer) beforeEach(async () => { await page().goto(baseUrl) await page().waitForSelector('#app') }) test( 'enter', async () => { await page().evaluate(() => { const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition-group name="test"> <div v-for="item in items" :key="item" class="test">{{item}}</div> </transition-group> </div> <button id="toggleBtn" @click="click">button</button> `, setup: () => { const items = ref(['a', 'b', 'c']) const click = () => items.value.push('d', 'e') return { click, items } } }).mount('#app') }) expect(await html('#container')).toBe( `<div class="test">a</div>` + `<div class="test">b</div>` + `<div class="test">c</div>` ) expect(await htmlWhenTransitionStart()).toBe( `<div class="test">a</div>` + `<div class="test">b</div>` + `<div class="test">c</div>` + `<div class="test test-enter-from test-enter-active">d</div>` + `<div class="test test-enter-from test-enter-active">e</div>` ) await nextFrame() expect(await html('#container')).toBe( `<div class="test">a</div>` + `<div class="test">b</div>` + `<div class="test">c</div>` + `<div class="test test-enter-active test-enter-to">d</div>` + `<div class="test test-enter-active test-enter-to">e</div>` ) await transitionFinish() expect(await html('#container')).toBe( `<div class="test">a</div>` + `<div class="test">b</div>` + `<div class="test">c</div>` + `<div class="test">d</div>` + `<div class="test">e</div>` ) }, E2E_TIMEOUT ) test( 'leave', async () => { await page().evaluate(() => { const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition-group name="test"> <div v-for="item in items" :key="item" class="test">{{item}}</div> </transition-group> </div> <button id="toggleBtn" @click="click">button</button> `, setup: () => { const items = ref(['a', 'b', 'c']) const click = () => (items.value = ['b']) return { click, items } } }).mount('#app') }) expect(await html('#container')).toBe( `<div class="test">a</div>` + `<div class="test">b</div>` + `<div class="test">c</div>` ) expect(await htmlWhenTransitionStart()).toBe( `<div class="test test-leave-from test-leave-active">a</div>` + `<div class="test">b</div>` + `<div class="test test-leave-from test-leave-active">c</div>` ) await nextFrame() expect(await html('#container')).toBe( `<div class="test test-leave-active test-leave-to">a</div>` + `<div class="test">b</div>` + `<div class="test test-leave-active test-leave-to">c</div>` ) await transitionFinish() expect(await html('#container')).toBe(`<div class="test">b</div>`) }, E2E_TIMEOUT ) test( 'enter + leave', async () => { await page().evaluate(() => { const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition-group name="test"> <div v-for="item in items" :key="item" class="test">{{item}}</div> </transition-group> </div> <button id="toggleBtn" @click="click">button</button> `, setup: () => { const items = ref(['a', 'b', 'c']) const click = () => (items.value = ['b', 'c', 'd']) return { click, items } } }).mount('#app') }) expect(await html('#container')).toBe( `<div class="test">a</div>` + `<div class="test">b</div>` + `<div class="test">c</div>` ) expect(await htmlWhenTransitionStart()).toBe( `<div class="test test-leave-from test-leave-active">a</div>` + `<div class="test">b</div>` + `<div class="test">c</div>` + `<div class="test test-enter-from test-enter-active">d</div>` ) await nextFrame() expect(await html('#container')).toBe( `<div class="test test-leave-active test-leave-to">a</div>` + `<div class="test">b</div>` + `<div class="test">c</div>` + `<div class="test test-enter-active test-enter-to">d</div>` ) await transitionFinish() expect(await html('#container')).toBe( `<div class="test">b</div>` + `<div class="test">c</div>` + `<div class="test">d</div>` ) }, E2E_TIMEOUT ) test( 'appear', async () => { const appearHtml = await page().evaluate(() => { const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition-group appear appear-from-class="test-appear-from" appear-to-class="test-appear-to" appear-active-class="test-appear-active" name="test"> <div v-for="item in items" :key="item" class="test">{{item}}</div> </transition-group> </div> <button id="toggleBtn" @click="click">button</button> `, setup: () => { const items = ref(['a', 'b', 'c']) const click = () => items.value.push('d', 'e') return { click, items } } }).mount('#app') return Promise.resolve().then(() => { return document.querySelector('#container')!.innerHTML }) }) // appear expect(appearHtml).toBe( `<div class="test test-appear-from test-appear-active">a</div>` + `<div class="test test-appear-from test-appear-active">b</div>` + `<div class="test test-appear-from test-appear-active">c</div>` ) await nextFrame() expect(await html('#container')).toBe( `<div class="test test-appear-active test-appear-to">a</div>` + `<div class="test test-appear-active test-appear-to">b</div>` + `<div class="test test-appear-active test-appear-to">c</div>` ) await transitionFinish() expect(await html('#container')).toBe( `<div class="test">a</div>` + `<div class="test">b</div>` + `<div class="test">c</div>` ) // enter expect(await htmlWhenTransitionStart()).toBe( `<div class="test">a</div>` + `<div class="test">b</div>` + `<div class="test">c</div>` + `<div class="test test-enter-from test-enter-active">d</div>` + `<div class="test test-enter-from test-enter-active">e</div>` ) await nextFrame() expect(await html('#container')).toBe( `<div class="test">a</div>` + `<div class="test">b</div>` + `<div class="test">c</div>` + `<div class="test test-enter-active test-enter-to">d</div>` + `<div class="test test-enter-active test-enter-to">e</div>` ) await transitionFinish() expect(await html('#container')).toBe( `<div class="test">a</div>` + `<div class="test">b</div>` + `<div class="test">c</div>` + `<div class="test">d</div>` + `<div class="test">e</div>` ) }, E2E_TIMEOUT ) test( 'move', async () => { await page().evaluate(() => { const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition-group name="group"> <div v-for="item in items" :key="item" class="test">{{item}}</div> </transition-group> </div> <button id="toggleBtn" @click="click">button</button> `, setup: () => { const items = ref(['a', 'b', 'c']) const click = () => (items.value = ['d', 'b', 'a']) return { click, items } } }).mount('#app') }) expect(await html('#container')).toBe( `<div class="test">a</div>` + `<div class="test">b</div>` + `<div class="test">c</div>` ) expect(await htmlWhenTransitionStart()).toBe( `<div class="test group-enter-from group-enter-active">d</div>` + `<div class="test">b</div>` + `<div class="test group-move" style="">a</div>` + `<div class="test group-leave-from group-leave-active group-move" style="">c</div>` ) await nextFrame() expect(await html('#container')).toBe( `<div class="test group-enter-active group-enter-to">d</div>` + `<div class="test">b</div>` + `<div class="test group-move" style="">a</div>` + `<div class="test group-leave-active group-move group-leave-to" style="">c</div>` ) await transitionFinish(duration * 2) expect(await html('#container')).toBe( `<div class="test">d</div>` + `<div class="test">b</div>` + `<div class="test" style="">a</div>` ) }, E2E_TIMEOUT ) test( 'dynamic name', async () => { await page().evaluate(() => { const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition-group :name="name"> <div v-for="item in items" :key="item" >{{item}}</div> </transition-group> </div> <button id="toggleBtn" @click="click">button</button> <button id="changeNameBtn" @click="changeName">button</button> `, setup: () => { const items = ref(['a', 'b', 'c']) const name = ref('invalid') const click = () => (items.value = ['b', 'c', 'a']) const changeName = () => { name.value = 'group' items.value = ['a', 'b', 'c'] } return { click, items, name, changeName } } }).mount('#app') }) expect(await html('#container')).toBe( `<div>a</div>` + `<div>b</div>` + `<div>c</div>` ) // invalid name expect(await htmlWhenTransitionStart()).toBe( `<div>b</div>` + `<div>c</div>` + `<div>a</div>` ) // change name const moveHtml = await page().evaluate(() => { ;(document.querySelector('#changeNameBtn') as any).click() return Promise.resolve().then(() => { return document.querySelector('#container')!.innerHTML }) }) expect(moveHtml).toBe( `<div class="group-move" style="">a</div>` + `<div class="group-move" style="">b</div>` + `<div class="group-move" style="">c</div>` ) // not sure why but we just have to wait really long for this to // pass consistently :/ await transitionFinish(duration * 4 + buffer) expect(await html('#container')).toBe( `<div class="" style="">a</div>` + `<div class="" style="">b</div>` + `<div class="" style="">c</div>` ) }, E2E_TIMEOUT ) test( 'events', async () => { const onLeaveSpy = vi.fn() const onEnterSpy = vi.fn() const onAppearSpy = vi.fn() const beforeLeaveSpy = vi.fn() const beforeEnterSpy = vi.fn() const beforeAppearSpy = vi.fn() const afterLeaveSpy = vi.fn() const afterEnterSpy = vi.fn() const afterAppearSpy = vi.fn() await page().exposeFunction('onLeaveSpy', onLeaveSpy) await page().exposeFunction('onEnterSpy', onEnterSpy) await page().exposeFunction('onAppearSpy', onAppearSpy) await page().exposeFunction('beforeLeaveSpy', beforeLeaveSpy) await page().exposeFunction('beforeEnterSpy', beforeEnterSpy) await page().exposeFunction('beforeAppearSpy', beforeAppearSpy) await page().exposeFunction('afterLeaveSpy', afterLeaveSpy) await page().exposeFunction('afterEnterSpy', afterEnterSpy) await page().exposeFunction('afterAppearSpy', afterAppearSpy) const appearHtml = await page().evaluate(() => { const { beforeAppearSpy, onAppearSpy, afterAppearSpy, beforeEnterSpy, onEnterSpy, afterEnterSpy, beforeLeaveSpy, onLeaveSpy, afterLeaveSpy } = window as any const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition-group name="test" appear appear-from-class="test-appear-from" appear-to-class="test-appear-to" appear-active-class="test-appear-active" @before-enter="beforeEnterSpy()" @enter="onEnterSpy()" @after-enter="afterEnterSpy()" @before-leave="beforeLeaveSpy()" @leave="onLeaveSpy()" @after-leave="afterLeaveSpy()" @before-appear="beforeAppearSpy()" @appear="onAppearSpy()" @after-appear="afterAppearSpy()"> <div v-for="item in items" :key="item" class="test">{{item}}</div> </transition-group> </div> <button id="toggleBtn" @click="click">button</button> `, setup: () => { const items = ref(['a', 'b', 'c']) const click = () => (items.value = ['b', 'c', 'd']) return { click, items, beforeAppearSpy, onAppearSpy, afterAppearSpy, beforeEnterSpy, onEnterSpy, afterEnterSpy, beforeLeaveSpy, onLeaveSpy, afterLeaveSpy } } }).mount('#app') return Promise.resolve().then(() => { return document.querySelector('#container')!.innerHTML }) }) expect(beforeAppearSpy).toBeCalled() expect(onAppearSpy).toBeCalled() expect(afterAppearSpy).not.toBeCalled() expect(appearHtml).toBe( `<div class="test test-appear-from test-appear-active">a</div>` + `<div class="test test-appear-from test-appear-active">b</div>` + `<div class="test test-appear-from test-appear-active">c</div>` ) await nextFrame() expect(afterAppearSpy).not.toBeCalled() expect(await html('#container')).toBe( `<div class="test test-appear-active test-appear-to">a</div>` + `<div class="test test-appear-active test-appear-to">b</div>` + `<div class="test test-appear-active test-appear-to">c</div>` ) await transitionFinish() expect(afterAppearSpy).toBeCalled() expect(await html('#container')).toBe( `<div class="test">a</div>` + `<div class="test">b</div>` + `<div class="test">c</div>` ) // enter + leave expect(await htmlWhenTransitionStart()).toBe( `<div class="test test-leave-from test-leave-active">a</div>` + `<div class="test">b</div>` + `<div class="test">c</div>` + `<div class="test test-enter-from test-enter-active">d</div>` ) expect(beforeLeaveSpy).toBeCalled() expect(onLeaveSpy).toBeCalled() expect(afterLeaveSpy).not.toBeCalled() expect(beforeEnterSpy).toBeCalled() expect(onEnterSpy).toBeCalled() expect(afterEnterSpy).not.toBeCalled() await nextFrame() expect(await html('#container')).toBe( `<div class="test test-leave-active test-leave-to">a</div>` + `<div class="test">b</div>` + `<div class="test">c</div>` + `<div class="test test-enter-active test-enter-to">d</div>` ) expect(afterLeaveSpy).not.toBeCalled() expect(afterEnterSpy).not.toBeCalled() await transitionFinish() expect(await html('#container')).toBe( `<div class="test">b</div>` + `<div class="test">c</div>` + `<div class="test">d</div>` ) expect(afterLeaveSpy).toBeCalled() expect(afterEnterSpy).toBeCalled() }, E2E_TIMEOUT ) test('warn unkeyed children', () => { createApp({ template: ` <transition-group name="test"> <div v-for="item in items" class="test">{{item}}</div> </transition-group> `, setup: () => { const items = ref(['a', 'b', 'c']) return { items } } }).mount(document.createElement('div')) expect(`<TransitionGroup> children must be keyed`).toHaveBeenWarned() }) })
packages/vue/__tests__/e2e/TransitionGroup.spec.ts
0
https://github.com/vuejs/core/commit/657476dcdb964be4fbb1277c215c073f3275728e
[ 0.00017769818077795208, 0.00017052021576091647, 0.0001635738299228251, 0.00017108756583184004, 0.0000031098716135602444 ]
{ "id": 0, "code_window": [ " expect(isReactive(value)).toBe(true)\n", " }\n", " })\n", " }\n", " })\n", " })\n", "\n", " const sets = [Set, WeakSet]\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " test('should return undefined from Map.clear() call', () => {\n", " const wrapped = readonly(new Collection())\n", " expect(wrapped.clear()).toBeUndefined()\n", " expect(\n", " `Clear operation failed: target is readonly.`\n", " ).toHaveBeenWarned()\n", " })\n" ], "file_path": "packages/reactivity/__tests__/readonly.spec.ts", "type": "add", "edit_start_line_idx": 277 }
import { createApp, App, Plugin } from 'vue' const app = createApp({}) // Plugin without types accept anything const PluginWithoutType: Plugin = { install(app: App) {} } app.use(PluginWithoutType) app.use(PluginWithoutType, 2) app.use(PluginWithoutType, { anything: 'goes' }, true) type PluginOptions = { option1?: string option2: number option3: boolean } const PluginWithObjectOptions = { install(app: App, options: PluginOptions) { options.option1 options.option2 options.option3 } } for (const Plugin of [ PluginWithObjectOptions, PluginWithObjectOptions.install ]) { // @ts-expect-error: no params app.use(Plugin) // @ts-expect-error option2 and option3 (required) missing app.use(Plugin, {}) // @ts-expect-error type mismatch app.use(Plugin, undefined) // valid options app.use(Plugin, { option2: 1, option3: true }) app.use(Plugin, { option1: 'foo', option2: 1, option3: true }) } const PluginNoOptions = { install(app: App) {} } for (const Plugin of [PluginNoOptions, PluginNoOptions.install]) { // no args app.use(Plugin) // @ts-expect-error unexpected plugin option app.use(Plugin, {}) // @ts-expect-error only no options is valid app.use(Plugin, undefined) } const PluginMultipleArgs = { install: (app: App, a: string, b: number) => {} } for (const Plugin of [PluginMultipleArgs, PluginMultipleArgs.install]) { // @ts-expect-error: 2 arguments expected app.use(Plugin, 'hey') app.use(Plugin, 'hey', 2) } const PluginOptionalOptions = { install( app: App, options: PluginOptions = { option2: 2, option3: true, option1: 'foo' } ) { options.option1 options.option2 options.option3 } } for (const Plugin of [PluginOptionalOptions, PluginOptionalOptions.install]) { // both version are valid app.use(Plugin) app.use(Plugin, undefined) // @ts-expect-error option2 and option3 (required) missing app.use(Plugin, {}) // valid options app.use(Plugin, { option2: 1, option3: true }) app.use(Plugin, { option1: 'foo', option2: 1, option3: true }) } // still valid but it's better to use the regular function because this one can accept an optional param const PluginTyped: Plugin<PluginOptions> = (app, options) => {} // @ts-expect-error: needs options app.use(PluginTyped) app.use(PluginTyped, { option2: 2, option3: true })
packages/dts-test/appUse.test-d.ts
0
https://github.com/vuejs/core/commit/657476dcdb964be4fbb1277c215c073f3275728e
[ 0.0006130712572485209, 0.00021321811072994024, 0.00016498724289704114, 0.00016895645239856094, 0.00013331681839190423 ]
{ "id": 1, "code_window": [ " for (const [v1, v2] of wrapped.entries()) {\n", " expect(isReadonly(v1)).toBe(true)\n", " expect(isReadonly(v2)).toBe(true)\n", " }\n", " })\n", " }\n", " })\n", " })\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " test('should return undefined from Set.clear() call', () => {\n", " const wrapped = readonly(new Collection())\n", " expect(wrapped.clear()).toBeUndefined()\n", " expect(\n", " `Clear operation failed: target is readonly.`\n", " ).toHaveBeenWarned()\n", " })\n" ], "file_path": "packages/reactivity/__tests__/readonly.spec.ts", "type": "add", "edit_start_line_idx": 334 }
import { isReactive, isReadonly, readonly, shallowReadonly } from '../src' describe('reactivity/shallowReadonly', () => { test('should not make non-reactive properties reactive', () => { const props = shallowReadonly({ n: { foo: 1 } }) expect(isReactive(props.n)).toBe(false) }) test('should make root level properties readonly', () => { const props = shallowReadonly({ n: 1 }) // @ts-expect-error props.n = 2 expect(props.n).toBe(1) expect( `Set operation on key "n" failed: target is readonly.` ).toHaveBeenWarned() }) // to retain 2.x behavior. test('should NOT make nested properties readonly', () => { const props = shallowReadonly({ n: { foo: 1 } }) props.n.foo = 2 expect(props.n.foo).toBe(2) expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() }) // #2843 test('should differentiate from normal readonly calls', () => { const original = { foo: {} } const shallowProxy = shallowReadonly(original) const reactiveProxy = readonly(original) expect(shallowProxy).not.toBe(reactiveProxy) expect(isReadonly(shallowProxy.foo)).toBe(false) expect(isReadonly(reactiveProxy.foo)).toBe(true) }) describe('collection/Map', () => { ;[Map, WeakMap].forEach(Collection => { test('should make the map/weak-map readonly', () => { const key = {} const val = { foo: 1 } const original = new Collection([[key, val]]) const sroMap = shallowReadonly(original) expect(isReadonly(sroMap)).toBe(true) expect(isReactive(sroMap)).toBe(false) expect(sroMap.get(key)).toBe(val) sroMap.set(key, {} as any) expect( `Set operation on key "[object Object]" failed: target is readonly.` ).toHaveBeenWarned() }) test('should not make nested values readonly', () => { const key = {} const val = { foo: 1 } const original = new Collection([[key, val]]) const sroMap = shallowReadonly(original) expect(isReadonly(sroMap.get(key))).toBe(false) expect(isReactive(sroMap.get(key))).toBe(false) sroMap.get(key)!.foo = 2 expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() }) }) test('should not make the value generated by the iterable method readonly', () => { const key = {} const val = { foo: 1 } const original = new Map([[key, val]]) const sroMap = shallowReadonly(original) const values1 = [...sroMap.values()] const values2 = [...sroMap.entries()] expect(isReadonly(values1[0])).toBe(false) expect(isReactive(values1[0])).toBe(false) expect(values1[0]).toBe(val) values1[0].foo = 2 expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() expect(isReadonly(values2[0][1])).toBe(false) expect(isReactive(values2[0][1])).toBe(false) expect(values2[0][1]).toBe(val) values2[0][1].foo = 2 expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() }) test('should not make the value generated by the forEach method readonly', () => { const val = { foo: 1 } const original = new Map([['key', val]]) const sroMap = shallowReadonly(original) sroMap.forEach(val => { expect(isReadonly(val)).toBe(false) expect(isReactive(val)).toBe(false) expect(val).toBe(val) val.foo = 2 expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() }) }) }) describe('collection/Set', () => { test('should make the set/weak-set readonly', () => { ;[Set, WeakSet].forEach(Collection => { const obj = { foo: 1 } const original = new Collection([obj]) const sroSet = shallowReadonly(original) expect(isReadonly(sroSet)).toBe(true) expect(isReactive(sroSet)).toBe(false) expect(sroSet.has(obj)).toBe(true) sroSet.add({} as any) expect( `Add operation on key "[object Object]" failed: target is readonly.` ).toHaveBeenWarned() }) }) test('should not make nested values readonly', () => { const obj = { foo: 1 } const original = new Set([obj]) const sroSet = shallowReadonly(original) const values = [...sroSet.values()] expect(values[0]).toBe(obj) expect(isReadonly(values[0])).toBe(false) expect(isReactive(values[0])).toBe(false) sroSet.add({} as any) expect( `Add operation on key "[object Object]" failed: target is readonly.` ).toHaveBeenWarned() values[0].foo = 2 expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() }) test('should not make the value generated by the iterable method readonly', () => { const val = { foo: 1 } const original = new Set([val]) const sroSet = shallowReadonly(original) const values1 = [...sroSet.values()] const values2 = [...sroSet.entries()] expect(isReadonly(values1[0])).toBe(false) expect(isReactive(values1[0])).toBe(false) expect(values1[0]).toBe(val) values1[0].foo = 2 expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() expect(isReadonly(values2[0][1])).toBe(false) expect(isReactive(values2[0][1])).toBe(false) expect(values2[0][1]).toBe(val) values2[0][1].foo = 2 expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() }) test('should not make the value generated by the forEach method readonly', () => { const val = { foo: 1 } const original = new Set([val]) const sroSet = shallowReadonly(original) sroSet.forEach(val => { expect(isReadonly(val)).toBe(false) expect(isReactive(val)).toBe(false) expect(val).toBe(val) val.foo = 2 expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() }) }) }) })
packages/reactivity/__tests__/shallowReadonly.spec.ts
1
https://github.com/vuejs/core/commit/657476dcdb964be4fbb1277c215c073f3275728e
[ 0.00021217140601947904, 0.00017189030768349767, 0.00016463978681713343, 0.00016973041056189686, 0.000009478173524257727 ]
{ "id": 1, "code_window": [ " for (const [v1, v2] of wrapped.entries()) {\n", " expect(isReadonly(v1)).toBe(true)\n", " expect(isReadonly(v2)).toBe(true)\n", " }\n", " })\n", " }\n", " })\n", " })\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " test('should return undefined from Set.clear() call', () => {\n", " const wrapped = readonly(new Collection())\n", " expect(wrapped.clear()).toBeUndefined()\n", " expect(\n", " `Clear operation failed: target is readonly.`\n", " ).toHaveBeenWarned()\n", " })\n" ], "file_path": "packages/reactivity/__tests__/readonly.spec.ts", "type": "add", "edit_start_line_idx": 334 }
// This entry is the "full-build" that includes both the runtime // and the compiler, and supports on-the-fly compilation of the template option. import { createCompatVue } from './createCompatVue' import { compile, CompilerError, CompilerOptions } from '@vue/compiler-dom' import { registerRuntimeCompiler, RenderFunction, warn } from '@vue/runtime-dom' import { isString, NOOP, generateCodeFrame, extend } from '@vue/shared' import { InternalRenderFunction } from 'packages/runtime-core/src/component' import * as runtimeDom from '@vue/runtime-dom' import { DeprecationTypes, warnDeprecation } from '../../runtime-core/src/compat/compatConfig' const compileCache: Record<string, RenderFunction> = Object.create(null) function compileToFunction( template: string | HTMLElement, options?: CompilerOptions ): RenderFunction { if (!isString(template)) { if (template.nodeType) { template = template.innerHTML } else { __DEV__ && warn(`invalid template option: `, template) return NOOP } } const key = template const cached = compileCache[key] if (cached) { return cached } if (template[0] === '#') { const el = document.querySelector(template) if (__DEV__ && !el) { warn(`Template element not found or is empty: ${template}`) } // __UNSAFE__ // Reason: potential execution of JS expressions in in-DOM template. // The user must make sure the in-DOM template is trusted. If it's rendered // by the server, the template should not contain any user data. template = el ? el.innerHTML : `` } if (__DEV__ && !__TEST__ && (!options || !options.whitespace)) { warnDeprecation(DeprecationTypes.CONFIG_WHITESPACE, null) } const { code } = compile( template, extend( { hoistStatic: true, whitespace: 'preserve', onError: __DEV__ ? onError : undefined, onWarn: __DEV__ ? e => onError(e, true) : NOOP } as CompilerOptions, options ) ) function onError(err: CompilerError, asWarning = false) { const message = asWarning ? err.message : `Template compilation error: ${err.message}` const codeFrame = err.loc && generateCodeFrame( template as string, err.loc.start.offset, err.loc.end.offset ) warn(codeFrame ? `${message}\n${codeFrame}` : message) } // The wildcard import results in a huge object with every export // with keys that cannot be mangled, and can be quite heavy size-wise. // In the global build we know `Vue` is available globally so we can avoid // the wildcard object. const render = ( __GLOBAL__ ? new Function(code)() : new Function('Vue', code)(runtimeDom) ) as RenderFunction // mark the function as runtime compiled ;(render as InternalRenderFunction)._rc = true return (compileCache[key] = render) } registerRuntimeCompiler(compileToFunction) const Vue = createCompatVue() Vue.compile = compileToFunction export default Vue
packages/vue-compat/src/index.ts
0
https://github.com/vuejs/core/commit/657476dcdb964be4fbb1277c215c073f3275728e
[ 0.00017814370221458375, 0.00017459449009038508, 0.00017145492893178016, 0.000174936096300371, 0.0000019922190404031426 ]
{ "id": 1, "code_window": [ " for (const [v1, v2] of wrapped.entries()) {\n", " expect(isReadonly(v1)).toBe(true)\n", " expect(isReadonly(v2)).toBe(true)\n", " }\n", " })\n", " }\n", " })\n", " })\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " test('should return undefined from Set.clear() call', () => {\n", " const wrapped = readonly(new Collection())\n", " expect(wrapped.clear()).toBeUndefined()\n", " expect(\n", " `Clear operation failed: target is readonly.`\n", " ).toHaveBeenWarned()\n", " })\n" ], "file_path": "packages/reactivity/__tests__/readonly.spec.ts", "type": "add", "edit_start_line_idx": 334 }
{ "private": true, "version": "3.3.8", "packageManager": "[email protected]", "type": "module", "scripts": { "dev": "node scripts/dev.js", "build": "node scripts/build.js", "build-dts": "tsc -p tsconfig.build.json && rollup -c rollup.dts.config.js", "clean": "rimraf packages/*/dist temp .eslintcache", "size": "run-s \"size-*\" && tsx scripts/usage-size.ts", "size-global": "node scripts/build.js vue runtime-dom -f global -p --size", "size-esm-runtime": "node scripts/build.js vue -f esm-bundler-runtime", "size-esm": "node scripts/build.js runtime-dom runtime-core reactivity shared -f esm-bundler", "check": "tsc --incremental --noEmit", "lint": "eslint --cache --ext .ts packages/*/{src,__tests__}/**.ts", "format": "prettier --write --cache \"**/*.[tj]s?(x)\"", "format-check": "prettier --check --cache \"**/*.[tj]s?(x)\"", "test": "vitest", "test-unit": "vitest -c vitest.unit.config.ts", "test-e2e": "node scripts/build.js vue -f global -d && vitest -c vitest.e2e.config.ts", "test-dts": "run-s build-dts test-dts-only", "test-dts-only": "tsc -p ./packages/dts-test/tsconfig.test.json", "test-coverage": "vitest -c vitest.unit.config.ts --coverage", "release": "node scripts/release.js", "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s", "dev-esm": "node scripts/dev.js -if esm-bundler-runtime", "dev-compiler": "run-p \"dev template-explorer\" serve", "dev-sfc": "run-s dev-sfc-prepare dev-sfc-run", "dev-sfc-prepare": "node scripts/pre-dev-sfc.js || npm run build-compiler-cjs", "dev-sfc-serve": "vite packages/sfc-playground --host", "dev-sfc-run": "run-p \"dev compiler-sfc -f esm-browser\" \"dev vue -if esm-bundler-runtime\" \"dev server-renderer -if esm-bundler\" dev-sfc-serve", "serve": "serve", "open": "open http://localhost:3000/packages/template-explorer/local.html", "build-sfc-playground": "run-s build-all-cjs build-runtime-esm build-ssr-esm build-sfc-playground-self", "build-all-cjs": "node scripts/build.js vue runtime compiler reactivity reactivity-transform shared -af cjs", "build-runtime-esm": "node scripts/build.js runtime reactivity shared -af esm-bundler && node scripts/build.js vue -f esm-bundler-runtime && node scripts/build.js vue -f esm-browser-runtime", "build-ssr-esm": "node scripts/build.js compiler-sfc server-renderer -f esm-browser", "build-sfc-playground-self": "cd packages/sfc-playground && npm run build", "preinstall": "npx only-allow pnpm", "postinstall": "simple-git-hooks" }, "simple-git-hooks": { "pre-commit": "pnpm lint-staged && pnpm check", "commit-msg": "node scripts/verifyCommit.js" }, "lint-staged": { "*.{js,json}": [ "prettier --write" ], "*.ts?(x)": [ "eslint", "prettier --parser=typescript --write" ] }, "engines": { "node": ">=18.12.0" }, "devDependencies": { "@babel/parser": "^7.23.0", "@babel/types": "^7.23.0", "@rollup/plugin-alias": "^5.0.1", "@rollup/plugin-commonjs": "^25.0.7", "@rollup/plugin-json": "^6.0.1", "@rollup/plugin-node-resolve": "^15.2.3", "@rollup/plugin-replace": "^5.0.4", "@rollup/plugin-terser": "^0.4.4", "@types/hash-sum": "^1.0.1", "@types/node": "^20.8.10", "@typescript-eslint/parser": "^6.9.1", "@vitest/coverage-istanbul": "^0.34.6", "@vue/consolidate": "0.17.3", "conventional-changelog-cli": "^4.1.0", "enquirer": "^2.4.1", "esbuild": "^0.19.5", "esbuild-plugin-polyfill-node": "^0.3.0", "eslint": "^8.52.0", "eslint-plugin-jest": "^27.6.0", "estree-walker": "^2.0.2", "execa": "^8.0.1", "jsdom": "^22.1.0", "lint-staged": "^15.0.2", "lodash": "^4.17.21", "magic-string": "^0.30.5", "markdown-table": "^3.0.3", "marked": "^9.1.4", "minimist": "^1.2.8", "npm-run-all": "^4.1.5", "picocolors": "^1.0.0", "prettier": "^3.0.3", "pretty-bytes": "^6.1.1", "pug": "^3.0.2", "puppeteer": "~21.4.1", "rimraf": "^5.0.5", "rollup": "^4.1.4", "rollup-plugin-dts": "^6.1.0", "rollup-plugin-esbuild": "^6.1.0", "rollup-plugin-polyfill-node": "^0.12.0", "semver": "^7.5.4", "serve": "^14.2.1", "simple-git-hooks": "^2.9.0", "terser": "^5.22.0", "todomvc-app-css": "^2.4.3", "tslib": "^2.6.2", "tsx": "^3.14.0", "typescript": "^5.2.2", "vite": "^4.5.0", "vitest": "^0.34.6" } }
package.json
0
https://github.com/vuejs/core/commit/657476dcdb964be4fbb1277c215c073f3275728e
[ 0.0001762621250236407, 0.00017423584358766675, 0.00016872367996256799, 0.00017463980475440621, 0.0000019261628949607257 ]
{ "id": 1, "code_window": [ " for (const [v1, v2] of wrapped.entries()) {\n", " expect(isReadonly(v1)).toBe(true)\n", " expect(isReadonly(v2)).toBe(true)\n", " }\n", " })\n", " }\n", " })\n", " })\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " test('should return undefined from Set.clear() call', () => {\n", " const wrapped = readonly(new Collection())\n", " expect(wrapped.clear()).toBeUndefined()\n", " expect(\n", " `Clear operation failed: target is readonly.`\n", " ).toHaveBeenWarned()\n", " })\n" ], "file_path": "packages/reactivity/__tests__/readonly.spec.ts", "type": "add", "edit_start_line_idx": 334 }
// SVG logic is technically dom-specific, but the logic is placed in core // because splitting it out of core would lead to unnecessary complexity in both // the renderer and compiler implementations. // Related files: // - runtime-core/src/renderer.ts // - compiler-core/src/transforms/transformElement.ts import { vtcKey } from '../../runtime-dom/src/components/Transition' import { render, h, ref, nextTick } from '../src' describe('SVG support', () => { test('should mount elements with correct namespaces', () => { const root = document.createElement('div') document.body.appendChild(root) const App = { template: ` <div id="e0"> <svg id="e1"> <foreignObject id="e2"> <div id="e3"/> </foreignObject> </svg> </div> ` } render(h(App), root) const e0 = document.getElementById('e0')! expect(e0.namespaceURI).toMatch('xhtml') expect(e0.querySelector('#e1')!.namespaceURI).toMatch('svg') expect(e0.querySelector('#e2')!.namespaceURI).toMatch('svg') expect(e0.querySelector('#e3')!.namespaceURI).toMatch('xhtml') }) test('should patch elements with correct namespaces', async () => { const root = document.createElement('div') document.body.appendChild(root) const cls = ref('foo') const App = { setup: () => ({ cls }), template: ` <div> <svg id="f1" :class="cls"> <foreignObject> <div id="f2" :class="cls"/> </foreignObject> </svg> </div> ` } render(h(App), root) const f1 = document.querySelector('#f1')! const f2 = document.querySelector('#f2')! expect(f1.getAttribute('class')).toBe('foo') expect(f2.className).toBe('foo') // set a transition class on the <div> - which is only respected on non-svg // patches ;(f2 as any)[vtcKey] = ['baz'] cls.value = 'bar' await nextTick() expect(f1.getAttribute('class')).toBe('bar') expect(f2.className).toBe('bar baz') }) })
packages/vue/__tests__/svgNamespace.spec.ts
0
https://github.com/vuejs/core/commit/657476dcdb964be4fbb1277c215c073f3275728e
[ 0.00017817868501879275, 0.0001726347691146657, 0.00016294166562147439, 0.00017241612658835948, 0.0000047838502723607235 ]
{ "id": 2, "code_window": [ " `Set operation on key \"foo\" failed: target is readonly.`\n", " ).not.toHaveBeenWarned()\n", " })\n", " })\n", " })\n", "\n", " describe('collection/Set', () => {\n", " test('should make the set/weak-set readonly', () => {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " test('should return undefined from Map.clear() call', () => {\n", " const sroMap = shallowReadonly(new Map())\n", " expect(sroMap.clear()).toBeUndefined()\n", " expect(`Clear operation failed: target is readonly.`).toHaveBeenWarned()\n", " })\n" ], "file_path": "packages/reactivity/__tests__/shallowReadonly.spec.ts", "type": "add", "edit_start_line_idx": 115 }
import { isReactive, isReadonly, readonly, shallowReadonly } from '../src' describe('reactivity/shallowReadonly', () => { test('should not make non-reactive properties reactive', () => { const props = shallowReadonly({ n: { foo: 1 } }) expect(isReactive(props.n)).toBe(false) }) test('should make root level properties readonly', () => { const props = shallowReadonly({ n: 1 }) // @ts-expect-error props.n = 2 expect(props.n).toBe(1) expect( `Set operation on key "n" failed: target is readonly.` ).toHaveBeenWarned() }) // to retain 2.x behavior. test('should NOT make nested properties readonly', () => { const props = shallowReadonly({ n: { foo: 1 } }) props.n.foo = 2 expect(props.n.foo).toBe(2) expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() }) // #2843 test('should differentiate from normal readonly calls', () => { const original = { foo: {} } const shallowProxy = shallowReadonly(original) const reactiveProxy = readonly(original) expect(shallowProxy).not.toBe(reactiveProxy) expect(isReadonly(shallowProxy.foo)).toBe(false) expect(isReadonly(reactiveProxy.foo)).toBe(true) }) describe('collection/Map', () => { ;[Map, WeakMap].forEach(Collection => { test('should make the map/weak-map readonly', () => { const key = {} const val = { foo: 1 } const original = new Collection([[key, val]]) const sroMap = shallowReadonly(original) expect(isReadonly(sroMap)).toBe(true) expect(isReactive(sroMap)).toBe(false) expect(sroMap.get(key)).toBe(val) sroMap.set(key, {} as any) expect( `Set operation on key "[object Object]" failed: target is readonly.` ).toHaveBeenWarned() }) test('should not make nested values readonly', () => { const key = {} const val = { foo: 1 } const original = new Collection([[key, val]]) const sroMap = shallowReadonly(original) expect(isReadonly(sroMap.get(key))).toBe(false) expect(isReactive(sroMap.get(key))).toBe(false) sroMap.get(key)!.foo = 2 expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() }) }) test('should not make the value generated by the iterable method readonly', () => { const key = {} const val = { foo: 1 } const original = new Map([[key, val]]) const sroMap = shallowReadonly(original) const values1 = [...sroMap.values()] const values2 = [...sroMap.entries()] expect(isReadonly(values1[0])).toBe(false) expect(isReactive(values1[0])).toBe(false) expect(values1[0]).toBe(val) values1[0].foo = 2 expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() expect(isReadonly(values2[0][1])).toBe(false) expect(isReactive(values2[0][1])).toBe(false) expect(values2[0][1]).toBe(val) values2[0][1].foo = 2 expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() }) test('should not make the value generated by the forEach method readonly', () => { const val = { foo: 1 } const original = new Map([['key', val]]) const sroMap = shallowReadonly(original) sroMap.forEach(val => { expect(isReadonly(val)).toBe(false) expect(isReactive(val)).toBe(false) expect(val).toBe(val) val.foo = 2 expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() }) }) }) describe('collection/Set', () => { test('should make the set/weak-set readonly', () => { ;[Set, WeakSet].forEach(Collection => { const obj = { foo: 1 } const original = new Collection([obj]) const sroSet = shallowReadonly(original) expect(isReadonly(sroSet)).toBe(true) expect(isReactive(sroSet)).toBe(false) expect(sroSet.has(obj)).toBe(true) sroSet.add({} as any) expect( `Add operation on key "[object Object]" failed: target is readonly.` ).toHaveBeenWarned() }) }) test('should not make nested values readonly', () => { const obj = { foo: 1 } const original = new Set([obj]) const sroSet = shallowReadonly(original) const values = [...sroSet.values()] expect(values[0]).toBe(obj) expect(isReadonly(values[0])).toBe(false) expect(isReactive(values[0])).toBe(false) sroSet.add({} as any) expect( `Add operation on key "[object Object]" failed: target is readonly.` ).toHaveBeenWarned() values[0].foo = 2 expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() }) test('should not make the value generated by the iterable method readonly', () => { const val = { foo: 1 } const original = new Set([val]) const sroSet = shallowReadonly(original) const values1 = [...sroSet.values()] const values2 = [...sroSet.entries()] expect(isReadonly(values1[0])).toBe(false) expect(isReactive(values1[0])).toBe(false) expect(values1[0]).toBe(val) values1[0].foo = 2 expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() expect(isReadonly(values2[0][1])).toBe(false) expect(isReactive(values2[0][1])).toBe(false) expect(values2[0][1]).toBe(val) values2[0][1].foo = 2 expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() }) test('should not make the value generated by the forEach method readonly', () => { const val = { foo: 1 } const original = new Set([val]) const sroSet = shallowReadonly(original) sroSet.forEach(val => { expect(isReadonly(val)).toBe(false) expect(isReactive(val)).toBe(false) expect(val).toBe(val) val.foo = 2 expect( `Set operation on key "foo" failed: target is readonly.` ).not.toHaveBeenWarned() }) }) }) })
packages/reactivity/__tests__/shallowReadonly.spec.ts
1
https://github.com/vuejs/core/commit/657476dcdb964be4fbb1277c215c073f3275728e
[ 0.6485542058944702, 0.03308873996138573, 0.00016818029689602554, 0.0007844880456104875, 0.1376713663339615 ]
{ "id": 2, "code_window": [ " `Set operation on key \"foo\" failed: target is readonly.`\n", " ).not.toHaveBeenWarned()\n", " })\n", " })\n", " })\n", "\n", " describe('collection/Set', () => {\n", " test('should make the set/weak-set readonly', () => {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " test('should return undefined from Map.clear() call', () => {\n", " const sroMap = shallowReadonly(new Map())\n", " expect(sroMap.clear()).toBeUndefined()\n", " expect(`Clear operation failed: target is readonly.`).toHaveBeenWarned()\n", " })\n" ], "file_path": "packages/reactivity/__tests__/shallowReadonly.spec.ts", "type": "add", "edit_start_line_idx": 115 }
import { LRUCache } from 'lru-cache' export function createCache<T extends {}>( max = 500 ): Map<string, T> | LRUCache<string, T> { if (__GLOBAL__ || __ESM_BROWSER__) { return new Map<string, T>() } return new LRUCache({ max }) }
packages/compiler-sfc/src/cache.ts
0
https://github.com/vuejs/core/commit/657476dcdb964be4fbb1277c215c073f3275728e
[ 0.00017800887871999294, 0.00017517716332804412, 0.0001723454479360953, 0.00017517716332804412, 0.000002831715391948819 ]
{ "id": 2, "code_window": [ " `Set operation on key \"foo\" failed: target is readonly.`\n", " ).not.toHaveBeenWarned()\n", " })\n", " })\n", " })\n", "\n", " describe('collection/Set', () => {\n", " test('should make the set/weak-set readonly', () => {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " test('should return undefined from Map.clear() call', () => {\n", " const sroMap = shallowReadonly(new Map())\n", " expect(sroMap.clear()).toBeUndefined()\n", " expect(`Clear operation failed: target is readonly.`).toHaveBeenWarned()\n", " })\n" ], "file_path": "packages/reactivity/__tests__/shallowReadonly.spec.ts", "type": "add", "edit_start_line_idx": 115 }
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html exports[`defineProps > basic usage 1`] = ` "const bar = 1 export default { props: { foo: String }, setup(__props, { expose: __expose }) { __expose(); const props = __props return { props, bar } } }" `; exports[`defineProps > defineProps w/ runtime options 1`] = ` "import { defineComponent as _defineComponent } from 'vue' export default /*#__PURE__*/_defineComponent({ props: { foo: String }, setup(__props, { expose: __expose }) { __expose(); const props = __props return { props } } })" `; exports[`defineProps > destructure without enabling reactive destructure 1`] = ` "import { defineComponent as _defineComponent } from 'vue' export default /*#__PURE__*/_defineComponent({ props: { foo: { type: null, required: true } }, setup(__props: any, { expose: __expose }) { __expose(); const { foo } = __props return { } } })" `; exports[`defineProps > w/ TS assertion 1`] = ` "import { defineComponent as _defineComponent } from 'vue' export default /*#__PURE__*/_defineComponent({ props: ['foo'], setup(__props, { expose: __expose }) { __expose(); return { } } })" `; exports[`defineProps > w/ exported interface 1`] = ` "import { defineComponent as _defineComponent } from 'vue' export interface Props { x?: number } export default /*#__PURE__*/_defineComponent({ props: { x: { type: Number, required: false } }, setup(__props: any, { expose: __expose }) { __expose(); return { } } })" `; exports[`defineProps > w/ exported interface in normal script 1`] = ` "import { defineComponent as _defineComponent } from 'vue' export interface Props { x?: number } export default /*#__PURE__*/_defineComponent({ props: { x: { type: Number, required: false } }, setup(__props: any, { expose: __expose }) { __expose(); return { } } })" `; exports[`defineProps > w/ exported type alias 1`] = ` "import { defineComponent as _defineComponent } from 'vue' export type Props = { x?: number } export default /*#__PURE__*/_defineComponent({ props: { x: { type: Number, required: false } }, setup(__props: any, { expose: __expose }) { __expose(); return { } } })" `; exports[`defineProps > w/ extends interface 1`] = ` "import { defineComponent as _defineComponent } from 'vue' interface Bar extends Foo { y?: number } interface Props extends Bar { z: number y: string } interface Foo { x?: number } export default /*#__PURE__*/_defineComponent({ props: { z: { type: Number, required: true }, y: { type: String, required: true }, x: { type: Number, required: false } }, setup(__props: any, { expose: __expose }) { __expose(); return { } } })" `; exports[`defineProps > w/ external definition 1`] = ` "import { propsModel } from './props' export default { props: propsModel, setup(__props, { expose: __expose }) { __expose(); const props = __props return { props, get propsModel() { return propsModel } } } }" `; exports[`defineProps > w/ interface 1`] = ` "import { defineComponent as _defineComponent } from 'vue' interface Props { x?: number } export default /*#__PURE__*/_defineComponent({ props: { x: { type: Number, required: false } }, setup(__props: any, { expose: __expose }) { __expose(); return { } } })" `; exports[`defineProps > w/ leading code 1`] = ` "import { x } from './x' export default { props: {}, setup(__props, { expose: __expose }) { __expose(); const props = __props return { props, get x() { return x } } } }" `; exports[`defineProps > w/ type 1`] = ` "import { defineComponent as _defineComponent } from 'vue' interface Test {} type Alias = number[] export default /*#__PURE__*/_defineComponent({ props: { string: { type: String, required: true }, number: { type: Number, required: true }, boolean: { type: Boolean, required: true }, object: { type: Object, required: true }, objectLiteral: { type: Object, required: true }, fn: { type: Function, required: true }, functionRef: { type: Function, required: true }, objectRef: { type: Object, required: true }, dateTime: { type: Date, required: true }, array: { type: Array, required: true }, arrayRef: { type: Array, required: true }, tuple: { type: Array, required: true }, set: { type: Set, required: true }, literal: { type: String, required: true }, optional: { type: null, required: false }, recordRef: { type: Object, required: true }, interface: { type: Object, required: true }, alias: { type: Array, required: true }, method: { type: Function, required: true }, symbol: { type: Symbol, required: true }, error: { type: Error, required: true }, extract: { type: Number, required: true }, exclude: { type: [Number, Boolean], required: true }, uppercase: { type: String, required: true }, params: { type: Array, required: true }, nonNull: { type: String, required: true }, objectOrFn: { type: [Function, Object], required: true }, union: { type: [String, Number], required: true }, literalUnion: { type: String, required: true }, literalUnionNumber: { type: Number, required: true }, literalUnionMixed: { type: [String, Number, Boolean], required: true }, intersection: { type: Object, required: true }, intersection2: { type: String, required: true }, foo: { type: [Function, null], required: true }, unknown: { type: null, required: true }, unknownUnion: { type: null, required: true }, unknownIntersection: { type: Object, required: true }, unknownUnionWithBoolean: { type: Boolean, required: true, skipCheck: true }, unknownUnionWithFunction: { type: Function, required: true, skipCheck: true } }, setup(__props: any, { expose: __expose }) { __expose(); return { } } })" `; exports[`defineProps > w/ type alias 1`] = ` "import { defineComponent as _defineComponent } from 'vue' type Props = { x?: number } export default /*#__PURE__*/_defineComponent({ props: { x: { type: Number, required: false } }, setup(__props: any, { expose: __expose }) { __expose(); return { } } })" `; exports[`defineProps > withDefaults (dynamic) 1`] = ` "import { mergeDefaults as _mergeDefaults, defineComponent as _defineComponent } from 'vue' import { defaults } from './foo' export default /*#__PURE__*/_defineComponent({ props: _mergeDefaults({ foo: { type: String, required: false }, bar: { type: Number, required: false }, baz: { type: Boolean, required: true } }, { ...defaults }), setup(__props: any, { expose: __expose }) { __expose(); const props = __props return { props, get defaults() { return defaults } } } })" `; exports[`defineProps > withDefaults (dynamic) w/ production mode 1`] = ` "import { mergeDefaults as _mergeDefaults, defineComponent as _defineComponent } from 'vue' import { defaults } from './foo' export default /*#__PURE__*/_defineComponent({ props: _mergeDefaults({ foo: { type: Function }, bar: { type: Boolean }, baz: { type: [Boolean, Function] }, qux: {} }, { ...defaults }), setup(__props: any, { expose: __expose }) { __expose(); const props = __props return { props, get defaults() { return defaults } } } })" `; exports[`defineProps > withDefaults (reference) 1`] = ` "import { mergeDefaults as _mergeDefaults, defineComponent as _defineComponent } from 'vue' import { defaults } from './foo' export default /*#__PURE__*/_defineComponent({ props: _mergeDefaults({ foo: { type: String, required: false }, bar: { type: Number, required: false }, baz: { type: Boolean, required: true } }, defaults), setup(__props: any, { expose: __expose }) { __expose(); const props = __props return { props, get defaults() { return defaults } } } })" `; exports[`defineProps > withDefaults (static) + normal script 1`] = ` "import { defineComponent as _defineComponent } from 'vue' interface Props { a?: string; } export default /*#__PURE__*/_defineComponent({ props: { a: { type: String, required: false, default: \\"a\\" } }, setup(__props: any, { expose: __expose }) { __expose(); const props = __props; return { props } } })" `; exports[`defineProps > withDefaults (static) 1`] = ` "import { defineComponent as _defineComponent } from 'vue' export default /*#__PURE__*/_defineComponent({ props: { foo: { type: String, required: false, default: 'hi' }, bar: { type: Number, required: false }, baz: { type: Boolean, required: true }, qux: { type: Function, required: false, default() { return 1 } }, quux: { type: Function, required: false, default() { } }, quuxx: { type: Promise, required: false, async default() { return await Promise.resolve('hi') } }, fred: { type: String, required: false, get default() { return 'fred' } } }, setup(__props: any, { expose: __expose }) { __expose(); const props = __props return { props } } })" `; exports[`defineProps > withDefaults (static) w/ production mode 1`] = ` "import { defineComponent as _defineComponent } from 'vue' export default /*#__PURE__*/_defineComponent({ props: { foo: {}, bar: { type: Boolean }, baz: { type: [Boolean, Function], default: true }, qux: { default: 'hi' } }, setup(__props: any, { expose: __expose }) { __expose(); const props = __props return { props } } })" `; exports[`defineProps > withDefaults w/ dynamic object method 1`] = ` "import { mergeDefaults as _mergeDefaults, defineComponent as _defineComponent } from 'vue' export default /*#__PURE__*/_defineComponent({ props: _mergeDefaults({ foo: { type: Function, required: false } }, { ['fo' + 'o']() { return 'foo' } }), setup(__props: any, { expose: __expose }) { __expose(); const props = __props return { props } } })" `;
packages/compiler-sfc/__tests__/compileScript/__snapshots__/defineProps.spec.ts.snap
0
https://github.com/vuejs/core/commit/657476dcdb964be4fbb1277c215c073f3275728e
[ 0.00029334178543649614, 0.00017492688493803144, 0.0001558548101456836, 0.0001730198709992692, 0.000018438087863614783 ]
{ "id": 2, "code_window": [ " `Set operation on key \"foo\" failed: target is readonly.`\n", " ).not.toHaveBeenWarned()\n", " })\n", " })\n", " })\n", "\n", " describe('collection/Set', () => {\n", " test('should make the set/weak-set readonly', () => {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " test('should return undefined from Map.clear() call', () => {\n", " const sroMap = shallowReadonly(new Map())\n", " expect(sroMap.clear()).toBeUndefined()\n", " expect(`Clear operation failed: target is readonly.`).toHaveBeenWarned()\n", " })\n" ], "file_path": "packages/reactivity/__tests__/shallowReadonly.spec.ts", "type": "add", "edit_start_line_idx": 115 }
The MIT License (MIT) Copyright (c) 2018-present, Yuxi (Evan) You 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.
packages/compiler-core/LICENSE
0
https://github.com/vuejs/core/commit/657476dcdb964be4fbb1277c215c073f3275728e
[ 0.00017910462338477373, 0.000174646163941361, 0.00017116987146437168, 0.00017366399697493762, 0.0000033129604162240867 ]
{ "id": 3, "code_window": [ " `Set operation on key \"foo\" failed: target is readonly.`\n", " ).not.toHaveBeenWarned()\n", " })\n", " })\n", " })\n", "})" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\n", " test('should return undefined from Set.clear() call', () => {\n", " const sroSet = shallowReadonly(new Set())\n", " expect(sroSet.clear()).toBeUndefined()\n", " expect(`Clear operation failed: target is readonly.`).toHaveBeenWarned()\n", " })\n" ], "file_path": "packages/reactivity/__tests__/shallowReadonly.spec.ts", "type": "add", "edit_start_line_idx": 199 }
import { reactive, readonly, toRaw, isReactive, isReadonly, markRaw, effect, ref, isProxy, computed } from '../src' /** * @see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html */ type Writable<T> = { -readonly [P in keyof T]: T[P] } describe('reactivity/readonly', () => { describe('Object', () => { it('should make nested values readonly', () => { const original = { foo: 1, bar: { baz: 2 } } const wrapped = readonly(original) expect(wrapped).not.toBe(original) expect(isProxy(wrapped)).toBe(true) expect(isReactive(wrapped)).toBe(false) expect(isReadonly(wrapped)).toBe(true) expect(isReactive(original)).toBe(false) expect(isReadonly(original)).toBe(false) expect(isReactive(wrapped.bar)).toBe(false) expect(isReadonly(wrapped.bar)).toBe(true) expect(isReactive(original.bar)).toBe(false) expect(isReadonly(original.bar)).toBe(false) // get expect(wrapped.foo).toBe(1) // has expect('foo' in wrapped).toBe(true) // ownKeys expect(Object.keys(wrapped)).toEqual(['foo', 'bar']) }) it('should not allow mutation', () => { const qux = Symbol('qux') const original = { foo: 1, bar: { baz: 2 }, [qux]: 3 } const wrapped: Writable<typeof original> = readonly(original) wrapped.foo = 2 expect(wrapped.foo).toBe(1) expect( `Set operation on key "foo" failed: target is readonly.` ).toHaveBeenWarnedLast() wrapped.bar.baz = 3 expect(wrapped.bar.baz).toBe(2) expect( `Set operation on key "baz" failed: target is readonly.` ).toHaveBeenWarnedLast() wrapped[qux] = 4 expect(wrapped[qux]).toBe(3) expect( `Set operation on key "Symbol(qux)" failed: target is readonly.` ).toHaveBeenWarnedLast() // @ts-expect-error delete wrapped.foo expect(wrapped.foo).toBe(1) expect( `Delete operation on key "foo" failed: target is readonly.` ).toHaveBeenWarnedLast() // @ts-expect-error delete wrapped.bar.baz expect(wrapped.bar.baz).toBe(2) expect( `Delete operation on key "baz" failed: target is readonly.` ).toHaveBeenWarnedLast() // @ts-expect-error delete wrapped[qux] expect(wrapped[qux]).toBe(3) expect( `Delete operation on key "Symbol(qux)" failed: target is readonly.` ).toHaveBeenWarnedLast() }) it('should not trigger effects', () => { const wrapped: any = readonly({ a: 1 }) let dummy effect(() => { dummy = wrapped.a }) expect(dummy).toBe(1) wrapped.a = 2 expect(wrapped.a).toBe(1) expect(dummy).toBe(1) expect(`target is readonly`).toHaveBeenWarned() }) }) describe('Array', () => { it('should make nested values readonly', () => { const original = [{ foo: 1 }] const wrapped = readonly(original) expect(wrapped).not.toBe(original) expect(isProxy(wrapped)).toBe(true) expect(isReactive(wrapped)).toBe(false) expect(isReadonly(wrapped)).toBe(true) expect(isReactive(original)).toBe(false) expect(isReadonly(original)).toBe(false) expect(isReactive(wrapped[0])).toBe(false) expect(isReadonly(wrapped[0])).toBe(true) expect(isReactive(original[0])).toBe(false) expect(isReadonly(original[0])).toBe(false) // get expect(wrapped[0].foo).toBe(1) // has expect(0 in wrapped).toBe(true) // ownKeys expect(Object.keys(wrapped)).toEqual(['0']) }) it('should not allow mutation', () => { const wrapped: any = readonly([{ foo: 1 }]) wrapped[0] = 1 expect(wrapped[0]).not.toBe(1) expect( `Set operation on key "0" failed: target is readonly.` ).toHaveBeenWarned() wrapped[0].foo = 2 expect(wrapped[0].foo).toBe(1) expect( `Set operation on key "foo" failed: target is readonly.` ).toHaveBeenWarned() // should block length mutation wrapped.length = 0 expect(wrapped.length).toBe(1) expect(wrapped[0].foo).toBe(1) expect( `Set operation on key "length" failed: target is readonly.` ).toHaveBeenWarned() // mutation methods invoke set/length internally and thus are blocked as well wrapped.push(2) expect(wrapped.length).toBe(1) // push triggers two warnings on [1] and .length expect(`target is readonly.`).toHaveBeenWarnedTimes(5) }) it('should not trigger effects', () => { const wrapped: any = readonly([{ a: 1 }]) let dummy effect(() => { dummy = wrapped[0].a }) expect(dummy).toBe(1) wrapped[0].a = 2 expect(wrapped[0].a).toBe(1) expect(dummy).toBe(1) expect(`target is readonly`).toHaveBeenWarnedTimes(1) wrapped[0] = { a: 2 } expect(wrapped[0].a).toBe(1) expect(dummy).toBe(1) expect(`target is readonly`).toHaveBeenWarnedTimes(2) }) }) const maps = [Map, WeakMap] maps.forEach((Collection: any) => { describe(Collection.name, () => { test('should make nested values readonly', () => { const key1 = {} const key2 = {} const original = new Collection([ [key1, {}], [key2, {}] ]) const wrapped = readonly(original) expect(wrapped).not.toBe(original) expect(isProxy(wrapped)).toBe(true) expect(isReactive(wrapped)).toBe(false) expect(isReadonly(wrapped)).toBe(true) expect(isReactive(original)).toBe(false) expect(isReadonly(original)).toBe(false) expect(isReactive(wrapped.get(key1))).toBe(false) expect(isReadonly(wrapped.get(key1))).toBe(true) expect(isReactive(original.get(key1))).toBe(false) expect(isReadonly(original.get(key1))).toBe(false) }) test('should not allow mutation & not trigger effect', () => { const map = readonly(new Collection()) const key = {} let dummy effect(() => { dummy = map.get(key) }) expect(dummy).toBeUndefined() map.set(key, 1) expect(dummy).toBeUndefined() expect(map.has(key)).toBe(false) expect( `Set operation on key "${key}" failed: target is readonly.` ).toHaveBeenWarned() }) // #1772 test('readonly + reactive should make get() value also readonly + reactive', () => { const map = reactive(new Collection()) const roMap = readonly(map) const key = {} map.set(key, {}) const item = map.get(key) expect(isReactive(item)).toBe(true) expect(isReadonly(item)).toBe(false) const roItem = roMap.get(key) expect(isReactive(roItem)).toBe(true) expect(isReadonly(roItem)).toBe(true) }) if (Collection === Map) { test('should retrieve readonly values on iteration', () => { const key1 = {} const key2 = {} const original = new Map([ [key1, {}], [key2, {}] ]) const wrapped: any = readonly(original) expect(wrapped.size).toBe(2) for (const [key, value] of wrapped) { expect(isReadonly(key)).toBe(true) expect(isReadonly(value)).toBe(true) } wrapped.forEach((value: any) => { expect(isReadonly(value)).toBe(true) }) for (const value of wrapped.values()) { expect(isReadonly(value)).toBe(true) } }) test('should retrieve reactive + readonly values on iteration', () => { const key1 = {} const key2 = {} const original = reactive( new Map([ [key1, {}], [key2, {}] ]) ) const wrapped: any = readonly(original) expect(wrapped.size).toBe(2) for (const [key, value] of wrapped) { expect(isReadonly(key)).toBe(true) expect(isReadonly(value)).toBe(true) expect(isReactive(key)).toBe(true) expect(isReactive(value)).toBe(true) } wrapped.forEach((value: any) => { expect(isReadonly(value)).toBe(true) expect(isReactive(value)).toBe(true) }) for (const value of wrapped.values()) { expect(isReadonly(value)).toBe(true) expect(isReactive(value)).toBe(true) } }) } }) }) const sets = [Set, WeakSet] sets.forEach((Collection: any) => { describe(Collection.name, () => { test('should make nested values readonly', () => { const key1 = {} const key2 = {} const original = new Collection([key1, key2]) const wrapped = readonly(original) expect(wrapped).not.toBe(original) expect(isProxy(wrapped)).toBe(true) expect(isReactive(wrapped)).toBe(false) expect(isReadonly(wrapped)).toBe(true) expect(isReactive(original)).toBe(false) expect(isReadonly(original)).toBe(false) expect(wrapped.has(reactive(key1))).toBe(true) expect(original.has(reactive(key1))).toBe(false) }) test('should not allow mutation & not trigger effect', () => { const set = readonly(new Collection()) const key = {} let dummy effect(() => { dummy = set.has(key) }) expect(dummy).toBe(false) set.add(key) expect(dummy).toBe(false) expect(set.has(key)).toBe(false) expect( `Add operation on key "${key}" failed: target is readonly.` ).toHaveBeenWarned() }) if (Collection === Set) { test('should retrieve readonly values on iteration', () => { const original = new Collection([{}, {}]) const wrapped: any = readonly(original) expect(wrapped.size).toBe(2) for (const value of wrapped) { expect(isReadonly(value)).toBe(true) } wrapped.forEach((value: any) => { expect(isReadonly(value)).toBe(true) }) for (const value of wrapped.values()) { expect(isReadonly(value)).toBe(true) } for (const [v1, v2] of wrapped.entries()) { expect(isReadonly(v1)).toBe(true) expect(isReadonly(v2)).toBe(true) } }) } }) }) test('calling reactive on an readonly should return readonly', () => { const a = readonly({}) const b = reactive(a) expect(isReadonly(b)).toBe(true) // should point to same original expect(toRaw(a)).toBe(toRaw(b)) }) test('calling readonly on a reactive object should return readonly', () => { const a = reactive({}) const b = readonly(a) expect(isReadonly(b)).toBe(true) // should point to same original expect(toRaw(a)).toBe(toRaw(b)) }) test('readonly should track and trigger if wrapping reactive original', () => { const a = reactive({ n: 1 }) const b = readonly(a) // should return true since it's wrapping a reactive source expect(isReactive(b)).toBe(true) let dummy effect(() => { dummy = b.n }) expect(dummy).toBe(1) a.n++ expect(b.n).toBe(2) expect(dummy).toBe(2) }) test('readonly collection should not track', () => { const map = new Map() map.set('foo', 1) const reMap = reactive(map) const roMap = readonly(map) let dummy effect(() => { dummy = roMap.get('foo') }) expect(dummy).toBe(1) reMap.set('foo', 2) expect(roMap.get('foo')).toBe(2) // should not trigger expect(dummy).toBe(1) }) test('readonly array should not track', () => { const arr = [1] const roArr = readonly(arr) const eff = effect(() => { roArr.includes(2) }) expect(eff.effect.deps.length).toBe(0) }) test('readonly should track and trigger if wrapping reactive original (collection)', () => { const a = reactive(new Map()) const b = readonly(a) // should return true since it's wrapping a reactive source expect(isReactive(b)).toBe(true) a.set('foo', 1) let dummy effect(() => { dummy = b.get('foo') }) expect(dummy).toBe(1) a.set('foo', 2) expect(b.get('foo')).toBe(2) expect(dummy).toBe(2) }) test('wrapping already wrapped value should return same Proxy', () => { const original = { foo: 1 } const wrapped = readonly(original) const wrapped2 = readonly(wrapped) expect(wrapped2).toBe(wrapped) }) test('wrapping the same value multiple times should return same Proxy', () => { const original = { foo: 1 } const wrapped = readonly(original) const wrapped2 = readonly(original) expect(wrapped2).toBe(wrapped) }) test('markRaw', () => { const obj = readonly({ foo: { a: 1 }, bar: markRaw({ b: 2 }) }) expect(isReadonly(obj.foo)).toBe(true) expect(isReactive(obj.bar)).toBe(false) }) test('should make ref readonly', () => { const n = readonly(ref(1)) // @ts-expect-error n.value = 2 expect(n.value).toBe(1) expect( `Set operation on key "value" failed: target is readonly.` ).toHaveBeenWarned() }) // https://github.com/vuejs/core/issues/3376 test('calling readonly on computed should allow computed to set its private properties', () => { const r = ref<boolean>(false) const c = computed(() => r.value) const rC = readonly(c) r.value = true expect(rC.value).toBe(true) expect( 'Set operation on key "_dirty" failed: target is readonly.' ).not.toHaveBeenWarned() // @ts-expect-error - non-existent property rC.randomProperty = true expect( 'Set operation on key "randomProperty" failed: target is readonly.' ).toHaveBeenWarned() }) // #4986 test('setting a readonly object as a property of a reactive object should retain readonly proxy', () => { const r = readonly({}) const rr = reactive({}) as any rr.foo = r expect(rr.foo).toBe(r) expect(isReadonly(rr.foo)).toBe(true) }) test('attempting to write plain value to a readonly ref nested in a reactive object should fail', () => { const r = ref(false) const ror = readonly(r) const obj = reactive({ ror }) expect(() => { obj.ror = true }).toThrow() expect(obj.ror).toBe(false) }) test('replacing a readonly ref nested in a reactive object with a new ref', () => { const r = ref(false) const ror = readonly(r) const obj = reactive({ ror }) obj.ror = ref(true) as unknown as boolean expect(obj.ror).toBe(true) expect(toRaw(obj).ror).not.toBe(ror) // ref successfully replaced }) test('setting readonly object to writable nested ref', () => { const r = ref<any>() const obj = reactive({ r }) const ro = readonly({}) obj.r = ro expect(obj.r).toBe(ro) expect(r.value).toBe(ro) }) })
packages/reactivity/__tests__/readonly.spec.ts
1
https://github.com/vuejs/core/commit/657476dcdb964be4fbb1277c215c073f3275728e
[ 0.005908110644668341, 0.0005537517718039453, 0.00016352877719327807, 0.0001721590233501047, 0.001137352199293673 ]
{ "id": 3, "code_window": [ " `Set operation on key \"foo\" failed: target is readonly.`\n", " ).not.toHaveBeenWarned()\n", " })\n", " })\n", " })\n", "})" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\n", " test('should return undefined from Set.clear() call', () => {\n", " const sroSet = shallowReadonly(new Set())\n", " expect(sroSet.clear()).toBeUndefined()\n", " expect(`Clear operation failed: target is readonly.`).toHaveBeenWarned()\n", " })\n" ], "file_path": "packages/reactivity/__tests__/shallowReadonly.spec.ts", "type": "add", "edit_start_line_idx": 199 }
import { NodeTransform, TransformContext } from '../transform' import { NodeTypes, ElementTypes, CallExpression, ObjectExpression, ElementNode, DirectiveNode, ExpressionNode, ArrayExpression, createCallExpression, createArrayExpression, createObjectProperty, createSimpleExpression, createObjectExpression, Property, ComponentNode, VNodeCall, TemplateTextChildNode, DirectiveArguments, createVNodeCall, ConstantTypes } from '../ast' import { PatchFlags, PatchFlagNames, isSymbol, isOn, isObject, isReservedProp, capitalize, camelize, isBuiltInDirective } from '@vue/shared' import { createCompilerError, ErrorCodes } from '../errors' import { RESOLVE_DIRECTIVE, RESOLVE_COMPONENT, RESOLVE_DYNAMIC_COMPONENT, MERGE_PROPS, NORMALIZE_CLASS, NORMALIZE_STYLE, NORMALIZE_PROPS, TO_HANDLERS, TELEPORT, KEEP_ALIVE, SUSPENSE, UNREF, GUARD_REACTIVE_PROPS } from '../runtimeHelpers' import { getInnerRange, toValidAssetId, findProp, isCoreComponent, isStaticArgOf, findDir, isStaticExp } from '../utils' import { buildSlots } from './vSlot' import { getConstantType } from './hoistStatic' import { BindingTypes } from '../options' import { checkCompatEnabled, CompilerDeprecationTypes, isCompatEnabled } from '../compat/compatConfig' // some directive transforms (e.g. v-model) may return a symbol for runtime // import, which should be used instead of a resolveDirective call. const directiveImportMap = new WeakMap<DirectiveNode, symbol>() // generate a JavaScript AST for this element's codegen export const transformElement: NodeTransform = (node, context) => { // perform the work on exit, after all child expressions have been // processed and merged. return function postTransformElement() { node = context.currentNode! if ( !( node.type === NodeTypes.ELEMENT && (node.tagType === ElementTypes.ELEMENT || node.tagType === ElementTypes.COMPONENT) ) ) { return } const { tag, props } = node const isComponent = node.tagType === ElementTypes.COMPONENT // The goal of the transform is to create a codegenNode implementing the // VNodeCall interface. let vnodeTag = isComponent ? resolveComponentType(node as ComponentNode, context) : `"${tag}"` const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT let vnodeProps: VNodeCall['props'] let vnodeChildren: VNodeCall['children'] let vnodePatchFlag: VNodeCall['patchFlag'] let patchFlag: number = 0 let vnodeDynamicProps: VNodeCall['dynamicProps'] let dynamicPropNames: string[] | undefined let vnodeDirectives: VNodeCall['directives'] let shouldUseBlock = // dynamic component may resolve to plain elements isDynamicComponent || vnodeTag === TELEPORT || vnodeTag === SUSPENSE || (!isComponent && // <svg> and <foreignObject> must be forced into blocks so that block // updates inside get proper isSVG flag at runtime. (#639, #643) // This is technically web-specific, but splitting the logic out of core // leads to too much unnecessary complexity. (tag === 'svg' || tag === 'foreignObject')) // props if (props.length > 0) { const propsBuildResult = buildProps( node, context, undefined, isComponent, isDynamicComponent ) vnodeProps = propsBuildResult.props patchFlag = propsBuildResult.patchFlag dynamicPropNames = propsBuildResult.dynamicPropNames const directives = propsBuildResult.directives vnodeDirectives = directives && directives.length ? (createArrayExpression( directives.map(dir => buildDirectiveArgs(dir, context)) ) as DirectiveArguments) : undefined if (propsBuildResult.shouldUseBlock) { shouldUseBlock = true } } // children if (node.children.length > 0) { if (vnodeTag === KEEP_ALIVE) { // Although a built-in component, we compile KeepAlive with raw children // instead of slot functions so that it can be used inside Transition // or other Transition-wrapping HOCs. // To ensure correct updates with block optimizations, we need to: // 1. Force keep-alive into a block. This avoids its children being // collected by a parent block. shouldUseBlock = true // 2. Force keep-alive to always be updated, since it uses raw children. patchFlag |= PatchFlags.DYNAMIC_SLOTS if (__DEV__ && node.children.length > 1) { context.onError( createCompilerError(ErrorCodes.X_KEEP_ALIVE_INVALID_CHILDREN, { start: node.children[0].loc.start, end: node.children[node.children.length - 1].loc.end, source: '' }) ) } } const shouldBuildAsSlots = isComponent && // Teleport is not a real component and has dedicated runtime handling vnodeTag !== TELEPORT && // explained above. vnodeTag !== KEEP_ALIVE if (shouldBuildAsSlots) { const { slots, hasDynamicSlots } = buildSlots(node, context) vnodeChildren = slots if (hasDynamicSlots) { patchFlag |= PatchFlags.DYNAMIC_SLOTS } } else if (node.children.length === 1 && vnodeTag !== TELEPORT) { const child = node.children[0] const type = child.type // check for dynamic text children const hasDynamicTextChild = type === NodeTypes.INTERPOLATION || type === NodeTypes.COMPOUND_EXPRESSION if ( hasDynamicTextChild && getConstantType(child, context) === ConstantTypes.NOT_CONSTANT ) { patchFlag |= PatchFlags.TEXT } // pass directly if the only child is a text node // (plain / interpolation / expression) if (hasDynamicTextChild || type === NodeTypes.TEXT) { vnodeChildren = child as TemplateTextChildNode } else { vnodeChildren = node.children } } else { vnodeChildren = node.children } } // patchFlag & dynamicPropNames if (patchFlag !== 0) { if (__DEV__) { if (patchFlag < 0) { // special flags (negative and mutually exclusive) vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag as PatchFlags]} */` } else { // bitwise flags const flagNames = Object.keys(PatchFlagNames) .map(Number) .filter(n => n > 0 && patchFlag & n) .map(n => PatchFlagNames[n as PatchFlags]) .join(`, `) vnodePatchFlag = patchFlag + ` /* ${flagNames} */` } } else { vnodePatchFlag = String(patchFlag) } if (dynamicPropNames && dynamicPropNames.length) { vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames) } } node.codegenNode = createVNodeCall( context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, isComponent, node.loc ) } } export function resolveComponentType( node: ComponentNode, context: TransformContext, ssr = false ) { let { tag } = node // 1. dynamic component const isExplicitDynamic = isComponentTag(tag) const isProp = findProp(node, 'is') if (isProp) { if ( isExplicitDynamic || (__COMPAT__ && isCompatEnabled( CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT, context )) ) { const exp = isProp.type === NodeTypes.ATTRIBUTE ? isProp.value && createSimpleExpression(isProp.value.content, true) : isProp.exp if (exp) { return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [ exp ]) } } else if ( isProp.type === NodeTypes.ATTRIBUTE && isProp.value!.content.startsWith('vue:') ) { // <button is="vue:xxx"> // if not <component>, only is value that starts with "vue:" will be // treated as component by the parse phase and reach here, unless it's // compat mode where all is values are considered components tag = isProp.value!.content.slice(4) } } // 1.5 v-is (TODO: remove in 3.4) const isDir = !isExplicitDynamic && findDir(node, 'is') if (isDir && isDir.exp) { if (__DEV__) { context.onWarn( createCompilerError(ErrorCodes.DEPRECATION_V_IS, isDir.loc) ) } return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [ isDir.exp ]) } // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...) const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag) if (builtIn) { // built-ins are simply fallthroughs / have special handling during ssr // so we don't need to import their runtime equivalents if (!ssr) context.helper(builtIn) return builtIn } // 3. user component (from setup bindings) // this is skipped in browser build since browser builds do not perform // binding analysis. if (!__BROWSER__) { const fromSetup = resolveSetupReference(tag, context) if (fromSetup) { return fromSetup } const dotIndex = tag.indexOf('.') if (dotIndex > 0) { const ns = resolveSetupReference(tag.slice(0, dotIndex), context) if (ns) { return ns + tag.slice(dotIndex) } } } // 4. Self referencing component (inferred from filename) if ( !__BROWSER__ && context.selfName && capitalize(camelize(tag)) === context.selfName ) { context.helper(RESOLVE_COMPONENT) // codegen.ts has special check for __self postfix when generating // component imports, which will pass additional `maybeSelfReference` flag // to `resolveComponent`. context.components.add(tag + `__self`) return toValidAssetId(tag, `component`) } // 5. user component (resolve) context.helper(RESOLVE_COMPONENT) context.components.add(tag) return toValidAssetId(tag, `component`) } function resolveSetupReference(name: string, context: TransformContext) { const bindings = context.bindingMetadata if (!bindings || bindings.__isScriptSetup === false) { return } const camelName = camelize(name) const PascalName = capitalize(camelName) const checkType = (type: BindingTypes) => { if (bindings[name] === type) { return name } if (bindings[camelName] === type) { return camelName } if (bindings[PascalName] === type) { return PascalName } } const fromConst = checkType(BindingTypes.SETUP_CONST) || checkType(BindingTypes.SETUP_REACTIVE_CONST) || checkType(BindingTypes.LITERAL_CONST) if (fromConst) { return context.inline ? // in inline mode, const setup bindings (e.g. imports) can be used as-is fromConst : `$setup[${JSON.stringify(fromConst)}]` } const fromMaybeRef = checkType(BindingTypes.SETUP_LET) || checkType(BindingTypes.SETUP_REF) || checkType(BindingTypes.SETUP_MAYBE_REF) if (fromMaybeRef) { return context.inline ? // setup scope bindings that may be refs need to be unrefed `${context.helperString(UNREF)}(${fromMaybeRef})` : `$setup[${JSON.stringify(fromMaybeRef)}]` } } export type PropsExpression = ObjectExpression | CallExpression | ExpressionNode export function buildProps( node: ElementNode, context: TransformContext, props: ElementNode['props'] = node.props, isComponent: boolean, isDynamicComponent: boolean, ssr = false ): { props: PropsExpression | undefined directives: DirectiveNode[] patchFlag: number dynamicPropNames: string[] shouldUseBlock: boolean } { const { tag, loc: elementLoc, children } = node let properties: ObjectExpression['properties'] = [] const mergeArgs: PropsExpression[] = [] const runtimeDirectives: DirectiveNode[] = [] const hasChildren = children.length > 0 let shouldUseBlock = false // patchFlag analysis let patchFlag = 0 let hasRef = false let hasClassBinding = false let hasStyleBinding = false let hasHydrationEventBinding = false let hasDynamicKeys = false let hasVnodeHook = false const dynamicPropNames: string[] = [] const pushMergeArg = (arg?: PropsExpression) => { if (properties.length) { mergeArgs.push( createObjectExpression(dedupeProperties(properties), elementLoc) ) properties = [] } if (arg) mergeArgs.push(arg) } const analyzePatchFlag = ({ key, value }: Property) => { if (isStaticExp(key)) { const name = key.content const isEventHandler = isOn(name) if ( isEventHandler && (!isComponent || isDynamicComponent) && // omit the flag for click handlers because hydration gives click // dedicated fast path. name.toLowerCase() !== 'onclick' && // omit v-model handlers name !== 'onUpdate:modelValue' && // omit onVnodeXXX hooks !isReservedProp(name) ) { hasHydrationEventBinding = true } if (isEventHandler && isReservedProp(name)) { hasVnodeHook = true } if ( value.type === NodeTypes.JS_CACHE_EXPRESSION || ((value.type === NodeTypes.SIMPLE_EXPRESSION || value.type === NodeTypes.COMPOUND_EXPRESSION) && getConstantType(value, context) > 0) ) { // skip if the prop is a cached handler or has constant value return } if (name === 'ref') { hasRef = true } else if (name === 'class') { hasClassBinding = true } else if (name === 'style') { hasStyleBinding = true } else if (name !== 'key' && !dynamicPropNames.includes(name)) { dynamicPropNames.push(name) } // treat the dynamic class and style binding of the component as dynamic props if ( isComponent && (name === 'class' || name === 'style') && !dynamicPropNames.includes(name) ) { dynamicPropNames.push(name) } } else { hasDynamicKeys = true } } for (let i = 0; i < props.length; i++) { // static attribute const prop = props[i] if (prop.type === NodeTypes.ATTRIBUTE) { const { loc, name, value } = prop let isStatic = true if (name === 'ref') { hasRef = true if (context.scopes.vFor > 0) { properties.push( createObjectProperty( createSimpleExpression('ref_for', true), createSimpleExpression('true') ) ) } // in inline mode there is no setupState object, so we can't use string // keys to set the ref. Instead, we need to transform it to pass the // actual ref instead. if (!__BROWSER__ && value && context.inline) { const binding = context.bindingMetadata[value.content] if ( binding === BindingTypes.SETUP_LET || binding === BindingTypes.SETUP_REF || binding === BindingTypes.SETUP_MAYBE_REF ) { isStatic = false properties.push( createObjectProperty( createSimpleExpression('ref_key', true), createSimpleExpression(value.content, true, value.loc) ) ) } } } // skip is on <component>, or is="vue:xxx" if ( name === 'is' && (isComponentTag(tag) || (value && value.content.startsWith('vue:')) || (__COMPAT__ && isCompatEnabled( CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT, context ))) ) { continue } properties.push( createObjectProperty( createSimpleExpression( name, true, getInnerRange(loc, 0, name.length) ), createSimpleExpression( value ? value.content : '', isStatic, value ? value.loc : loc ) ) ) } else { // directives const { name, arg, exp, loc } = prop const isVBind = name === 'bind' const isVOn = name === 'on' // skip v-slot - it is handled by its dedicated transform. if (name === 'slot') { if (!isComponent) { context.onError( createCompilerError(ErrorCodes.X_V_SLOT_MISPLACED, loc) ) } continue } // skip v-once/v-memo - they are handled by dedicated transforms. if (name === 'once' || name === 'memo') { continue } // skip v-is and :is on <component> if ( name === 'is' || (isVBind && isStaticArgOf(arg, 'is') && (isComponentTag(tag) || (__COMPAT__ && isCompatEnabled( CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT, context )))) ) { continue } // skip v-on in SSR compilation if (isVOn && ssr) { continue } if ( // #938: elements with dynamic keys should be forced into blocks (isVBind && isStaticArgOf(arg, 'key')) || // inline before-update hooks need to force block so that it is invoked // before children (isVOn && hasChildren && isStaticArgOf(arg, 'vue:before-update')) ) { shouldUseBlock = true } if (isVBind && isStaticArgOf(arg, 'ref') && context.scopes.vFor > 0) { properties.push( createObjectProperty( createSimpleExpression('ref_for', true), createSimpleExpression('true') ) ) } // special case for v-bind and v-on with no argument if (!arg && (isVBind || isVOn)) { hasDynamicKeys = true if (exp) { if (isVBind) { // have to merge early for compat build check pushMergeArg() if (__COMPAT__) { // 2.x v-bind object order compat if (__DEV__) { const hasOverridableKeys = mergeArgs.some(arg => { if (arg.type === NodeTypes.JS_OBJECT_EXPRESSION) { return arg.properties.some(({ key }) => { if ( key.type !== NodeTypes.SIMPLE_EXPRESSION || !key.isStatic ) { return true } return ( key.content !== 'class' && key.content !== 'style' && !isOn(key.content) ) }) } else { // dynamic expression return true } }) if (hasOverridableKeys) { checkCompatEnabled( CompilerDeprecationTypes.COMPILER_V_BIND_OBJECT_ORDER, context, loc ) } } if ( isCompatEnabled( CompilerDeprecationTypes.COMPILER_V_BIND_OBJECT_ORDER, context ) ) { mergeArgs.unshift(exp) continue } } mergeArgs.push(exp) } else { // v-on="obj" -> toHandlers(obj) pushMergeArg({ type: NodeTypes.JS_CALL_EXPRESSION, loc, callee: context.helper(TO_HANDLERS), arguments: isComponent ? [exp] : [exp, `true`] }) } } else { context.onError( createCompilerError( isVBind ? ErrorCodes.X_V_BIND_NO_EXPRESSION : ErrorCodes.X_V_ON_NO_EXPRESSION, loc ) ) } continue } const directiveTransform = context.directiveTransforms[name] if (directiveTransform) { // has built-in directive transform. const { props, needRuntime } = directiveTransform(prop, node, context) !ssr && props.forEach(analyzePatchFlag) if (isVOn && arg && !isStaticExp(arg)) { pushMergeArg(createObjectExpression(props, elementLoc)) } else { properties.push(...props) } if (needRuntime) { runtimeDirectives.push(prop) if (isSymbol(needRuntime)) { directiveImportMap.set(prop, needRuntime) } } } else if (!isBuiltInDirective(name)) { // no built-in transform, this is a user custom directive. runtimeDirectives.push(prop) // custom dirs may use beforeUpdate so they need to force blocks // to ensure before-update gets called before children update if (hasChildren) { shouldUseBlock = true } } } } let propsExpression: PropsExpression | undefined = undefined // has v-bind="object" or v-on="object", wrap with mergeProps if (mergeArgs.length) { // close up any not-yet-merged props pushMergeArg() if (mergeArgs.length > 1) { propsExpression = createCallExpression( context.helper(MERGE_PROPS), mergeArgs, elementLoc ) } else { // single v-bind with nothing else - no need for a mergeProps call propsExpression = mergeArgs[0] } } else if (properties.length) { propsExpression = createObjectExpression( dedupeProperties(properties), elementLoc ) } // patchFlag analysis if (hasDynamicKeys) { patchFlag |= PatchFlags.FULL_PROPS } else { if (hasClassBinding && !isComponent) { patchFlag |= PatchFlags.CLASS } if (hasStyleBinding && !isComponent) { patchFlag |= PatchFlags.STYLE } if (dynamicPropNames.length) { patchFlag |= PatchFlags.PROPS } if (hasHydrationEventBinding) { patchFlag |= PatchFlags.HYDRATE_EVENTS } } if ( !shouldUseBlock && (patchFlag === 0 || patchFlag === PatchFlags.HYDRATE_EVENTS) && (hasRef || hasVnodeHook || runtimeDirectives.length > 0) ) { patchFlag |= PatchFlags.NEED_PATCH } // pre-normalize props, SSR is skipped for now if (!context.inSSR && propsExpression) { switch (propsExpression.type) { case NodeTypes.JS_OBJECT_EXPRESSION: // means that there is no v-bind, // but still need to deal with dynamic key binding let classKeyIndex = -1 let styleKeyIndex = -1 let hasDynamicKey = false for (let i = 0; i < propsExpression.properties.length; i++) { const key = propsExpression.properties[i].key if (isStaticExp(key)) { if (key.content === 'class') { classKeyIndex = i } else if (key.content === 'style') { styleKeyIndex = i } } else if (!key.isHandlerKey) { hasDynamicKey = true } } const classProp = propsExpression.properties[classKeyIndex] const styleProp = propsExpression.properties[styleKeyIndex] // no dynamic key if (!hasDynamicKey) { if (classProp && !isStaticExp(classProp.value)) { classProp.value = createCallExpression( context.helper(NORMALIZE_CLASS), [classProp.value] ) } if ( styleProp && // the static style is compiled into an object, // so use `hasStyleBinding` to ensure that it is a dynamic style binding (hasStyleBinding || (styleProp.value.type === NodeTypes.SIMPLE_EXPRESSION && styleProp.value.content.trim()[0] === `[`) || // v-bind:style and style both exist, // v-bind:style with static literal object styleProp.value.type === NodeTypes.JS_ARRAY_EXPRESSION) ) { styleProp.value = createCallExpression( context.helper(NORMALIZE_STYLE), [styleProp.value] ) } } else { // dynamic key binding, wrap with `normalizeProps` propsExpression = createCallExpression( context.helper(NORMALIZE_PROPS), [propsExpression] ) } break case NodeTypes.JS_CALL_EXPRESSION: // mergeProps call, do nothing break default: // single v-bind propsExpression = createCallExpression( context.helper(NORMALIZE_PROPS), [ createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [ propsExpression ]) ] ) break } } return { props: propsExpression, directives: runtimeDirectives, patchFlag, dynamicPropNames, shouldUseBlock } } // Dedupe props in an object literal. // Literal duplicated attributes would have been warned during the parse phase, // however, it's possible to encounter duplicated `onXXX` handlers with different // modifiers. We also need to merge static and dynamic class / style attributes. // - onXXX handlers / style: merge into array // - class: merge into single expression with concatenation function dedupeProperties(properties: Property[]): Property[] { const knownProps: Map<string, Property> = new Map() const deduped: Property[] = [] for (let i = 0; i < properties.length; i++) { const prop = properties[i] // dynamic keys are always allowed if (prop.key.type === NodeTypes.COMPOUND_EXPRESSION || !prop.key.isStatic) { deduped.push(prop) continue } const name = prop.key.content const existing = knownProps.get(name) if (existing) { if (name === 'style' || name === 'class' || isOn(name)) { mergeAsArray(existing, prop) } // unexpected duplicate, should have emitted error during parse } else { knownProps.set(name, prop) deduped.push(prop) } } return deduped } function mergeAsArray(existing: Property, incoming: Property) { if (existing.value.type === NodeTypes.JS_ARRAY_EXPRESSION) { existing.value.elements.push(incoming.value) } else { existing.value = createArrayExpression( [existing.value, incoming.value], existing.loc ) } } export function buildDirectiveArgs( dir: DirectiveNode, context: TransformContext ): ArrayExpression { const dirArgs: ArrayExpression['elements'] = [] const runtime = directiveImportMap.get(dir) if (runtime) { // built-in directive with runtime dirArgs.push(context.helperString(runtime)) } else { // user directive. // see if we have directives exposed via <script setup> const fromSetup = !__BROWSER__ && resolveSetupReference('v-' + dir.name, context) if (fromSetup) { dirArgs.push(fromSetup) } else { // inject statement for resolving directive context.helper(RESOLVE_DIRECTIVE) context.directives.add(dir.name) dirArgs.push(toValidAssetId(dir.name, `directive`)) } } const { loc } = dir if (dir.exp) dirArgs.push(dir.exp) if (dir.arg) { if (!dir.exp) { dirArgs.push(`void 0`) } dirArgs.push(dir.arg) } if (Object.keys(dir.modifiers).length) { if (!dir.arg) { if (!dir.exp) { dirArgs.push(`void 0`) } dirArgs.push(`void 0`) } const trueExpression = createSimpleExpression(`true`, false, loc) dirArgs.push( createObjectExpression( dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression) ), loc ) ) } return createArrayExpression(dirArgs, dir.loc) } function stringifyDynamicPropNames(props: string[]): string { let propsNamesString = `[` for (let i = 0, l = props.length; i < l; i++) { propsNamesString += JSON.stringify(props[i]) if (i < l - 1) propsNamesString += ', ' } return propsNamesString + `]` } function isComponentTag(tag: string) { return tag === 'component' || tag === 'Component' }
packages/compiler-core/src/transforms/transformElement.ts
0
https://github.com/vuejs/core/commit/657476dcdb964be4fbb1277c215c073f3275728e
[ 0.0003027066122740507, 0.00017143654986284673, 0.00016363937174901366, 0.00017015982302837074, 0.000013763057722826488 ]
{ "id": 3, "code_window": [ " `Set operation on key \"foo\" failed: target is readonly.`\n", " ).not.toHaveBeenWarned()\n", " })\n", " })\n", " })\n", "})" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\n", " test('should return undefined from Set.clear() call', () => {\n", " const sroSet = shallowReadonly(new Set())\n", " expect(sroSet.clear()).toBeUndefined()\n", " expect(`Clear operation failed: target is readonly.`).toHaveBeenWarned()\n", " })\n" ], "file_path": "packages/reactivity/__tests__/shallowReadonly.spec.ts", "type": "add", "edit_start_line_idx": 199 }
import { isArray, isObject, isPromise } from '@vue/shared' import { defineAsyncComponent } from '../apiAsyncComponent' import { Component } from '../component' import { isVNode } from '../vnode' interface LegacyAsyncOptions { component: Promise<Component> loading?: Component error?: Component delay?: number timeout?: number } type LegacyAsyncReturnValue = Promise<Component> | LegacyAsyncOptions type LegacyAsyncComponent = ( resolve?: (res: LegacyAsyncReturnValue) => void, reject?: (reason?: any) => void ) => LegacyAsyncReturnValue | undefined const normalizedAsyncComponentMap = new WeakMap< LegacyAsyncComponent, Component >() export function convertLegacyAsyncComponent(comp: LegacyAsyncComponent) { if (normalizedAsyncComponentMap.has(comp)) { return normalizedAsyncComponentMap.get(comp)! } // we have to call the function here due to how v2's API won't expose the // options until we call it let resolve: (res: LegacyAsyncReturnValue) => void let reject: (reason?: any) => void const fallbackPromise = new Promise<Component>((r, rj) => { ;(resolve = r), (reject = rj) }) const res = comp(resolve!, reject!) let converted: Component if (isPromise(res)) { converted = defineAsyncComponent(() => res) } else if (isObject(res) && !isVNode(res) && !isArray(res)) { converted = defineAsyncComponent({ loader: () => res.component, loadingComponent: res.loading, errorComponent: res.error, delay: res.delay, timeout: res.timeout }) } else if (res == null) { converted = defineAsyncComponent(() => fallbackPromise) } else { converted = comp as any // probably a v3 functional comp } normalizedAsyncComponentMap.set(comp, converted) return converted }
packages/runtime-core/src/compat/componentAsync.ts
0
https://github.com/vuejs/core/commit/657476dcdb964be4fbb1277c215c073f3275728e
[ 0.00017234808183275163, 0.0001685512252151966, 0.00016535718168597668, 0.00016866190708242357, 0.0000024768494313320844 ]
{ "id": 3, "code_window": [ " `Set operation on key \"foo\" failed: target is readonly.`\n", " ).not.toHaveBeenWarned()\n", " })\n", " })\n", " })\n", "})" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\n", " test('should return undefined from Set.clear() call', () => {\n", " const sroSet = shallowReadonly(new Set())\n", " expect(sroSet.clear()).toBeUndefined()\n", " expect(`Clear operation failed: target is readonly.`).toHaveBeenWarned()\n", " })\n" ], "file_path": "packages/reactivity/__tests__/shallowReadonly.spec.ts", "type": "add", "edit_start_line_idx": 199 }
import { compile } from '../src' describe('ssr: attrs fallthrough', () => { test('basic', () => { expect(compile(`<div/>`).code).toMatchInlineSnapshot(` "const { ssrRenderAttrs: _ssrRenderAttrs } = require(\\"vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { _push(\`<div\${_ssrRenderAttrs(_attrs)}></div>\`) }" `) }) test('with comments', () => { expect(compile(`<!--!--><div/>`).code).toMatchInlineSnapshot(` "const { ssrRenderAttrs: _ssrRenderAttrs } = require(\\"vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { _push(\`<!--[--><!--!--><div\${_ssrRenderAttrs(_attrs)}></div><!--]-->\`) }" `) }) // #5140 test('should not inject to non-single-root if branches', () => { expect(compile(`<div v-if="true"/><div/>`).code).toMatchInlineSnapshot(` " return function ssrRender(_ctx, _push, _parent, _attrs) { _push(\`<!--[-->\`) if (true) { _push(\`<div></div>\`) } else { _push(\`<!---->\`) } _push(\`<div></div><!--]-->\`) }" `) }) test('fallthrough component content (root with comments)', () => { expect(compile(`<!--root--><transition><div/></transition>`).code) .toMatchInlineSnapshot(` "const { ssrRenderAttrs: _ssrRenderAttrs } = require(\\"vue/server-renderer\\") return function ssrRender(_ctx, _push, _parent, _attrs) { _push(\`<!--[--><!--root--><div\${_ssrRenderAttrs(_attrs)}></div><!--]-->\`) }" `) }) test('should not inject to fallthrough component content if not root', () => { expect(compile(`<div/><transition><div/></transition>`).code) .toMatchInlineSnapshot(` " return function ssrRender(_ctx, _push, _parent, _attrs) { _push(\`<!--[--><div></div><div></div><!--]-->\`) }" `) }) })
packages/compiler-ssr/__tests__/ssrFallthroughAttrs.spec.ts
0
https://github.com/vuejs/core/commit/657476dcdb964be4fbb1277c215c073f3275728e
[ 0.00018662572256289423, 0.0001719713764032349, 0.0001665930321905762, 0.000168315862538293, 0.000006749490694346605 ]
{ "id": 4, "code_window": [ " console.warn(\n", " `${capitalize(type)} operation ${key}failed: target is readonly.`,\n", " toRaw(this)\n", " )\n", " }\n", " return type === TriggerOpTypes.DELETE ? false : this\n", " }\n", "}\n", "\n", "function createInstrumentations() {\n", " const mutableInstrumentations: Record<string, Function | number> = {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return type === TriggerOpTypes.DELETE\n", " ? false\n", " : type === TriggerOpTypes.CLEAR\n", " ? undefined\n", " : this\n" ], "file_path": "packages/reactivity/src/collectionHandlers.ts", "type": "replace", "edit_start_line_idx": 225 }
import { reactive, readonly, toRaw, isReactive, isReadonly, markRaw, effect, ref, isProxy, computed } from '../src' /** * @see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html */ type Writable<T> = { -readonly [P in keyof T]: T[P] } describe('reactivity/readonly', () => { describe('Object', () => { it('should make nested values readonly', () => { const original = { foo: 1, bar: { baz: 2 } } const wrapped = readonly(original) expect(wrapped).not.toBe(original) expect(isProxy(wrapped)).toBe(true) expect(isReactive(wrapped)).toBe(false) expect(isReadonly(wrapped)).toBe(true) expect(isReactive(original)).toBe(false) expect(isReadonly(original)).toBe(false) expect(isReactive(wrapped.bar)).toBe(false) expect(isReadonly(wrapped.bar)).toBe(true) expect(isReactive(original.bar)).toBe(false) expect(isReadonly(original.bar)).toBe(false) // get expect(wrapped.foo).toBe(1) // has expect('foo' in wrapped).toBe(true) // ownKeys expect(Object.keys(wrapped)).toEqual(['foo', 'bar']) }) it('should not allow mutation', () => { const qux = Symbol('qux') const original = { foo: 1, bar: { baz: 2 }, [qux]: 3 } const wrapped: Writable<typeof original> = readonly(original) wrapped.foo = 2 expect(wrapped.foo).toBe(1) expect( `Set operation on key "foo" failed: target is readonly.` ).toHaveBeenWarnedLast() wrapped.bar.baz = 3 expect(wrapped.bar.baz).toBe(2) expect( `Set operation on key "baz" failed: target is readonly.` ).toHaveBeenWarnedLast() wrapped[qux] = 4 expect(wrapped[qux]).toBe(3) expect( `Set operation on key "Symbol(qux)" failed: target is readonly.` ).toHaveBeenWarnedLast() // @ts-expect-error delete wrapped.foo expect(wrapped.foo).toBe(1) expect( `Delete operation on key "foo" failed: target is readonly.` ).toHaveBeenWarnedLast() // @ts-expect-error delete wrapped.bar.baz expect(wrapped.bar.baz).toBe(2) expect( `Delete operation on key "baz" failed: target is readonly.` ).toHaveBeenWarnedLast() // @ts-expect-error delete wrapped[qux] expect(wrapped[qux]).toBe(3) expect( `Delete operation on key "Symbol(qux)" failed: target is readonly.` ).toHaveBeenWarnedLast() }) it('should not trigger effects', () => { const wrapped: any = readonly({ a: 1 }) let dummy effect(() => { dummy = wrapped.a }) expect(dummy).toBe(1) wrapped.a = 2 expect(wrapped.a).toBe(1) expect(dummy).toBe(1) expect(`target is readonly`).toHaveBeenWarned() }) }) describe('Array', () => { it('should make nested values readonly', () => { const original = [{ foo: 1 }] const wrapped = readonly(original) expect(wrapped).not.toBe(original) expect(isProxy(wrapped)).toBe(true) expect(isReactive(wrapped)).toBe(false) expect(isReadonly(wrapped)).toBe(true) expect(isReactive(original)).toBe(false) expect(isReadonly(original)).toBe(false) expect(isReactive(wrapped[0])).toBe(false) expect(isReadonly(wrapped[0])).toBe(true) expect(isReactive(original[0])).toBe(false) expect(isReadonly(original[0])).toBe(false) // get expect(wrapped[0].foo).toBe(1) // has expect(0 in wrapped).toBe(true) // ownKeys expect(Object.keys(wrapped)).toEqual(['0']) }) it('should not allow mutation', () => { const wrapped: any = readonly([{ foo: 1 }]) wrapped[0] = 1 expect(wrapped[0]).not.toBe(1) expect( `Set operation on key "0" failed: target is readonly.` ).toHaveBeenWarned() wrapped[0].foo = 2 expect(wrapped[0].foo).toBe(1) expect( `Set operation on key "foo" failed: target is readonly.` ).toHaveBeenWarned() // should block length mutation wrapped.length = 0 expect(wrapped.length).toBe(1) expect(wrapped[0].foo).toBe(1) expect( `Set operation on key "length" failed: target is readonly.` ).toHaveBeenWarned() // mutation methods invoke set/length internally and thus are blocked as well wrapped.push(2) expect(wrapped.length).toBe(1) // push triggers two warnings on [1] and .length expect(`target is readonly.`).toHaveBeenWarnedTimes(5) }) it('should not trigger effects', () => { const wrapped: any = readonly([{ a: 1 }]) let dummy effect(() => { dummy = wrapped[0].a }) expect(dummy).toBe(1) wrapped[0].a = 2 expect(wrapped[0].a).toBe(1) expect(dummy).toBe(1) expect(`target is readonly`).toHaveBeenWarnedTimes(1) wrapped[0] = { a: 2 } expect(wrapped[0].a).toBe(1) expect(dummy).toBe(1) expect(`target is readonly`).toHaveBeenWarnedTimes(2) }) }) const maps = [Map, WeakMap] maps.forEach((Collection: any) => { describe(Collection.name, () => { test('should make nested values readonly', () => { const key1 = {} const key2 = {} const original = new Collection([ [key1, {}], [key2, {}] ]) const wrapped = readonly(original) expect(wrapped).not.toBe(original) expect(isProxy(wrapped)).toBe(true) expect(isReactive(wrapped)).toBe(false) expect(isReadonly(wrapped)).toBe(true) expect(isReactive(original)).toBe(false) expect(isReadonly(original)).toBe(false) expect(isReactive(wrapped.get(key1))).toBe(false) expect(isReadonly(wrapped.get(key1))).toBe(true) expect(isReactive(original.get(key1))).toBe(false) expect(isReadonly(original.get(key1))).toBe(false) }) test('should not allow mutation & not trigger effect', () => { const map = readonly(new Collection()) const key = {} let dummy effect(() => { dummy = map.get(key) }) expect(dummy).toBeUndefined() map.set(key, 1) expect(dummy).toBeUndefined() expect(map.has(key)).toBe(false) expect( `Set operation on key "${key}" failed: target is readonly.` ).toHaveBeenWarned() }) // #1772 test('readonly + reactive should make get() value also readonly + reactive', () => { const map = reactive(new Collection()) const roMap = readonly(map) const key = {} map.set(key, {}) const item = map.get(key) expect(isReactive(item)).toBe(true) expect(isReadonly(item)).toBe(false) const roItem = roMap.get(key) expect(isReactive(roItem)).toBe(true) expect(isReadonly(roItem)).toBe(true) }) if (Collection === Map) { test('should retrieve readonly values on iteration', () => { const key1 = {} const key2 = {} const original = new Map([ [key1, {}], [key2, {}] ]) const wrapped: any = readonly(original) expect(wrapped.size).toBe(2) for (const [key, value] of wrapped) { expect(isReadonly(key)).toBe(true) expect(isReadonly(value)).toBe(true) } wrapped.forEach((value: any) => { expect(isReadonly(value)).toBe(true) }) for (const value of wrapped.values()) { expect(isReadonly(value)).toBe(true) } }) test('should retrieve reactive + readonly values on iteration', () => { const key1 = {} const key2 = {} const original = reactive( new Map([ [key1, {}], [key2, {}] ]) ) const wrapped: any = readonly(original) expect(wrapped.size).toBe(2) for (const [key, value] of wrapped) { expect(isReadonly(key)).toBe(true) expect(isReadonly(value)).toBe(true) expect(isReactive(key)).toBe(true) expect(isReactive(value)).toBe(true) } wrapped.forEach((value: any) => { expect(isReadonly(value)).toBe(true) expect(isReactive(value)).toBe(true) }) for (const value of wrapped.values()) { expect(isReadonly(value)).toBe(true) expect(isReactive(value)).toBe(true) } }) } }) }) const sets = [Set, WeakSet] sets.forEach((Collection: any) => { describe(Collection.name, () => { test('should make nested values readonly', () => { const key1 = {} const key2 = {} const original = new Collection([key1, key2]) const wrapped = readonly(original) expect(wrapped).not.toBe(original) expect(isProxy(wrapped)).toBe(true) expect(isReactive(wrapped)).toBe(false) expect(isReadonly(wrapped)).toBe(true) expect(isReactive(original)).toBe(false) expect(isReadonly(original)).toBe(false) expect(wrapped.has(reactive(key1))).toBe(true) expect(original.has(reactive(key1))).toBe(false) }) test('should not allow mutation & not trigger effect', () => { const set = readonly(new Collection()) const key = {} let dummy effect(() => { dummy = set.has(key) }) expect(dummy).toBe(false) set.add(key) expect(dummy).toBe(false) expect(set.has(key)).toBe(false) expect( `Add operation on key "${key}" failed: target is readonly.` ).toHaveBeenWarned() }) if (Collection === Set) { test('should retrieve readonly values on iteration', () => { const original = new Collection([{}, {}]) const wrapped: any = readonly(original) expect(wrapped.size).toBe(2) for (const value of wrapped) { expect(isReadonly(value)).toBe(true) } wrapped.forEach((value: any) => { expect(isReadonly(value)).toBe(true) }) for (const value of wrapped.values()) { expect(isReadonly(value)).toBe(true) } for (const [v1, v2] of wrapped.entries()) { expect(isReadonly(v1)).toBe(true) expect(isReadonly(v2)).toBe(true) } }) } }) }) test('calling reactive on an readonly should return readonly', () => { const a = readonly({}) const b = reactive(a) expect(isReadonly(b)).toBe(true) // should point to same original expect(toRaw(a)).toBe(toRaw(b)) }) test('calling readonly on a reactive object should return readonly', () => { const a = reactive({}) const b = readonly(a) expect(isReadonly(b)).toBe(true) // should point to same original expect(toRaw(a)).toBe(toRaw(b)) }) test('readonly should track and trigger if wrapping reactive original', () => { const a = reactive({ n: 1 }) const b = readonly(a) // should return true since it's wrapping a reactive source expect(isReactive(b)).toBe(true) let dummy effect(() => { dummy = b.n }) expect(dummy).toBe(1) a.n++ expect(b.n).toBe(2) expect(dummy).toBe(2) }) test('readonly collection should not track', () => { const map = new Map() map.set('foo', 1) const reMap = reactive(map) const roMap = readonly(map) let dummy effect(() => { dummy = roMap.get('foo') }) expect(dummy).toBe(1) reMap.set('foo', 2) expect(roMap.get('foo')).toBe(2) // should not trigger expect(dummy).toBe(1) }) test('readonly array should not track', () => { const arr = [1] const roArr = readonly(arr) const eff = effect(() => { roArr.includes(2) }) expect(eff.effect.deps.length).toBe(0) }) test('readonly should track and trigger if wrapping reactive original (collection)', () => { const a = reactive(new Map()) const b = readonly(a) // should return true since it's wrapping a reactive source expect(isReactive(b)).toBe(true) a.set('foo', 1) let dummy effect(() => { dummy = b.get('foo') }) expect(dummy).toBe(1) a.set('foo', 2) expect(b.get('foo')).toBe(2) expect(dummy).toBe(2) }) test('wrapping already wrapped value should return same Proxy', () => { const original = { foo: 1 } const wrapped = readonly(original) const wrapped2 = readonly(wrapped) expect(wrapped2).toBe(wrapped) }) test('wrapping the same value multiple times should return same Proxy', () => { const original = { foo: 1 } const wrapped = readonly(original) const wrapped2 = readonly(original) expect(wrapped2).toBe(wrapped) }) test('markRaw', () => { const obj = readonly({ foo: { a: 1 }, bar: markRaw({ b: 2 }) }) expect(isReadonly(obj.foo)).toBe(true) expect(isReactive(obj.bar)).toBe(false) }) test('should make ref readonly', () => { const n = readonly(ref(1)) // @ts-expect-error n.value = 2 expect(n.value).toBe(1) expect( `Set operation on key "value" failed: target is readonly.` ).toHaveBeenWarned() }) // https://github.com/vuejs/core/issues/3376 test('calling readonly on computed should allow computed to set its private properties', () => { const r = ref<boolean>(false) const c = computed(() => r.value) const rC = readonly(c) r.value = true expect(rC.value).toBe(true) expect( 'Set operation on key "_dirty" failed: target is readonly.' ).not.toHaveBeenWarned() // @ts-expect-error - non-existent property rC.randomProperty = true expect( 'Set operation on key "randomProperty" failed: target is readonly.' ).toHaveBeenWarned() }) // #4986 test('setting a readonly object as a property of a reactive object should retain readonly proxy', () => { const r = readonly({}) const rr = reactive({}) as any rr.foo = r expect(rr.foo).toBe(r) expect(isReadonly(rr.foo)).toBe(true) }) test('attempting to write plain value to a readonly ref nested in a reactive object should fail', () => { const r = ref(false) const ror = readonly(r) const obj = reactive({ ror }) expect(() => { obj.ror = true }).toThrow() expect(obj.ror).toBe(false) }) test('replacing a readonly ref nested in a reactive object with a new ref', () => { const r = ref(false) const ror = readonly(r) const obj = reactive({ ror }) obj.ror = ref(true) as unknown as boolean expect(obj.ror).toBe(true) expect(toRaw(obj).ror).not.toBe(ror) // ref successfully replaced }) test('setting readonly object to writable nested ref', () => { const r = ref<any>() const obj = reactive({ r }) const ro = readonly({}) obj.r = ro expect(obj.r).toBe(ro) expect(r.value).toBe(ro) }) })
packages/reactivity/__tests__/readonly.spec.ts
1
https://github.com/vuejs/core/commit/657476dcdb964be4fbb1277c215c073f3275728e
[ 0.0022183118853718042, 0.00022582660312764347, 0.00016426719957962632, 0.0001720914151519537, 0.000285536254523322 ]
{ "id": 4, "code_window": [ " console.warn(\n", " `${capitalize(type)} operation ${key}failed: target is readonly.`,\n", " toRaw(this)\n", " )\n", " }\n", " return type === TriggerOpTypes.DELETE ? false : this\n", " }\n", "}\n", "\n", "function createInstrumentations() {\n", " const mutableInstrumentations: Record<string, Function | number> = {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return type === TriggerOpTypes.DELETE\n", " ? false\n", " : type === TriggerOpTypes.CLEAR\n", " ? undefined\n", " : this\n" ], "file_path": "packages/reactivity/src/collectionHandlers.ts", "type": "replace", "edit_start_line_idx": 225 }
{ "name": "@vue/compiler-dom", "version": "3.3.8", "description": "@vue/compiler-dom", "main": "index.js", "module": "dist/compiler-dom.esm-bundler.js", "types": "dist/compiler-dom.d.ts", "unpkg": "dist/compiler-dom.global.js", "jsdelivr": "dist/compiler-dom.global.js", "files": [ "index.js", "dist" ], "sideEffects": false, "buildOptions": { "name": "VueCompilerDOM", "compat": true, "formats": [ "esm-bundler", "esm-browser", "cjs", "global" ] }, "repository": { "type": "git", "url": "git+https://github.com/vuejs/core.git", "directory": "packages/compiler-dom" }, "keywords": [ "vue" ], "author": "Evan You", "license": "MIT", "bugs": { "url": "https://github.com/vuejs/core/issues" }, "homepage": "https://github.com/vuejs/core/tree/main/packages/compiler-dom#readme", "dependencies": { "@vue/shared": "3.3.8", "@vue/compiler-core": "3.3.8" } }
packages/compiler-dom/package.json
0
https://github.com/vuejs/core/commit/657476dcdb964be4fbb1277c215c073f3275728e
[ 0.00017857957573141903, 0.00017580404528416693, 0.00017273817502427846, 0.00017602262960281223, 0.000002071632707156823 ]
{ "id": 4, "code_window": [ " console.warn(\n", " `${capitalize(type)} operation ${key}failed: target is readonly.`,\n", " toRaw(this)\n", " )\n", " }\n", " return type === TriggerOpTypes.DELETE ? false : this\n", " }\n", "}\n", "\n", "function createInstrumentations() {\n", " const mutableInstrumentations: Record<string, Function | number> = {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return type === TriggerOpTypes.DELETE\n", " ? false\n", " : type === TriggerOpTypes.CLEAR\n", " ? undefined\n", " : this\n" ], "file_path": "packages/reactivity/src/collectionHandlers.ts", "type": "replace", "edit_start_line_idx": 225 }
import { isArray, isFunction, isString, isObject, EMPTY_ARR, extend, normalizeClass, normalizeStyle, PatchFlags, ShapeFlags, SlotFlags, isOn } from '@vue/shared' import { ComponentInternalInstance, Data, ConcreteComponent, ClassComponent, Component, isClassComponent } from './component' import { RawSlots } from './componentSlots' import { isProxy, Ref, toRaw, ReactiveFlags, isRef } from '@vue/reactivity' import { AppContext } from './apiCreateApp' import { Suspense, SuspenseImpl, isSuspense, SuspenseBoundary } from './components/Suspense' import { DirectiveBinding } from './directives' import { TransitionHooks } from './components/BaseTransition' import { warn } from './warning' import { Teleport, TeleportImpl, isTeleport } from './components/Teleport' import { currentRenderingInstance, currentScopeId } from './componentRenderContext' import { RendererNode, RendererElement } from './renderer' import { NULL_DYNAMIC_COMPONENT } from './helpers/resolveAssets' import { hmrDirtyComponents } from './hmr' import { convertLegacyComponent } from './compat/component' import { convertLegacyVModelProps } from './compat/componentVModel' import { defineLegacyVNodeProperties } from './compat/renderFn' import { callWithAsyncErrorHandling, ErrorCodes } from './errorHandling' import { ComponentPublicInstance } from './componentPublicInstance' export const Fragment = Symbol.for('v-fgt') as any as { __isFragment: true new (): { $props: VNodeProps } } export const Text = Symbol.for('v-txt') export const Comment = Symbol.for('v-cmt') export const Static = Symbol.for('v-stc') export type VNodeTypes = | string | VNode | Component | typeof Text | typeof Static | typeof Comment | typeof Fragment | typeof Teleport | typeof TeleportImpl | typeof Suspense | typeof SuspenseImpl export type VNodeRef = | string | Ref | (( ref: Element | ComponentPublicInstance | null, refs: Record<string, any> ) => void) export type VNodeNormalizedRefAtom = { i: ComponentInternalInstance r: VNodeRef k?: string // setup ref key f?: boolean // refInFor marker } export type VNodeNormalizedRef = | VNodeNormalizedRefAtom | VNodeNormalizedRefAtom[] type VNodeMountHook = (vnode: VNode) => void type VNodeUpdateHook = (vnode: VNode, oldVNode: VNode) => void export type VNodeHook = | VNodeMountHook | VNodeUpdateHook | VNodeMountHook[] | VNodeUpdateHook[] // https://github.com/microsoft/TypeScript/issues/33099 export type VNodeProps = { key?: string | number | symbol ref?: VNodeRef ref_for?: boolean ref_key?: string // vnode hooks onVnodeBeforeMount?: VNodeMountHook | VNodeMountHook[] onVnodeMounted?: VNodeMountHook | VNodeMountHook[] onVnodeBeforeUpdate?: VNodeUpdateHook | VNodeUpdateHook[] onVnodeUpdated?: VNodeUpdateHook | VNodeUpdateHook[] onVnodeBeforeUnmount?: VNodeMountHook | VNodeMountHook[] onVnodeUnmounted?: VNodeMountHook | VNodeMountHook[] } type VNodeChildAtom = | VNode | typeof NULL_DYNAMIC_COMPONENT | string | number | boolean | null | undefined | void export type VNodeArrayChildren = Array<VNodeArrayChildren | VNodeChildAtom> export type VNodeChild = VNodeChildAtom | VNodeArrayChildren export type VNodeNormalizedChildren = | string | VNodeArrayChildren | RawSlots | null export interface VNode< HostNode = RendererNode, HostElement = RendererElement, ExtraProps = { [key: string]: any } > { /** * @internal */ __v_isVNode: true /** * @internal */ [ReactiveFlags.SKIP]: true type: VNodeTypes props: (VNodeProps & ExtraProps) | null key: string | number | symbol | null ref: VNodeNormalizedRef | null /** * SFC only. This is assigned on vnode creation using currentScopeId * which is set alongside currentRenderingInstance. */ scopeId: string | null /** * SFC only. This is assigned to: * - Slot fragment vnodes with :slotted SFC styles. * - Component vnodes (during patch/hydration) so that its root node can * inherit the component's slotScopeIds * @internal */ slotScopeIds: string[] | null children: VNodeNormalizedChildren component: ComponentInternalInstance | null dirs: DirectiveBinding[] | null transition: TransitionHooks<HostElement> | null // DOM el: HostNode | null anchor: HostNode | null // fragment anchor target: HostElement | null // teleport target targetAnchor: HostNode | null // teleport target anchor /** * number of elements contained in a static vnode * @internal */ staticCount: number // suspense suspense: SuspenseBoundary | null /** * @internal */ ssContent: VNode | null /** * @internal */ ssFallback: VNode | null // optimization only shapeFlag: number patchFlag: number /** * @internal */ dynamicProps: string[] | null /** * @internal */ dynamicChildren: VNode[] | null // application root node only appContext: AppContext | null /** * @internal lexical scope owner instance */ ctx: ComponentInternalInstance | null /** * @internal attached by v-memo */ memo?: any[] /** * @internal __COMPAT__ only */ isCompatRoot?: true /** * @internal custom element interception hook */ ce?: (instance: ComponentInternalInstance) => void } // Since v-if and v-for are the two possible ways node structure can dynamically // change, once we consider v-if branches and each v-for fragment a block, we // can divide a template into nested blocks, and within each block the node // structure would be stable. This allows us to skip most children diffing // and only worry about the dynamic nodes (indicated by patch flags). export const blockStack: (VNode[] | null)[] = [] export let currentBlock: VNode[] | null = null /** * Open a block. * This must be called before `createBlock`. It cannot be part of `createBlock` * because the children of the block are evaluated before `createBlock` itself * is called. The generated code typically looks like this: * * ```js * function render() { * return (openBlock(),createBlock('div', null, [...])) * } * ``` * disableTracking is true when creating a v-for fragment block, since a v-for * fragment always diffs its children. * * @private */ export function openBlock(disableTracking = false) { blockStack.push((currentBlock = disableTracking ? null : [])) } export function closeBlock() { blockStack.pop() currentBlock = blockStack[blockStack.length - 1] || null } // Whether we should be tracking dynamic child nodes inside a block. // Only tracks when this value is > 0 // We are not using a simple boolean because this value may need to be // incremented/decremented by nested usage of v-once (see below) export let isBlockTreeEnabled = 1 /** * Block tracking sometimes needs to be disabled, for example during the * creation of a tree that needs to be cached by v-once. The compiler generates * code like this: * * ``` js * _cache[1] || ( * setBlockTracking(-1), * _cache[1] = createVNode(...), * setBlockTracking(1), * _cache[1] * ) * ``` * * @private */ export function setBlockTracking(value: number) { isBlockTreeEnabled += value } function setupBlock(vnode: VNode) { // save current block children on the block vnode vnode.dynamicChildren = isBlockTreeEnabled > 0 ? currentBlock || (EMPTY_ARR as any) : null // close block closeBlock() // a block is always going to be patched, so track it as a child of its // parent block if (isBlockTreeEnabled > 0 && currentBlock) { currentBlock.push(vnode) } return vnode } /** * @private */ export function createElementBlock( type: string | typeof Fragment, props?: Record<string, any> | null, children?: any, patchFlag?: number, dynamicProps?: string[], shapeFlag?: number ) { return setupBlock( createBaseVNode( type, props, children, patchFlag, dynamicProps, shapeFlag, true /* isBlock */ ) ) } /** * Create a block root vnode. Takes the same exact arguments as `createVNode`. * A block root keeps track of dynamic nodes within the block in the * `dynamicChildren` array. * * @private */ export function createBlock( type: VNodeTypes | ClassComponent, props?: Record<string, any> | null, children?: any, patchFlag?: number, dynamicProps?: string[] ): VNode { return setupBlock( createVNode( type, props, children, patchFlag, dynamicProps, true /* isBlock: prevent a block from tracking itself */ ) ) } export function isVNode(value: any): value is VNode { return value ? value.__v_isVNode === true : false } export function isSameVNodeType(n1: VNode, n2: VNode): boolean { if ( __DEV__ && n2.shapeFlag & ShapeFlags.COMPONENT && hmrDirtyComponents.has(n2.type as ConcreteComponent) ) { // #7042, ensure the vnode being unmounted during HMR // bitwise operations to remove keep alive flags n1.shapeFlag &= ~ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE n2.shapeFlag &= ~ShapeFlags.COMPONENT_KEPT_ALIVE // HMR only: if the component has been hot-updated, force a reload. return false } return n1.type === n2.type && n1.key === n2.key } let vnodeArgsTransformer: | (( args: Parameters<typeof _createVNode>, instance: ComponentInternalInstance | null ) => Parameters<typeof _createVNode>) | undefined /** * Internal API for registering an arguments transform for createVNode * used for creating stubs in the test-utils * It is *internal* but needs to be exposed for test-utils to pick up proper * typings */ export function transformVNodeArgs(transformer?: typeof vnodeArgsTransformer) { vnodeArgsTransformer = transformer } const createVNodeWithArgsTransform = ( ...args: Parameters<typeof _createVNode> ): VNode => { return _createVNode( ...(vnodeArgsTransformer ? vnodeArgsTransformer(args, currentRenderingInstance) : args) ) } export const InternalObjectKey = `__vInternal` const normalizeKey = ({ key }: VNodeProps): VNode['key'] => key != null ? key : null const normalizeRef = ({ ref, ref_key, ref_for }: VNodeProps): VNodeNormalizedRefAtom | null => { if (typeof ref === 'number') { ref = '' + ref } return ( ref != null ? isString(ref) || isRef(ref) || isFunction(ref) ? { i: currentRenderingInstance, r: ref, k: ref_key, f: !!ref_for } : ref : null ) as any } function createBaseVNode( type: VNodeTypes | ClassComponent | typeof NULL_DYNAMIC_COMPONENT, props: (Data & VNodeProps) | null = null, children: unknown = null, patchFlag = 0, dynamicProps: string[] | null = null, shapeFlag = type === Fragment ? 0 : ShapeFlags.ELEMENT, isBlockNode = false, needFullChildrenNormalization = false ) { const vnode = { __v_isVNode: true, __v_skip: true, type, props, key: props && normalizeKey(props), ref: props && normalizeRef(props), scopeId: currentScopeId, slotScopeIds: null, children, component: null, suspense: null, ssContent: null, ssFallback: null, dirs: null, transition: null, el: null, anchor: null, target: null, targetAnchor: null, staticCount: 0, shapeFlag, patchFlag, dynamicProps, dynamicChildren: null, appContext: null, ctx: currentRenderingInstance } as VNode if (needFullChildrenNormalization) { normalizeChildren(vnode, children) // normalize suspense children if (__FEATURE_SUSPENSE__ && shapeFlag & ShapeFlags.SUSPENSE) { ;(type as typeof SuspenseImpl).normalize(vnode) } } else if (children) { // compiled element vnode - if children is passed, only possible types are // string or Array. vnode.shapeFlag |= isString(children) ? ShapeFlags.TEXT_CHILDREN : ShapeFlags.ARRAY_CHILDREN } // validate key if (__DEV__ && vnode.key !== vnode.key) { warn(`VNode created with invalid key (NaN). VNode type:`, vnode.type) } // track vnode for block tree if ( isBlockTreeEnabled > 0 && // avoid a block node from tracking itself !isBlockNode && // has current parent block currentBlock && // presence of a patch flag indicates this node needs patching on updates. // component nodes also should always be patched, because even if the // component doesn't need to update, it needs to persist the instance on to // the next vnode so that it can be properly unmounted later. (vnode.patchFlag > 0 || shapeFlag & ShapeFlags.COMPONENT) && // the EVENTS flag is only for hydration and if it is the only flag, the // vnode should not be considered dynamic due to handler caching. vnode.patchFlag !== PatchFlags.HYDRATE_EVENTS ) { currentBlock.push(vnode) } if (__COMPAT__) { convertLegacyVModelProps(vnode) defineLegacyVNodeProperties(vnode) } return vnode } export { createBaseVNode as createElementVNode } export const createVNode = ( __DEV__ ? createVNodeWithArgsTransform : _createVNode ) as typeof _createVNode function _createVNode( type: VNodeTypes | ClassComponent | typeof NULL_DYNAMIC_COMPONENT, props: (Data & VNodeProps) | null = null, children: unknown = null, patchFlag: number = 0, dynamicProps: string[] | null = null, isBlockNode = false ): VNode { if (!type || type === NULL_DYNAMIC_COMPONENT) { if (__DEV__ && !type) { warn(`Invalid vnode type when creating vnode: ${type}.`) } type = Comment } if (isVNode(type)) { // createVNode receiving an existing vnode. This happens in cases like // <component :is="vnode"/> // #2078 make sure to merge refs during the clone instead of overwriting it const cloned = cloneVNode(type, props, true /* mergeRef: true */) if (children) { normalizeChildren(cloned, children) } if (isBlockTreeEnabled > 0 && !isBlockNode && currentBlock) { if (cloned.shapeFlag & ShapeFlags.COMPONENT) { currentBlock[currentBlock.indexOf(type)] = cloned } else { currentBlock.push(cloned) } } cloned.patchFlag |= PatchFlags.BAIL return cloned } // class component normalization. if (isClassComponent(type)) { type = type.__vccOpts } // 2.x async/functional component compat if (__COMPAT__) { type = convertLegacyComponent(type, currentRenderingInstance) } // class & style normalization. if (props) { // for reactive or proxy objects, we need to clone it to enable mutation. props = guardReactiveProps(props)! let { class: klass, style } = props if (klass && !isString(klass)) { props.class = normalizeClass(klass) } if (isObject(style)) { // reactive state objects need to be cloned since they are likely to be // mutated if (isProxy(style) && !isArray(style)) { style = extend({}, style) } props.style = normalizeStyle(style) } } // encode the vnode type information into a bitmap const shapeFlag = isString(type) ? ShapeFlags.ELEMENT : __FEATURE_SUSPENSE__ && isSuspense(type) ? ShapeFlags.SUSPENSE : isTeleport(type) ? ShapeFlags.TELEPORT : isObject(type) ? ShapeFlags.STATEFUL_COMPONENT : isFunction(type) ? ShapeFlags.FUNCTIONAL_COMPONENT : 0 if (__DEV__ && shapeFlag & ShapeFlags.STATEFUL_COMPONENT && isProxy(type)) { type = toRaw(type) warn( `Vue received a Component which was made a reactive object. This can ` + `lead to unnecessary performance overhead, and should be avoided by ` + `marking the component with \`markRaw\` or using \`shallowRef\` ` + `instead of \`ref\`.`, `\nComponent that was made reactive: `, type ) } return createBaseVNode( type, props, children, patchFlag, dynamicProps, shapeFlag, isBlockNode, true ) } export function guardReactiveProps(props: (Data & VNodeProps) | null) { if (!props) return null return isProxy(props) || InternalObjectKey in props ? extend({}, props) : props } export function cloneVNode<T, U>( vnode: VNode<T, U>, extraProps?: (Data & VNodeProps) | null, mergeRef = false ): VNode<T, U> { // This is intentionally NOT using spread or extend to avoid the runtime // key enumeration cost. const { props, ref, patchFlag, children } = vnode const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props const cloned: VNode<T, U> = { __v_isVNode: true, __v_skip: true, type: vnode.type, props: mergedProps, key: mergedProps && normalizeKey(mergedProps), ref: extraProps && extraProps.ref ? // #2078 in the case of <component :is="vnode" ref="extra"/> // if the vnode itself already has a ref, cloneVNode will need to merge // the refs so the single vnode can be set on multiple refs mergeRef && ref ? isArray(ref) ? ref.concat(normalizeRef(extraProps)!) : [ref, normalizeRef(extraProps)!] : normalizeRef(extraProps) : ref, scopeId: vnode.scopeId, slotScopeIds: vnode.slotScopeIds, children: __DEV__ && patchFlag === PatchFlags.HOISTED && isArray(children) ? (children as VNode[]).map(deepCloneVNode) : children, target: vnode.target, targetAnchor: vnode.targetAnchor, staticCount: vnode.staticCount, shapeFlag: vnode.shapeFlag, // if the vnode is cloned with extra props, we can no longer assume its // existing patch flag to be reliable and need to add the FULL_PROPS flag. // note: preserve flag for fragments since they use the flag for children // fast paths only. patchFlag: extraProps && vnode.type !== Fragment ? patchFlag === -1 // hoisted node ? PatchFlags.FULL_PROPS : patchFlag | PatchFlags.FULL_PROPS : patchFlag, dynamicProps: vnode.dynamicProps, dynamicChildren: vnode.dynamicChildren, appContext: vnode.appContext, dirs: vnode.dirs, transition: vnode.transition, // These should technically only be non-null on mounted VNodes. However, // they *should* be copied for kept-alive vnodes. So we just always copy // them since them being non-null during a mount doesn't affect the logic as // they will simply be overwritten. component: vnode.component, suspense: vnode.suspense, ssContent: vnode.ssContent && cloneVNode(vnode.ssContent), ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback), el: vnode.el, anchor: vnode.anchor, ctx: vnode.ctx, ce: vnode.ce } if (__COMPAT__) { defineLegacyVNodeProperties(cloned as VNode) } return cloned } /** * Dev only, for HMR of hoisted vnodes reused in v-for * https://github.com/vitejs/vite/issues/2022 */ function deepCloneVNode(vnode: VNode): VNode { const cloned = cloneVNode(vnode) if (isArray(vnode.children)) { cloned.children = (vnode.children as VNode[]).map(deepCloneVNode) } return cloned } /** * @private */ export function createTextVNode(text: string = ' ', flag: number = 0): VNode { return createVNode(Text, null, text, flag) } /** * @private */ export function createStaticVNode( content: string, numberOfNodes: number ): VNode { // A static vnode can contain multiple stringified elements, and the number // of elements is necessary for hydration. const vnode = createVNode(Static, null, content) vnode.staticCount = numberOfNodes return vnode } /** * @private */ export function createCommentVNode( text: string = '', // when used as the v-else branch, the comment node must be created as a // block to ensure correct updates. asBlock: boolean = false ): VNode { return asBlock ? (openBlock(), createBlock(Comment, null, text)) : createVNode(Comment, null, text) } export function normalizeVNode(child: VNodeChild): VNode { if (child == null || typeof child === 'boolean') { // empty placeholder return createVNode(Comment) } else if (isArray(child)) { // fragment return createVNode( Fragment, null, // #3666, avoid reference pollution when reusing vnode child.slice() ) } else if (typeof child === 'object') { // already vnode, this should be the most common since compiled templates // always produce all-vnode children arrays return cloneIfMounted(child) } else { // strings and numbers return createVNode(Text, null, String(child)) } } // optimized normalization for template-compiled render fns export function cloneIfMounted(child: VNode): VNode { return (child.el === null && child.patchFlag !== PatchFlags.HOISTED) || child.memo ? child : cloneVNode(child) } export function normalizeChildren(vnode: VNode, children: unknown) { let type = 0 const { shapeFlag } = vnode if (children == null) { children = null } else if (isArray(children)) { type = ShapeFlags.ARRAY_CHILDREN } else if (typeof children === 'object') { if (shapeFlag & (ShapeFlags.ELEMENT | ShapeFlags.TELEPORT)) { // Normalize slot to plain children for plain element and Teleport const slot = (children as any).default if (slot) { // _c marker is added by withCtx() indicating this is a compiled slot slot._c && (slot._d = false) normalizeChildren(vnode, slot()) slot._c && (slot._d = true) } return } else { type = ShapeFlags.SLOTS_CHILDREN const slotFlag = (children as RawSlots)._ if (!slotFlag && !(InternalObjectKey in children!)) { // if slots are not normalized, attach context instance // (compiled / normalized slots already have context) ;(children as RawSlots)._ctx = currentRenderingInstance } else if (slotFlag === SlotFlags.FORWARDED && currentRenderingInstance) { // a child component receives forwarded slots from the parent. // its slot type is determined by its parent's slot type. if ( (currentRenderingInstance.slots as RawSlots)._ === SlotFlags.STABLE ) { ;(children as RawSlots)._ = SlotFlags.STABLE } else { ;(children as RawSlots)._ = SlotFlags.DYNAMIC vnode.patchFlag |= PatchFlags.DYNAMIC_SLOTS } } } } else if (isFunction(children)) { children = { default: children, _ctx: currentRenderingInstance } type = ShapeFlags.SLOTS_CHILDREN } else { children = String(children) // force teleport children to array so it can be moved around if (shapeFlag & ShapeFlags.TELEPORT) { type = ShapeFlags.ARRAY_CHILDREN children = [createTextVNode(children as string)] } else { type = ShapeFlags.TEXT_CHILDREN } } vnode.children = children as VNodeNormalizedChildren vnode.shapeFlag |= type } export function mergeProps(...args: (Data & VNodeProps)[]) { const ret: Data = {} for (let i = 0; i < args.length; i++) { const toMerge = args[i] for (const key in toMerge) { if (key === 'class') { if (ret.class !== toMerge.class) { ret.class = normalizeClass([ret.class, toMerge.class]) } } else if (key === 'style') { ret.style = normalizeStyle([ret.style, toMerge.style]) } else if (isOn(key)) { const existing = ret[key] const incoming = toMerge[key] if ( incoming && existing !== incoming && !(isArray(existing) && existing.includes(incoming)) ) { ret[key] = existing ? [].concat(existing as any, incoming as any) : incoming } } else if (key !== '') { ret[key] = toMerge[key] } } } return ret } export function invokeVNodeHook( hook: VNodeHook, instance: ComponentInternalInstance | null, vnode: VNode, prevVNode: VNode | null = null ) { callWithAsyncErrorHandling(hook, instance, ErrorCodes.VNODE_HOOK, [ vnode, prevVNode ]) }
packages/runtime-core/src/vnode.ts
0
https://github.com/vuejs/core/commit/657476dcdb964be4fbb1277c215c073f3275728e
[ 0.0016712696524336934, 0.00021771456522401422, 0.0001597864757059142, 0.00017276385915465653, 0.00020597258117049932 ]
{ "id": 4, "code_window": [ " console.warn(\n", " `${capitalize(type)} operation ${key}failed: target is readonly.`,\n", " toRaw(this)\n", " )\n", " }\n", " return type === TriggerOpTypes.DELETE ? false : this\n", " }\n", "}\n", "\n", "function createInstrumentations() {\n", " const mutableInstrumentations: Record<string, Function | number> = {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return type === TriggerOpTypes.DELETE\n", " ? false\n", " : type === TriggerOpTypes.CLEAR\n", " ? undefined\n", " : this\n" ], "file_path": "packages/reactivity/src/collectionHandlers.ts", "type": "replace", "edit_start_line_idx": 225 }
import { getGlobalThis } from '@vue/shared' /** * This is only called in esm-bundler builds. * It is called when a renderer is created, in `baseCreateRenderer` so that * importing runtime-core is side-effects free. * * istanbul-ignore-next */ export function initFeatureFlags() { const needWarn = [] if (typeof __FEATURE_OPTIONS_API__ !== 'boolean') { __DEV__ && needWarn.push(`__VUE_OPTIONS_API__`) getGlobalThis().__VUE_OPTIONS_API__ = true } if (typeof __FEATURE_PROD_DEVTOOLS__ !== 'boolean') { __DEV__ && needWarn.push(`__VUE_PROD_DEVTOOLS__`) getGlobalThis().__VUE_PROD_DEVTOOLS__ = false } if (__DEV__ && needWarn.length) { const multi = needWarn.length > 1 console.warn( `Feature flag${multi ? `s` : ``} ${needWarn.join(', ')} ${ multi ? `are` : `is` } not explicitly defined. You are running the esm-bundler build of Vue, ` + `which expects these compile-time feature flags to be globally injected ` + `via the bundler config in order to get better tree-shaking in the ` + `production bundle.\n\n` + `For more details, see https://link.vuejs.org/feature-flags.` ) } }
packages/runtime-core/src/featureFlags.ts
0
https://github.com/vuejs/core/commit/657476dcdb964be4fbb1277c215c073f3275728e
[ 0.000174502725712955, 0.00016994148609228432, 0.0001645252195885405, 0.00017036899225786328, 0.0000040755294321570545 ]
{ "id": 0, "code_window": [ " `),\n", " ).toEqual('Markdown title');\n", " });\n", "});\n", "\n", "describe('parseMarkdownContentTitle', () => {\n", " test('Should parse markdown h1 title at the top', () => {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " test('should create excerpt for content with various code blocks', () => {\n", " expect(\n", " createExcerpt(dedent`\n", " \\`\\`\\`jsx\n", " import React from 'react';\n", " import Layout from '@theme/Layout';\n", " \\`\\`\\`\n", "\n", " Lorem \\`ipsum\\` dolor sit amet, consectetur \\`adipiscing elit\\`.\n", " `),\n", " ).toEqual('Lorem ipsum dolor sit amet, consectetur adipiscing elit.');\n", " });\n" ], "file_path": "packages/docusaurus-utils/src/__tests__/markdownParser.test.ts", "type": "add", "edit_start_line_idx": 131 }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { createExcerpt, parseMarkdownContentTitle, parseMarkdownString, } from '../markdownParser'; import dedent from 'dedent'; describe('createExcerpt', () => { test('should create excerpt for text-only content', () => { expect( createExcerpt(dedent` Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ex urna, molestie et sagittis ut, varius ac justo. Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis. `), ).toEqual( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ex urna, molestie et sagittis ut, varius ac justo.', ); }); test('should create excerpt for regular content with regular title', () => { expect( createExcerpt(dedent` # Markdown Regular Title Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ex urna, molestie et sagittis ut, varius ac justo. Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis. `), ).toEqual( // h1 title is skipped on purpose, because we don't want the page to have SEO metadatas title === description 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ex urna, molestie et sagittis ut, varius ac justo.', ); }); test('should create excerpt for regular content with alternate title', () => { expect( createExcerpt(dedent` Markdown Alternate Title ================ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ex urna, molestie et sagittis ut, varius ac justo. Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis. `), ).toEqual( // h1 title is skipped on purpose, because we don't want the page to have SEO metadatas title === description 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ex urna, molestie et sagittis ut, varius ac justo.', ); }); test('should create excerpt for content with h2 heading', () => { expect( createExcerpt(dedent` ## Lorem ipsum dolor sit amet Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis. `), ).toEqual('Lorem ipsum dolor sit amet'); }); test('should create excerpt for content beginning with blockquote', () => { expect( createExcerpt(dedent` > Lorem ipsum dolor sit amet Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis. `), ).toEqual('Lorem ipsum dolor sit amet'); }); test('should create excerpt for content beginning with image (eg. blog post)', () => { expect( createExcerpt(dedent` ![Lorem ipsum](/img/lorem-ipsum.svg) `), ).toEqual('Lorem ipsum'); }); test('should create excerpt for content beginning with admonitions', () => { expect( createExcerpt(dedent` import Component from '@site/src/components/Component' :::caution Lorem ipsum dolor sit amet, consectetur adipiscing elit. ::: Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis. `), ).toEqual('Lorem ipsum dolor sit amet, consectetur adipiscing elit.'); }); test('should create excerpt for content with imports/exports declarations and Markdown markup, as well as Emoji', () => { expect( createExcerpt(dedent` import Component from '@site/src/components/Component'; import Component from '@site/src/components/Component' import './styles.css'; export function ItemCol(props) { return <Item {...props} className={'col col--6 margin-bottom--lg'}/> } export function ItemCol(props) { return <Item {...props} className={'col col--6 margin-bottom--lg'}/> }; Lorem **ipsum** dolor sit \`amet\`[^1], consectetur _adipiscing_ elit. [**Vestibulum**](https://wiktionary.org/wiki/vestibulum) ex urna[^bignote], ~molestie~ et sagittis ut, varius ac justo :wink:. Nunc porttitor libero nec vulputate venenatis. Nam nec rhoncus mauris. Morbi tempus est et nibh maximus, tempus venenatis arcu lobortis. `), ).toEqual( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ex urna, molestie et sagittis ut, varius ac justo.', ); }); test('should create excerpt for heading specified with anchor-id syntax', () => { expect( createExcerpt(dedent` ## Markdown title {#my-anchor-id} `), ).toEqual('Markdown title'); }); }); describe('parseMarkdownContentTitle', () => { test('Should parse markdown h1 title at the top', () => { const markdown = dedent` # Markdown Title Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: 'Markdown Title', }); }); test('Should parse markdown h1 title at the top and remove it', () => { const markdown = dedent` # Markdown Title Lorem Ipsum `; expect( parseMarkdownContentTitle(markdown, {removeContentTitle: true}), ).toEqual({ content: 'Lorem Ipsum', contentTitle: 'Markdown Title', }); }); test('Should parse markdown h1 title at the top and unwrap inline code block', () => { const markdown = dedent` # \`Markdown Title\` Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: 'Markdown Title', }); }); test('Should parse markdown h1 title and trim content', () => { const markdown = ` # Markdown Title Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown.trim(), contentTitle: 'Markdown Title', }); }); test('Should parse not parse markdown h1 title and trim content', () => { const markdown = ` Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown.trim(), contentTitle: undefined, }); }); test('Should parse markdown h1 title with fixed anchor-id syntax', () => { const markdown = dedent` # Markdown Title {#my-anchor-id} Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: 'Markdown Title', }); }); test('Should parse markdown h1 title at the top (atx style with closing #)', () => { const markdown = dedent` # Markdown Title # Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: 'Markdown Title', }); }); test('Should parse markdown h1 title at the top followed by h2 title', () => { const markdown = dedent` # Markdown Title ## Heading 2 Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: 'Markdown Title', }); }); test('Should parse only first h1 title', () => { const markdown = dedent` # Markdown Title # Markdown Title 2 Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: 'Markdown Title', }); }); test('Should not parse title that is not at the top', () => { const markdown = dedent` Lorem Ipsum # Markdown Title 2 Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: undefined, }); }); test('Should parse markdown h1 alternate title', () => { const markdown = dedent` Markdown Title ================ Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: 'Markdown Title', }); }); test('Should parse markdown h1 alternate title and remove it', () => { const markdown = dedent` Markdown Title ================ Lorem Ipsum `; expect( parseMarkdownContentTitle(markdown, {removeContentTitle: true}), ).toEqual({ content: 'Lorem Ipsum', contentTitle: 'Markdown Title', }); }); test('Should parse markdown h1 title placed after import declarations', () => { const markdown = dedent` import Component1 from '@site/src/components/Component1'; import Component2 from '@site/src/components/Component2' import Component3 from '@site/src/components/Component3' import './styles.css'; # Markdown Title Lorem Ipsum `; // remove the useless line breaks? Does not matter too much expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: 'Markdown Title', }); }); test('Should parse markdown h1 title placed after various import declarations', () => { const markdown = ` import DefaultComponent from '@site/src/components/Component1'; import DefaultComponent2 from '../relative/path/Component2'; import * as EntireComponent from './relative/path/Component3'; import { Component4 } from "double-quote-module-name"; import { Component51, Component52, \n Component53, \n\t\t Component54 } from "double-quote-module-name"; import { Component6 as AliasComponent6 } from "module-name"; import DefaultComponent8, { DefaultComponent81 ,\nDefaultComponent82 } from "module-name"; import DefaultComponent9, * as EntireComponent9 from "module-name"; import {Component71,\nComponent72 as AliasComponent72,\nComponent73\n} \nfrom "module-name"; import './styles.css'; import _ from 'underscore'; import "module-name" # Markdown Title Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown.trim(), contentTitle: 'Markdown Title', }); }); test('Should parse markdown h1 title placed after various import declarations and remove it', () => { const markdown = ` import DefaultComponent from '@site/src/components/Component1'; import DefaultComponent2 from '../relative/path/Component2'; import * as EntireComponent from './relative/path/Component3'; import { Component4 } from "double-quote-module-name"; import { Component51, Component52, \n Component53, \n\t\t Component54 } from "double-quote-module-name"; import { Component6 as AliasComponent6 } from "module-name"; import DefaultComponent8, { DefaultComponent81 ,\nDefaultComponent82 } from "module-name"; import DefaultComponent9, * as EntireComponent9 from "module-name"; import {Component71,\nComponent72 as AliasComponent72,\nComponent73\n} \nfrom "module-name"; import './styles.css'; import _ from 'underscore'; import "module-name" # Markdown Title Lorem Ipsum `; expect( parseMarkdownContentTitle(markdown, {removeContentTitle: true}), ).toEqual({ content: markdown.trim().replace('# Markdown Title', ''), contentTitle: 'Markdown Title', }); }); test('Should parse markdown h1 alternate title placed after import declarations', () => { const markdown = dedent` import Component from '@site/src/components/Component'; import Component from '@site/src/components/Component' import './styles.css'; Markdown Title ============== Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: 'Markdown Title', }); }); test('Should parse markdown h1 alternate title placed after import declarations and remove it', () => { const markdown = dedent` import Component from '@site/src/components/Component'; import Component from '@site/src/components/Component' import './styles.css'; Markdown Title ============== Lorem Ipsum `; expect( parseMarkdownContentTitle(markdown, {removeContentTitle: true}), ).toEqual({ content: markdown.replace('Markdown Title\n==============\n\n', ''), contentTitle: 'Markdown Title', }); }); test('Should parse title-only', () => { const markdown = '# Document With Only A Title'; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: 'Document With Only A Title', }); }); test('Should not parse markdown h1 title in the middle of a doc', () => { const markdown = dedent` Lorem Ipsum # Markdown Title Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: undefined, }); }); test('Should not parse markdown h1 alternate title in the middle of the doc', () => { const markdown = dedent` Lorem Ipsum Markdown Title ================ Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: undefined, }); }); test('Should parse markdown h1 title placed after multiple import declarations', () => { const markdown = dedent` import Component1 from '@site/src/components/Component1'; import Component2 from '@site/src/components/Component2'; import Component3 from '@site/src/components/Component3'; import Component4 from '@site/src/components/Component4'; import Component5 from '@site/src/components/Component5'; import Component6 from '@site/src/components/Component6'; import Component7 from '@site/src/components/Component7'; import Component8 from '@site/src/components/Component8'; import Component9 from '@site/src/components/Component9'; import Component10 from '@site/src/components/Component10'; import Component11 from '@site/src/components/Component11'; import Component12 from '@site/src/components/Component12'; import Component13 from '@site/src/components/Component13'; import Component14 from '@site/src/components/Component14'; import Component15 from '@site/src/components/Component15'; # Markdown Title Lorem Ipsum `; expect(parseMarkdownContentTitle(markdown)).toEqual({ content: markdown, contentTitle: 'Markdown Title', }); }); test('Should parse markdown h1 title placed after multiple import declarations and remove it', () => { const markdown = dedent` import Component1 from '@site/src/components/Component1'; import Component2 from '@site/src/components/Component2'; import Component3 from '@site/src/components/Component3'; import Component4 from '@site/src/components/Component4'; import Component5 from '@site/src/components/Component5'; import Component6 from '@site/src/components/Component6'; import Component7 from '@site/src/components/Component7'; import Component8 from '@site/src/components/Component8'; import Component9 from '@site/src/components/Component9'; import Component10 from '@site/src/components/Component10'; import Component11 from '@site/src/components/Component11'; import Component12 from '@site/src/components/Component12'; import Component13 from '@site/src/components/Component13'; import Component14 from '@site/src/components/Component14'; import Component15 from '@site/src/components/Component15'; # Markdown Title Lorem Ipsum `; expect( parseMarkdownContentTitle(markdown, {removeContentTitle: true}), ).toEqual({ content: markdown.replace('# Markdown Title', ''), contentTitle: 'Markdown Title', }); }); }); describe('parseMarkdownString', () => { test('parse markdown with frontmatter', () => { expect( parseMarkdownString(dedent` --- title: Frontmatter title --- Some text `), ).toMatchInlineSnapshot(` Object { "content": "Some text", "contentTitle": undefined, "excerpt": "Some text", "frontMatter": Object { "title": "Frontmatter title", }, } `); }); test('should parse first heading as contentTitle', () => { expect( parseMarkdownString(dedent` # Markdown Title Some text `), ).toMatchInlineSnapshot(` Object { "content": "# Markdown Title Some text", "contentTitle": "Markdown Title", "excerpt": "Some text", "frontMatter": Object {}, } `); }); test('should warn about duplicate titles (frontmatter + markdown)', () => { expect( parseMarkdownString(dedent` --- title: Frontmatter title --- # Markdown Title Some text `), ).toMatchInlineSnapshot(` Object { "content": "# Markdown Title Some text", "contentTitle": "Markdown Title", "excerpt": "Some text", "frontMatter": Object { "title": "Frontmatter title", }, } `); }); test('should warn about duplicate titles (frontmatter + markdown alternate)', () => { expect( parseMarkdownString(dedent` --- title: Frontmatter title --- Markdown Title alternate ================ Some text `), ).toMatchInlineSnapshot(` Object { "content": "Markdown Title alternate ================ Some text", "contentTitle": "Markdown Title alternate", "excerpt": "Some text", "frontMatter": Object { "title": "Frontmatter title", }, } `); }); test('should not warn for duplicate title if markdown title is not at the top', () => { expect( parseMarkdownString(dedent` --- title: Frontmatter title --- foo # Markdown Title `), ).toMatchInlineSnapshot(` Object { "content": "foo # Markdown Title", "contentTitle": undefined, "excerpt": "foo", "frontMatter": Object { "title": "Frontmatter title", }, } `); }); test('should delete only first heading', () => { expect( parseMarkdownString(dedent` # Markdown Title test test test # test bar # Markdown Title 2 ### Markdown Title h3 `), ).toMatchInlineSnapshot(` Object { "content": "# Markdown Title test test test # test bar # Markdown Title 2 ### Markdown Title h3", "contentTitle": "Markdown Title", "excerpt": "test test test # test bar", "frontMatter": Object {}, } `); }); test('should parse front-matter and ignore h2', () => { expect( parseMarkdownString( dedent` --- title: Frontmatter title --- ## test `, ), ).toMatchInlineSnapshot(` Object { "content": "## test", "contentTitle": undefined, "excerpt": "test", "frontMatter": Object { "title": "Frontmatter title", }, } `); }); test('should read front matter only', () => { expect( parseMarkdownString(dedent` --- title: test --- `), ).toMatchInlineSnapshot(` Object { "content": "", "contentTitle": undefined, "excerpt": undefined, "frontMatter": Object { "title": "test", }, } `); }); test('should parse title only', () => { expect(parseMarkdownString('# test')).toMatchInlineSnapshot(` Object { "content": "# test", "contentTitle": "test", "excerpt": undefined, "frontMatter": Object {}, } `); }); test('should parse title only alternate', () => { expect( parseMarkdownString(dedent` test === `), ).toMatchInlineSnapshot(` Object { "content": "test ===", "contentTitle": "test", "excerpt": undefined, "frontMatter": Object {}, } `); }); test('should warn about duplicate titles', () => { expect( parseMarkdownString(dedent` --- title: Frontmatter title --- # test `), ).toMatchInlineSnapshot(` Object { "content": "# test", "contentTitle": "test", "excerpt": undefined, "frontMatter": Object { "title": "Frontmatter title", }, } `); }); test('should ignore markdown title if its not a first text', () => { expect( parseMarkdownString(dedent` foo # test `), ).toMatchInlineSnapshot(` Object { "content": "foo # test", "contentTitle": undefined, "excerpt": "foo", "frontMatter": Object {}, } `); }); test('should delete only first heading', () => { expect( parseMarkdownString(dedent` # test test test test test test test test test test # test bar # test2 ### test test3 `), ).toMatchInlineSnapshot(` Object { "content": "# test test test test test test test test test test # test bar # test2 ### test test3", "contentTitle": "test", "excerpt": "test test test test test test", "frontMatter": Object {}, } `); }); });
packages/docusaurus-utils/src/__tests__/markdownParser.test.ts
1
https://github.com/facebook/docusaurus/commit/578470a24c513c13e122139bd94671342c702980
[ 0.9861787557601929, 0.15441766381263733, 0.0001681681169429794, 0.001555182272568345, 0.30839982628822327 ]
{ "id": 0, "code_window": [ " `),\n", " ).toEqual('Markdown title');\n", " });\n", "});\n", "\n", "describe('parseMarkdownContentTitle', () => {\n", " test('Should parse markdown h1 title at the top', () => {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " test('should create excerpt for content with various code blocks', () => {\n", " expect(\n", " createExcerpt(dedent`\n", " \\`\\`\\`jsx\n", " import React from 'react';\n", " import Layout from '@theme/Layout';\n", " \\`\\`\\`\n", "\n", " Lorem \\`ipsum\\` dolor sit amet, consectetur \\`adipiscing elit\\`.\n", " `),\n", " ).toEqual('Lorem ipsum dolor sit amet, consectetur adipiscing elit.');\n", " });\n" ], "file_path": "packages/docusaurus-utils/src/__tests__/markdownParser.test.ts", "type": "add", "edit_start_line_idx": 131 }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const advancedBasePreset = require('cssnano-preset-advanced'); const postCssSortMediaQueries = require('postcss-sort-media-queries'); const postCssRemoveOverriddenCustomProperties = require('./src/remove-overridden-custom-properties'); module.exports = function docusaurusCssnanoPreset(opts) { const advancedPreset = advancedBasePreset({ autoprefixer: {add: false}, discardComments: {removeAll: true}, ...opts, }); advancedPreset.plugins.unshift( [postCssSortMediaQueries], [postCssRemoveOverriddenCustomProperties], ); return advancedPreset; };
packages/docusaurus-cssnano-preset/index.js
0
https://github.com/facebook/docusaurus/commit/578470a24c513c13e122139bd94671342c702980
[ 0.0001753480319166556, 0.00017371232388541102, 0.00017125510203186423, 0.00017453383770771325, 0.0000017690265394776361 ]
{ "id": 0, "code_window": [ " `),\n", " ).toEqual('Markdown title');\n", " });\n", "});\n", "\n", "describe('parseMarkdownContentTitle', () => {\n", " test('Should parse markdown h1 title at the top', () => {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " test('should create excerpt for content with various code blocks', () => {\n", " expect(\n", " createExcerpt(dedent`\n", " \\`\\`\\`jsx\n", " import React from 'react';\n", " import Layout from '@theme/Layout';\n", " \\`\\`\\`\n", "\n", " Lorem \\`ipsum\\` dolor sit amet, consectetur \\`adipiscing elit\\`.\n", " `),\n", " ).toEqual('Lorem ipsum dolor sit amet, consectetur adipiscing elit.');\n", " });\n" ], "file_path": "packages/docusaurus-utils/src/__tests__/markdownParser.test.ts", "type": "add", "edit_start_line_idx": 131 }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { CategoryMetadatasFile, DefaultSidebarItemsGenerator, } from '../sidebarItemsGenerator'; import {Sidebar, SidebarItemsGenerator} from '../types'; import fs from 'fs-extra'; import {DefaultNumberPrefixParser} from '../numberPrefix'; describe('DefaultSidebarItemsGenerator', () => { function testDefaultSidebarItemsGenerator( params: Partial<Parameters<SidebarItemsGenerator>[0]>, ) { return DefaultSidebarItemsGenerator({ numberPrefixParser: DefaultNumberPrefixParser, item: { type: 'autogenerated', dirName: '.', }, version: { versionName: 'current', contentPath: 'docs', }, docs: [], options: { sidebarCollapsed: true, sidebarCollapsible: true, }, ...params, }); } function mockCategoryMetadataFiles( categoryMetadataFiles: Record<string, Partial<CategoryMetadatasFile>>, ) { jest.spyOn(fs, 'pathExists').mockImplementation((metadataFilePath) => { return typeof categoryMetadataFiles[metadataFilePath] !== 'undefined'; }); jest.spyOn(fs, 'readFile').mockImplementation( // @ts-expect-error: annoying TS error due to overrides async (metadataFilePath: string) => { return JSON.stringify(categoryMetadataFiles[metadataFilePath]); }, ); } test('generates empty sidebar slice when no docs and emit a warning', async () => { const consoleWarn = jest.spyOn(console, 'warn'); const sidebarSlice = await testDefaultSidebarItemsGenerator({ docs: [], }); expect(sidebarSlice).toEqual([]); expect(consoleWarn).toHaveBeenCalledWith( expect.stringMatching( /No docs found in dir .: can't auto-generate a sidebar/, ), ); }); test('generates simple flat sidebar', async () => { const sidebarSlice = await DefaultSidebarItemsGenerator({ numberPrefixParser: DefaultNumberPrefixParser, item: { type: 'autogenerated', dirName: '.', }, version: { versionName: 'current', contentPath: '', }, docs: [ { id: 'doc1', source: 'doc1.md', sourceDirName: '.', sidebarPosition: 2, frontMatter: { sidebar_label: 'doc1 sidebar label', }, }, { id: 'doc2', source: 'doc2.md', sourceDirName: '.', sidebarPosition: 3, frontMatter: {}, }, { id: 'doc3', source: 'doc3.md', sourceDirName: '.', sidebarPosition: 1, frontMatter: {}, }, { id: 'doc4', source: 'doc4.md', sourceDirName: '.', sidebarPosition: 1.5, frontMatter: {}, }, { id: 'doc5', source: 'doc5.md', sourceDirName: '.', sidebarPosition: undefined, frontMatter: {}, }, ], options: { sidebarCollapsed: true, sidebarCollapsible: true, }, }); expect(sidebarSlice).toEqual([ {type: 'doc', id: 'doc3'}, {type: 'doc', id: 'doc4'}, {type: 'doc', id: 'doc1', label: 'doc1 sidebar label'}, {type: 'doc', id: 'doc2'}, {type: 'doc', id: 'doc5'}, ] as Sidebar); }); test('generates complex nested sidebar', async () => { mockCategoryMetadataFiles({ '02-Guides/_category_.json': {collapsed: false}, '02-Guides/01-SubGuides/_category_.yml': { label: 'SubGuides (metadata file label)', }, }); const sidebarSlice = await DefaultSidebarItemsGenerator({ numberPrefixParser: DefaultNumberPrefixParser, item: { type: 'autogenerated', dirName: '.', }, version: { versionName: 'current', contentPath: '', }, docs: [ { id: 'intro', source: 'intro.md', sourceDirName: '.', sidebarPosition: 1, frontMatter: {}, }, { id: 'tutorial2', source: 'tutorial2.md', sourceDirName: '01-Tutorials', sidebarPosition: 2, frontMatter: {}, }, { id: 'tutorial1', source: 'tutorial1.md', sourceDirName: '01-Tutorials', sidebarPosition: 1, frontMatter: {}, }, { id: 'guide2', source: 'guide2.md', sourceDirName: '02-Guides', sidebarPosition: 2, frontMatter: {}, }, { id: 'guide1', source: 'guide1.md', sourceDirName: '02-Guides', sidebarPosition: 1, frontMatter: {}, }, { id: 'nested-guide', source: 'nested-guide.md', sourceDirName: '02-Guides/01-SubGuides', sidebarPosition: undefined, frontMatter: {}, }, { id: 'end', source: 'end.md', sourceDirName: '.', sidebarPosition: 3, frontMatter: {}, }, ], options: { sidebarCollapsed: true, sidebarCollapsible: true, }, }); expect(sidebarSlice).toEqual([ {type: 'doc', id: 'intro'}, { type: 'category', label: 'Tutorials', collapsed: true, collapsible: true, items: [ {type: 'doc', id: 'tutorial1'}, {type: 'doc', id: 'tutorial2'}, ], }, { type: 'category', label: 'Guides', collapsed: false, collapsible: true, items: [ {type: 'doc', id: 'guide1'}, { type: 'category', label: 'SubGuides (metadata file label)', collapsed: true, collapsible: true, items: [{type: 'doc', id: 'nested-guide'}], }, {type: 'doc', id: 'guide2'}, ], }, {type: 'doc', id: 'end'}, ] as Sidebar); }); test('generates subfolder sidebar', async () => { // Ensure that category metadata file is correctly read // fix edge case found in https://github.com/facebook/docusaurus/issues/4638 mockCategoryMetadataFiles({ 'subfolder/subsubfolder/subsubsubfolder2/_category_.yml': { position: 2, label: 'subsubsubfolder2 (_category_.yml label)', }, 'subfolder/subsubfolder/subsubsubfolder3/_category_.json': { position: 1, label: 'subsubsubfolder3 (_category_.json label)', collapsible: false, collapsed: false, }, }); const sidebarSlice = await DefaultSidebarItemsGenerator({ numberPrefixParser: DefaultNumberPrefixParser, item: { type: 'autogenerated', dirName: 'subfolder/subsubfolder', }, version: { versionName: 'current', contentPath: '', }, docs: [ { id: 'doc1', source: 'doc1.md', sourceDirName: 'subfolder/subsubfolder', sidebarPosition: undefined, frontMatter: {}, }, { id: 'doc2', source: 'doc2.md', sourceDirName: 'subfolder', sidebarPosition: undefined, frontMatter: {}, }, { id: 'doc3', source: 'doc3.md', sourceDirName: '.', sidebarPosition: undefined, frontMatter: {}, }, { id: 'doc4', source: 'doc4.md', sourceDirName: 'subfolder/subsubfolder', sidebarPosition: undefined, frontMatter: {}, }, { id: 'doc5', source: 'doc5.md', sourceDirName: 'subfolder/subsubfolder/subsubsubfolder', sidebarPosition: undefined, frontMatter: {}, }, { id: 'doc6', source: 'doc6.md', sourceDirName: 'subfolder/subsubfolder/subsubsubfolder2', sidebarPosition: undefined, frontMatter: {}, }, { id: 'doc7', source: 'doc7.md', sourceDirName: 'subfolder/subsubfolder/subsubsubfolder3', sidebarPosition: 2, frontMatter: {}, }, { id: 'doc8', source: 'doc8.md', sourceDirName: 'subfolder/subsubfolder/subsubsubfolder3', sidebarPosition: 1, frontMatter: {}, }, ], options: { sidebarCollapsed: true, sidebarCollapsible: true, }, }); expect(sidebarSlice).toEqual([ { type: 'category', label: 'subsubsubfolder3 (_category_.json label)', collapsed: false, collapsible: false, items: [ {type: 'doc', id: 'doc8'}, {type: 'doc', id: 'doc7'}, ], }, { type: 'category', label: 'subsubsubfolder2 (_category_.yml label)', collapsed: true, collapsible: true, items: [{type: 'doc', id: 'doc6'}], }, {type: 'doc', id: 'doc1'}, {type: 'doc', id: 'doc4'}, { type: 'category', label: 'subsubsubfolder', collapsed: true, collapsible: true, items: [{type: 'doc', id: 'doc5'}], }, ] as Sidebar); }); });
packages/docusaurus-plugin-content-docs/src/__tests__/sidebarItemsGenerator.test.ts
0
https://github.com/facebook/docusaurus/commit/578470a24c513c13e122139bd94671342c702980
[ 0.0001777585275704041, 0.0001740306179272011, 0.0001675100502325222, 0.00017427068087272346, 0.0000023050224626786076 ]
{ "id": 0, "code_window": [ " `),\n", " ).toEqual('Markdown title');\n", " });\n", "});\n", "\n", "describe('parseMarkdownContentTitle', () => {\n", " test('Should parse markdown h1 title at the top', () => {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " test('should create excerpt for content with various code blocks', () => {\n", " expect(\n", " createExcerpt(dedent`\n", " \\`\\`\\`jsx\n", " import React from 'react';\n", " import Layout from '@theme/Layout';\n", " \\`\\`\\`\n", "\n", " Lorem \\`ipsum\\` dolor sit amet, consectetur \\`adipiscing elit\\`.\n", " `),\n", " ).toEqual('Lorem ipsum dolor sit amet, consectetur adipiscing elit.');\n", " });\n" ], "file_path": "packages/docusaurus-utils/src/__tests__/markdownParser.test.ts", "type": "add", "edit_start_line_idx": 131 }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment'; import siteConfig from '@generated/docusaurus.config'; import type * as PrismNamespace from 'prismjs'; const prismIncludeLanguages = (PrismObject: typeof PrismNamespace): void => { if (ExecutionEnvironment.canUseDOM) { const { themeConfig: {prism = {}}, } = siteConfig; const {additionalLanguages = []} = prism as {additionalLanguages: string[]}; window.Prism = PrismObject; additionalLanguages.forEach((lang) => { require(`prismjs/components/prism-${lang}`); // eslint-disable-line }); delete (window as Window & {Prism?: typeof PrismNamespace}).Prism; } }; export default prismIncludeLanguages;
packages/docusaurus-theme-classic/src/theme/prism-include-languages.ts
0
https://github.com/facebook/docusaurus/commit/578470a24c513c13e122139bd94671342c702980
[ 0.00017732023843564093, 0.00017271487740799785, 0.000166826241184026, 0.00017399813805241138, 0.000004379198799142614 ]
{ "id": 1, "code_window": [ " .trimLeft()\n", " // Remove Markdown alternate title\n", " .replace(/^[^\\n]*\\n[=]+/g, '')\n", " .split('\\n');\n", "\n", " /* eslint-disable no-continue */\n", " // eslint-disable-next-line no-restricted-syntax\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " let inCode = false;\n" ], "file_path": "packages/docusaurus-utils/src/markdownParser.ts", "type": "add", "edit_start_line_idx": 20 }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import chalk from 'chalk'; import fs from 'fs-extra'; import matter from 'gray-matter'; // Hacky way of stripping out import statements from the excerpt // TODO: Find a better way to do so, possibly by compiling the Markdown content, // stripping out HTML tags and obtaining the first line. export function createExcerpt(fileString: string): string | undefined { const fileLines = fileString .trimLeft() // Remove Markdown alternate title .replace(/^[^\n]*\n[=]+/g, '') .split('\n'); /* eslint-disable no-continue */ // eslint-disable-next-line no-restricted-syntax for (const fileLine of fileLines) { // Skip empty line. if (!fileLine.trim()) { continue; } // Skip import/export declaration. if (/^\s*?import\s.*(from.*)?;?|export\s.*{.*};?/.test(fileLine)) { continue; } const cleanedLine = fileLine // Remove HTML tags. .replace(/<[^>]*>/g, '') // Remove Title headers .replace(/^#\s*([^#]*)\s*#?/gm, '') // Remove Markdown + ATX-style headers .replace(/^#{1,6}\s*([^#]*)\s*(#{1,6})?/gm, '$1') // Remove emphasis and strikethroughs. .replace(/([*_~]{1,3})(\S.*?\S{0,1})\1/g, '$2') // Remove images. .replace(/!\[(.*?)\][[(].*?[\])]/g, '$1') // Remove footnotes. .replace(/\[\^.+?\](: .*?$)?/g, '') // Remove inline links. .replace(/\[(.*?)\][[(].*?[\])]/g, '$1') // Remove inline code. .replace(/`(.+?)`/g, '$1') // Remove blockquotes. .replace(/^\s{0,3}>\s?/g, '') // Remove admonition definition. .replace(/(:{3}.*)/, '') // Remove Emoji names within colons include preceding whitespace. .replace(/\s?(:(::|[^:\n])+:)/g, '') // Remove custom Markdown heading id. .replace(/{#*[\w-]+}/, '') .trim(); if (cleanedLine) { return cleanedLine; } } return undefined; } export function parseFrontMatter( markdownFileContent: string, ): { frontMatter: Record<string, unknown>; content: string; } { const {data, content} = matter(markdownFileContent); return { frontMatter: data ?? {}, content: content?.trim() ?? '', }; } // Try to convert markdown heading as text // Does not need to be perfect, it is only used as a fallback when frontMatter.title is not provided // For now, we just unwrap possible inline code blocks (# `config.js`) function toTextContentTitle(contentTitle: string): string { if (contentTitle.startsWith('`') && contentTitle.endsWith('`')) { return contentTitle.substring(1, contentTitle.length - 1); } return contentTitle; } export function parseMarkdownContentTitle( contentUntrimmed: string, options?: {removeContentTitle?: boolean}, ): {content: string; contentTitle: string | undefined} { const removeContentTitleOption = options?.removeContentTitle ?? false; const content = contentUntrimmed.trim(); const IMPORT_STATEMENT = /import\s+(([\w*{}\s\n,]+)from\s+)?["'\s]([@\w/_.-]+)["'\s];?|\n/ .source; const REGULAR_TITLE = /(?<pattern>#\s*(?<title>[^#\n{]*)+[ \t]*(?<suffix>({#*[\w-]+})|#)?\n*?)/ .source; const ALTERNATE_TITLE = /(?<pattern>\s*(?<title>[^\n]*)\s*\n[=]+)/.source; const regularTitleMatch = new RegExp( `^(?:${IMPORT_STATEMENT})*?${REGULAR_TITLE}`, 'g', ).exec(content); const alternateTitleMatch = new RegExp( `^(?:${IMPORT_STATEMENT})*?${ALTERNATE_TITLE}`, 'g', ).exec(content); const titleMatch = regularTitleMatch ?? alternateTitleMatch; const {pattern, title} = titleMatch?.groups ?? {}; if (!pattern || !title) { return {content, contentTitle: undefined}; } else { const newContent = removeContentTitleOption ? content.replace(pattern, '') : content; return { content: newContent.trim(), contentTitle: toTextContentTitle(title.trim()).trim(), }; } } type ParsedMarkdown = { frontMatter: Record<string, unknown>; content: string; contentTitle: string | undefined; excerpt: string | undefined; }; export function parseMarkdownString( markdownFileContent: string, options?: {removeContentTitle?: boolean}, ): ParsedMarkdown { try { const {frontMatter, content: contentWithoutFrontMatter} = parseFrontMatter( markdownFileContent, ); const {content, contentTitle} = parseMarkdownContentTitle( contentWithoutFrontMatter, options, ); const excerpt = createExcerpt(content); return { frontMatter, content, contentTitle, excerpt, }; } catch (e) { console.error( chalk.red(`Error while parsing Markdown frontmatter. This can happen if you use special characters in frontmatter values (try using double quotes around that value).`), ); throw e; } } export async function parseMarkdownFile( source: string, options?: {removeContentTitle?: boolean}, ): Promise<ParsedMarkdown> { const markdownString = await fs.readFile(source, 'utf-8'); try { return parseMarkdownString(markdownString, options); } catch (e) { throw new Error( `Error while parsing Markdown file ${source}: "${e.message}".`, ); } }
packages/docusaurus-utils/src/markdownParser.ts
1
https://github.com/facebook/docusaurus/commit/578470a24c513c13e122139bd94671342c702980
[ 0.4934103786945343, 0.027381695806980133, 0.00016647743177600205, 0.0006541989278048277, 0.10986387729644775 ]
{ "id": 1, "code_window": [ " .trimLeft()\n", " // Remove Markdown alternate title\n", " .replace(/^[^\\n]*\\n[=]+/g, '')\n", " .split('\\n');\n", "\n", " /* eslint-disable no-continue */\n", " // eslint-disable-next-line no-restricted-syntax\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " let inCode = false;\n" ], "file_path": "packages/docusaurus-utils/src/markdownParser.ts", "type": "add", "edit_start_line_idx": 20 }
--- id: docusaurus-core title: Docusaurus Client API sidebar_label: Client API --- Docusaurus provides some APIs on the clients that can be helpful to you when building your site. ## Components {#components} ### `<Head/>` {#head} This reusable React component will manage all of your changes to the document head. It takes plain HTML tags and outputs plain HTML tags and is beginner-friendly. It is a wrapper around [React Helmet](https://github.com/nfl/react-helmet). Usage Example: ```jsx {2,5,10} import React from 'react'; import Head from '@docusaurus/Head'; const MySEO = () => ( <Head> <meta property="og:description" content="My custom description" /> <meta charSet="utf-8" /> <title>My Title</title> <link rel="canonical" href="http://mysite.com/example" /> </Head> ); ``` Nested or latter components will override duplicate usages: ```jsx {2,5,8,11} <Parent> <Head> <title>My Title</title> <meta name="description" content="Helmet application" /> </Head> <Child> <Head> <title>Nested Title</title> <meta name="description" content="Nested component" /> </Head> </Child> </Parent> ``` Outputs: ```html <head> <title>Nested Title</title> <meta name="description" content="Nested component" /> </head> ``` ### `<Link/>` {#link} This component enables linking to internal pages as well as a powerful performance feature called preloading. Preloading is used to prefetch resources so that the resources are fetched by the time the user navigates with this component. We use an `IntersectionObserver` to fetch a low-priority request when the `<Link>` is in the viewport and then use an `onMouseOver` event to trigger a high-priority request when it is likely that a user will navigate to the requested resource. The component is a wrapper around react-router’s `<Link>` component that adds useful enhancements specific to Docusaurus. All props are passed through to react-router’s `<Link>` component. External links also work, and automatically have these props: `target="_blank" rel="noopener noreferrer"`. ```jsx {2,7} import React from 'react'; import Link from '@docusaurus/Link'; const Page = () => ( <div> <p> Check out my <Link to="/blog">blog</Link>! </p> <p> Follow me on <Link to="https://twitter.com/docusaurus">Twitter</Link>! </p> </div> ); ``` #### `to`: string {#to-string} The target location to navigate to. Example: `/docs/introduction`. ```jsx <Link to="/courses" /> ``` ### `<Redirect/>` {#redirect} Rendering a `<Redirect>` will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects (HTTP 3xx) do. You can refer to [React Router's Redirect documentation](https://reacttraining.com/react-router/web/api/Redirect) for more info on available props. Example usage: ```jsx {2,5} import React from 'react'; import {Redirect} from '@docusaurus/router'; const Home = () => { return <Redirect to="/docs/test" />; }; ``` :::note `@docusaurus/router` implements [React Router](https://reacttraining.com/react-router/web/guides/quick-start) and supports its features. ::: ### `<BrowserOnly/>` {#browseronly} The `<BrowserOnly>` component permits to render React components only in the browser, after the React app has hydrated. :::tip Use it for integrating with code that can't run in Node.js, because `window` or `document` objects are being accessed. ::: #### Props {#browseronly-props} - `children`: render function prop returning browser-only JSX. Will not be executed in Node.js - `fallback` (optional): JSX to render on the server (Node.js) and until React hydration completes. #### Example with code {#browseronly-example-code} ```jsx // highlight-start import BrowserOnly from '@docusaurus/BrowserOnly'; // highlight-end const MyComponent = () => { return ( // highlight-start <BrowserOnly> {() => { <span>page url = {window.location.href}</span>; }} </BrowserOnly> // highlight-end ); }; ``` #### Example with a library {#browseronly-example-library} ```jsx // highlight-start import BrowserOnly from '@docusaurus/BrowserOnly'; // highlight-end const MyComponent = (props) => { return ( // highlight-start <BrowserOnly fallback={<div>Loading...</div>}> {() => { const LibComponent = require('some-lib').LibComponent; return <LibComponent {...props} />; }} </BrowserOnly> // highlight-end ); }; ``` ### `<Interpolate/>` {#interpolate} A simple interpolation component for text containing dynamic placeholders. The placeholders will be replaced with the provided dynamic values and JSX elements of your choice (strings, links, styled elements...). #### Props {#interpolate-props} - `children`: text containing interpolation placeholders like `{placeholderName}` - `values`: object containing interpolation placeholder values ```jsx import React from 'react'; import Link from '@docusaurus/Link'; import Interpolate from '@docusaurus/Interpolate'; export default function VisitMyWebsiteMessage() { return ( // highlight-start <Interpolate values={{ firstName: 'Sébastien', website: ( <Link to="https://docusaurus.io" className="my-website-class"> website </Link> ), }}> {'Hello, {firstName}! How are you? Take a look at my {website}'} </Interpolate> // highlight-end ); } ``` ### `<Translate/>` {#translate} When [localizing your site](./i18n/i18n-introduction.md), the `<Translate/>` component will allow providing **translation support to React components**, such as your homepage. The `<Translate>` component supports [interpolation](#interpolate). The translation strings will be extracted from your code with the [`docusaurus write-translations`](./cli.md#docusaurus-write-translations-sitedir) CLI and create a `code.json` translation file in `website/i18n/<locale>`. :::note The `<Translate/>` props **must be hardcoded strings**. Apart the `values` prop used for interpolation, it is **not possible to use variables**, or the static extraction wouldn't work. ::: #### Props {#translate-props} - `children`: untranslated string in the default site locale (can contain [interpolation placeholders](#interpolate)) - `id`: optional value to use as key in JSON translation files - `description`: optional text to help the translator - `values`: optional object containing interpolation placeholder values #### Example {#example} ```jsx title="src/pages/index.js" import React from 'react'; import Layout from '@theme/Layout'; // highlight-start import Translate from '@docusaurus/Translate'; // highlight-end export default function Home() { return ( <Layout> <h1> {/* highlight-start */} <Translate id="homepage.title" description="The homepage welcome message"> Welcome to my website </Translate> {/* highlight-end */} </h1> <main> {/* highlight-start */} <Translate values={{firstName: 'Sébastien'}}> {'Welcome, {firstName}! How are you?'} </Translate> {/* highlight-end */} </main> </Layout> ); } ``` ## Hooks {#hooks} ### `useDocusaurusContext` {#usedocusauruscontext} React hook to access Docusaurus Context. Context contains `siteConfig` object from [docusaurus.config.js](api/docusaurus.config.js.md), and some additional site metadata. ```ts type DocusaurusPluginVersionInformation = | {readonly type: 'package'; readonly version?: string} | {readonly type: 'project'} | {readonly type: 'local'} | {readonly type: 'synthetic'}; interface DocusaurusSiteMetadata { readonly docusaurusVersion: string; readonly siteVersion?: string; readonly pluginVersions: Record<string, DocusaurusPluginVersionInformation>; } interface I18nLocaleConfig { label: string; direction: string; } interface I18n { defaultLocale: string; locales: [string, ...string[]]; currentLocale: string; localeConfigs: Record<string, I18nLocaleConfig>; } interface DocusaurusContext { siteConfig: DocusaurusConfig; siteMetadata: DocusaurusSiteMetadata; globalData: Record<string, unknown>; i18n: I18n; codeTranslations: Record<string, string>; } ``` Usage example: ```jsx {5,8-10} import React from 'react'; import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; const MyComponent = () => { const {siteConfig, siteMetadata} = useDocusaurusContext(); return ( <div> <h1>{siteConfig.title}</h1> <div>{siteMetadata.siteVersion}</div> <div>{siteMetadata.docusaurusVersion}</div> </div> ); }; ``` ### `useIsBrowser` {#useIsBrowser} Returns `true` when the React app has successfully hydrated in the browser. :::caution Use this hook instead of `typeof windows !== 'undefined'` in React rendering logic. The first client-side render output (in the browser) **must be exactly the same** as the server-side render output (Node.js). Not following this rule can lead to unexpected hydration behaviors, as described in [The Perils of Rehydration](https://www.joshwcomeau.com/react/the-perils-of-rehydration/). ::: Usage example: ```jsx import React from 'react'; import useIsBrowser from '@docusaurus/useIsBrowser'; const MyComponent = () => { // highlight-start const isBrowser = useIsBrowser(); // highlight-end return <div>{isBrowser ? 'Client' : 'Server'}</div>; }; ``` ### `useBaseUrl` {#usebaseurl} React hook to prepend your site `baseUrl` to a string. :::caution **Don't use it for regular links!** The `/baseUrl/` prefix is automatically added to all **absolute paths** by default: - Markdown: `[link](/my/path)` will link to `/baseUrl/my/path` - React: `<Link to="/my/path/">link</Link>` will link to `/baseUrl/my/path` ::: #### Options {#options} ```ts type BaseUrlOptions = { forcePrependBaseUrl: boolean; absolute: boolean; }; ``` #### Example usage: {#example-usage} ```jsx import React from 'react'; import useBaseUrl from '@docusaurus/useBaseUrl'; const SomeImage = () => { // highlight-start const imgSrc = useBaseUrl('/img/myImage.png'); // highlight-end return <img src={imgSrc} />; }; ``` :::tip In most cases, you don't need `useBaseUrl`. Prefer a `require()` call for [assets](./guides/markdown-features/markdown-features-assets.mdx): ```jsx <img src={require('@site/static/img/myImage.png').default} /> ``` ::: ### `useBaseUrlUtils` {#usebaseurlutils} Sometimes `useBaseUrl` is not good enough. This hook return additional utils related to your site's base url. - `withBaseUrl`: useful if you need to add base urls to multiple urls at once. ```jsx import React from 'react'; import {useBaseUrlUtils} from '@docusaurus/useBaseUrl'; const Component = () => { const urls = ['/a', '/b']; // highlight-start const {withBaseUrl} = useBaseUrlUtils(); const urlsWithBaseUrl = urls.map(withBaseUrl); // highlight-end return <div>{/* ... */}</div>; }; ``` ### `useGlobalData` {#useglobaldata} React hook to access Docusaurus global data created by all the plugins. Global data is namespaced by plugin name, and plugin id. :::info Plugin id is only useful when a plugin is used multiple times on the same site. Each plugin instance is able to create its own global data. ::: ```ts type GlobalData = Record< PluginName, Record< PluginId, // "default" by default any // plugin-specific data > >; ``` Usage example: ```jsx {2,5-7} import React from 'react'; import useGlobalData from '@docusaurus/useGlobalData'; const MyComponent = () => { const globalData = useGlobalData(); const myPluginData = globalData['my-plugin']['default']; return <div>{myPluginData.someAttribute}</div>; }; ``` :::tip Inspect your site's global data at `./docusaurus/globalData.json` ::: ### `usePluginData` {#useplugindata} Access global data created by a specific plugin instance. This is the most convenient hook to access plugin global data, and should be used most of the time. `pluginId` is optional if you don't use multi-instance plugins. ```ts usePluginData(pluginName: string, pluginId?: string) ``` Usage example: ```jsx {2,5-6} import React from 'react'; import {usePluginData} from '@docusaurus/useGlobalData'; const MyComponent = () => { const myPluginData = usePluginData('my-plugin'); return <div>{myPluginData.someAttribute}</div>; }; ``` ### `useAllPluginInstancesData` {#useallplugininstancesdata} Access global data created by a specific plugin. Given a plugin name, it returns the data of all the plugins instances of that name, by plugin id. ```ts useAllPluginInstancesData(pluginName: string) ``` Usage example: ```jsx {2,5-7} import React from 'react'; import {useAllPluginInstancesData} from '@docusaurus/useGlobalData'; const MyComponent = () => { const allPluginInstancesData = useAllPluginInstancesData('my-plugin'); const myPluginData = allPluginInstancesData['default']; return <div>{myPluginData.someAttribute}</div>; }; ``` ## Functions {#functions} ### `interpolate` {#interpolate-1} The imperative counterpart of the [`<Interpolate>`](#interpolate) component. #### Signature {#signature} ```ts // Simple string interpolation function interpolate(text: string, values: Record<string, string>): string; // JSX interpolation function interpolate( text: string, values: Record<string, ReactNode>, ): ReactNode; ``` #### Example {#example-1} ```jsx // highlight-start import {interpolate} from '@docusaurus/Interpolate'; // highlight-end const message = interpolate('Welcome {firstName}', {firstName: 'Sébastien'}); ``` ### `translate` {#translate-1} The imperative counterpart of the [`<Translate>`](#translate) component. Also supporting [placeholders interpolation](#interpolate). :::tip Use the imperative API for the **rare cases** where a **component cannot be used**, such as: - the page `title` metadata - the `placeholder` props of form inputs - the `aria-label` props for accessibility ::: #### Signature {#signature-1} ```ts function translate( translation: {message: string; id?: string; description?: string}, values: Record<string, string>, ): string; ``` #### Example {#example-2} ```jsx title="src/pages/index.js" import React from 'react'; import Layout from '@theme/Layout'; // highlight-start import {translate} from '@docusaurus/Translate'; // highlight-end export default function Home() { return ( <Layout // highlight-start title={translate({message: 'My page meta title'})} // highlight-end > <img src={'https://docusaurus.io/logo.png'} aria-label={ // highlight-start translate( { message: 'The logo of site {siteName}', // Optional id: 'homepage.logo.ariaLabel', description: 'The home page logo aria label', }, {siteName: 'Docusaurus'}, ) // highlight-end } /> </Layout> ); } ``` ## Modules {#modules} ### `ExecutionEnvironment` {#executionenvironment} A module which exposes a few boolean variables to check the current rendering environment. :::caution For React rendering logic, use [`useIsBrowser()`](#useIsBrowser) or [`<BrowserOnly>`](#browseronly) instead. ::: Example: ```jsx import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment'; if (ExecutionEnvironment.canUseDOM) { require('lib-that-only-works-client-side'); } ``` | Field | Description | | --- | --- | | `ExecutionEnvironment.canUseDOM` | `true` if on client/browser, `false` on Node.js/prerendering. | | `ExecutionEnvironment.canUseEventListeners` | `true` if on client and has `window.addEventListener`. | | `ExecutionEnvironment.canUseIntersectionObserver` | `true` if on client and has `IntersectionObserver`. | | `ExecutionEnvironment.canUseViewport` | `true` if on client and has `window.screen`. | ### `constants` {#constants} A module exposing useful constants to client-side theme code. ```jsx import {DEFAULT_PLUGIN_ID} from '@docusaurus/constants'; ``` | Named export | Value | | ------------------- | --------- | | `DEFAULT_PLUGIN_ID` | `default` |
website/versioned_docs/version-2.0.0-beta.6/docusaurus-core.md
0
https://github.com/facebook/docusaurus/commit/578470a24c513c13e122139bd94671342c702980
[ 0.0005008087609894574, 0.0001867680693976581, 0.00016206002328544855, 0.00016963509551715106, 0.00006666593253612518 ]
{ "id": 1, "code_window": [ " .trimLeft()\n", " // Remove Markdown alternate title\n", " .replace(/^[^\\n]*\\n[=]+/g, '')\n", " .split('\\n');\n", "\n", " /* eslint-disable no-continue */\n", " // eslint-disable-next-line no-restricted-syntax\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " let inCode = false;\n" ], "file_path": "packages/docusaurus-utils/src/markdownParser.ts", "type": "add", "edit_start_line_idx": 20 }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {Handler} from '@netlify/functions'; import {createPlaygroundResponse} from '../functionUtils/playgroundUtils'; export const handler: Handler = async function (_event, _context) { return createPlaygroundResponse('stackblitz'); };
admin/new.docusaurus.io/functions/stackblitz.ts
0
https://github.com/facebook/docusaurus/commit/578470a24c513c13e122139bd94671342c702980
[ 0.0001759593578753993, 0.00017393814050592482, 0.00017191692313645035, 0.00017393814050592482, 0.0000020212173694744706 ]
{ "id": 1, "code_window": [ " .trimLeft()\n", " // Remove Markdown alternate title\n", " .replace(/^[^\\n]*\\n[=]+/g, '')\n", " .split('\\n');\n", "\n", " /* eslint-disable no-continue */\n", " // eslint-disable-next-line no-restricted-syntax\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " let inCode = false;\n" ], "file_path": "packages/docusaurus-utils/src/markdownParser.ts", "type": "add", "edit_start_line_idx": 20 }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {parseCodeBlockTitle} from '../codeBlockUtils'; describe('parseCodeBlockTitle', () => { test('should parse double quote delimited title', () => { expect(parseCodeBlockTitle(`title="index.js"`)).toEqual(`index.js`); }); test('should parse single quote delimited title', () => { expect(parseCodeBlockTitle(`title='index.js'`)).toEqual(`index.js`); }); test('should not parse mismatched quote delimiters', () => { expect(parseCodeBlockTitle(`title="index.js'`)).toEqual(``); }); test('should parse undefined metastring', () => { expect(parseCodeBlockTitle(undefined)).toEqual(``); }); test('should parse metastring with no title specified', () => { expect(parseCodeBlockTitle(`{1,2-3}`)).toEqual(``); }); test('should parse with multiple metadatas title first', () => { expect(parseCodeBlockTitle(`title="index.js" label="JavaScript"`)).toEqual( `index.js`, ); }); test('should parse with multiple metadatas title last', () => { expect(parseCodeBlockTitle(`label="JavaScript" title="index.js"`)).toEqual( `index.js`, ); }); test('should parse double quotes when delimited by single quotes', () => { expect(parseCodeBlockTitle(`title='console.log("Hello, World!")'`)).toEqual( `console.log("Hello, World!")`, ); }); test('should parse single quotes when delimited by double quotes', () => { expect(parseCodeBlockTitle(`title="console.log('Hello, World!')"`)).toEqual( `console.log('Hello, World!')`, ); }); });
packages/docusaurus-theme-common/src/utils/__tests__/codeBlockUtils.test.ts
0
https://github.com/facebook/docusaurus/commit/578470a24c513c13e122139bd94671342c702980
[ 0.000175337670953013, 0.00017356091120745987, 0.0001722038578009233, 0.00017345452215522528, 0.0000011313244385746657 ]
{ "id": 2, "code_window": [ " continue;\n", " }\n", "\n", " const cleanedLine = fileLine\n", " // Remove HTML tags.\n", " .replace(/<[^>]*>/g, '')\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " // Skip code block line.\n", " if (fileLine.trim().startsWith('```')) {\n", " inCode = !inCode;\n", " continue;\n", " } else if (inCode) {\n", " continue;\n", " }\n", "\n" ], "file_path": "packages/docusaurus-utils/src/markdownParser.ts", "type": "add", "edit_start_line_idx": 34 }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import chalk from 'chalk'; import fs from 'fs-extra'; import matter from 'gray-matter'; // Hacky way of stripping out import statements from the excerpt // TODO: Find a better way to do so, possibly by compiling the Markdown content, // stripping out HTML tags and obtaining the first line. export function createExcerpt(fileString: string): string | undefined { const fileLines = fileString .trimLeft() // Remove Markdown alternate title .replace(/^[^\n]*\n[=]+/g, '') .split('\n'); /* eslint-disable no-continue */ // eslint-disable-next-line no-restricted-syntax for (const fileLine of fileLines) { // Skip empty line. if (!fileLine.trim()) { continue; } // Skip import/export declaration. if (/^\s*?import\s.*(from.*)?;?|export\s.*{.*};?/.test(fileLine)) { continue; } const cleanedLine = fileLine // Remove HTML tags. .replace(/<[^>]*>/g, '') // Remove Title headers .replace(/^#\s*([^#]*)\s*#?/gm, '') // Remove Markdown + ATX-style headers .replace(/^#{1,6}\s*([^#]*)\s*(#{1,6})?/gm, '$1') // Remove emphasis and strikethroughs. .replace(/([*_~]{1,3})(\S.*?\S{0,1})\1/g, '$2') // Remove images. .replace(/!\[(.*?)\][[(].*?[\])]/g, '$1') // Remove footnotes. .replace(/\[\^.+?\](: .*?$)?/g, '') // Remove inline links. .replace(/\[(.*?)\][[(].*?[\])]/g, '$1') // Remove inline code. .replace(/`(.+?)`/g, '$1') // Remove blockquotes. .replace(/^\s{0,3}>\s?/g, '') // Remove admonition definition. .replace(/(:{3}.*)/, '') // Remove Emoji names within colons include preceding whitespace. .replace(/\s?(:(::|[^:\n])+:)/g, '') // Remove custom Markdown heading id. .replace(/{#*[\w-]+}/, '') .trim(); if (cleanedLine) { return cleanedLine; } } return undefined; } export function parseFrontMatter( markdownFileContent: string, ): { frontMatter: Record<string, unknown>; content: string; } { const {data, content} = matter(markdownFileContent); return { frontMatter: data ?? {}, content: content?.trim() ?? '', }; } // Try to convert markdown heading as text // Does not need to be perfect, it is only used as a fallback when frontMatter.title is not provided // For now, we just unwrap possible inline code blocks (# `config.js`) function toTextContentTitle(contentTitle: string): string { if (contentTitle.startsWith('`') && contentTitle.endsWith('`')) { return contentTitle.substring(1, contentTitle.length - 1); } return contentTitle; } export function parseMarkdownContentTitle( contentUntrimmed: string, options?: {removeContentTitle?: boolean}, ): {content: string; contentTitle: string | undefined} { const removeContentTitleOption = options?.removeContentTitle ?? false; const content = contentUntrimmed.trim(); const IMPORT_STATEMENT = /import\s+(([\w*{}\s\n,]+)from\s+)?["'\s]([@\w/_.-]+)["'\s];?|\n/ .source; const REGULAR_TITLE = /(?<pattern>#\s*(?<title>[^#\n{]*)+[ \t]*(?<suffix>({#*[\w-]+})|#)?\n*?)/ .source; const ALTERNATE_TITLE = /(?<pattern>\s*(?<title>[^\n]*)\s*\n[=]+)/.source; const regularTitleMatch = new RegExp( `^(?:${IMPORT_STATEMENT})*?${REGULAR_TITLE}`, 'g', ).exec(content); const alternateTitleMatch = new RegExp( `^(?:${IMPORT_STATEMENT})*?${ALTERNATE_TITLE}`, 'g', ).exec(content); const titleMatch = regularTitleMatch ?? alternateTitleMatch; const {pattern, title} = titleMatch?.groups ?? {}; if (!pattern || !title) { return {content, contentTitle: undefined}; } else { const newContent = removeContentTitleOption ? content.replace(pattern, '') : content; return { content: newContent.trim(), contentTitle: toTextContentTitle(title.trim()).trim(), }; } } type ParsedMarkdown = { frontMatter: Record<string, unknown>; content: string; contentTitle: string | undefined; excerpt: string | undefined; }; export function parseMarkdownString( markdownFileContent: string, options?: {removeContentTitle?: boolean}, ): ParsedMarkdown { try { const {frontMatter, content: contentWithoutFrontMatter} = parseFrontMatter( markdownFileContent, ); const {content, contentTitle} = parseMarkdownContentTitle( contentWithoutFrontMatter, options, ); const excerpt = createExcerpt(content); return { frontMatter, content, contentTitle, excerpt, }; } catch (e) { console.error( chalk.red(`Error while parsing Markdown frontmatter. This can happen if you use special characters in frontmatter values (try using double quotes around that value).`), ); throw e; } } export async function parseMarkdownFile( source: string, options?: {removeContentTitle?: boolean}, ): Promise<ParsedMarkdown> { const markdownString = await fs.readFile(source, 'utf-8'); try { return parseMarkdownString(markdownString, options); } catch (e) { throw new Error( `Error while parsing Markdown file ${source}: "${e.message}".`, ); } }
packages/docusaurus-utils/src/markdownParser.ts
1
https://github.com/facebook/docusaurus/commit/578470a24c513c13e122139bd94671342c702980
[ 0.9992043375968933, 0.10560738295316696, 0.00016481569036841393, 0.0001703799789538607, 0.3063051104545593 ]
{ "id": 2, "code_window": [ " continue;\n", " }\n", "\n", " const cleanedLine = fileLine\n", " // Remove HTML tags.\n", " .replace(/<[^>]*>/g, '')\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " // Skip code block line.\n", " if (fileLine.trim().startsWith('```')) {\n", " inCode = !inCode;\n", " continue;\n", " } else if (inCode) {\n", " continue;\n", " }\n", "\n" ], "file_path": "packages/docusaurus-utils/src/markdownParser.ts", "type": "add", "edit_start_line_idx": 34 }
--- id: creating-pages title: Creating Pages slug: /creating-pages sidebar_label: Pages --- In this section, we will learn about creating pages in Docusaurus. This is useful for creating **one-off standalone pages** like a showcase page, playground page or support page. The functionality of pages is powered by `@docusaurus/plugin-content-pages`. You can use React components, or Markdown. :::note Pages do not have sidebars, only [docs](./docs/docs-introduction.md) do. ::: :::info Check the [Pages Plugin API Reference documentation](./../api/plugins/plugin-content-pages.md) for an exhaustive list of options. ::: ## Add a React page {#add-a-react-page} Create a file `/src/pages/helloReact.js`: ```jsx title="/src/pages/helloReact.js" import React from 'react'; import Layout from '@theme/Layout'; function Hello() { return ( <Layout title="Hello"> <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '50vh', fontSize: '20px', }}> <p> Edit <code>pages/hello.js</code> and save to reload. </p> </div> </Layout> ); } export default Hello; ``` Once you save the file, the development server will automatically reload the changes. Now open `http://localhost:3000/helloReact`, you will see the new page you just created. Each page doesn't come with any styling. You will need to import the `Layout` component from `@theme/Layout` and wrap your contents within that component if you want the navbar and/or footer to appear. :::tip You can also create TypeScript pages with the `.tsx` extension (`helloReact.tsx`). ::: ## Add a Markdown page {#add-a-markdown-page} Create a file `/src/pages/helloMarkdown.md`: ```mdx title="/src/pages/helloMarkdown.md" --- title: my hello page title description: my hello page description hide_table_of_contents: true --- # Hello How are you? ``` In the same way, a page will be created at `http://localhost:3000/helloMarkdown`. Markdown pages are less flexible than React pages, because it always uses the theme layout. Here's an [example Markdown page](/examples/markdownPageExample). :::tip You can use the full power of React in Markdown pages too, refer to the [MDX](https://mdxjs.com/) documentation. ::: ## Routing {#routing} If you are familiar with other static site generators like Jekyll and Next, this routing approach will feel familiar to you. Any JavaScript file you create under `/src/pages/` directory will be automatically converted to a website page, following the `/src/pages/` directory hierarchy. For example: - `/src/pages/index.js` → `<baseUrl>` - `/src/pages/foo.js` → `<baseUrl>/foo` - `/src/pages/foo/test.js` → `<baseUrl>/foo/test` - `/src/pages/foo/index.js` → `<baseUrl>/foo/` In this component-based development era, it is encouraged to co-locate your styling, markup and behavior together into components. Each page is a component, and if you need to customize your page design with your own styles, we recommend co-locating your styles with the page component in its own directory. For example, to create a "Support" page, you could do one of the following: - Add a `/src/pages/support.js` file - Create a `/src/pages/support/` directory and a `/src/pages/support/index.js` file. The latter is preferred as it has the benefits of letting you put files related to the page within that directory. For example, a CSS module file (`styles.module.css`) with styles meant to only be used on the "Support" page. **Note:** this is merely a recommended directory structure and you will still need to manually import the CSS module file within your component module (`support/index.js`). By default, any Markdown or Javascript file starting with `_` will be ignored, and no routes will be created for that file (see the `exclude` option). ```sh my-website ├── src │ └── pages │ ├── styles.module.css │ ├── index.js | ├──_ignored.js │ └── support │ ├── index.js │ └── styles.module.css . ``` :::caution All JavaScript/TypeScript files within the `src/pages/` directory will have corresponding website paths generated for them. If you want to create reusable components into that directory, use the `exclude` option (by default, files prefixed with `_`, test files(`.test.js`) and files in `__tests__` directory are not turned into pages). ::: ## Using React {#using-react} React is used as the UI library to create pages. Every page component should export a React component, and you can leverage on the expressiveness of React to build rich and interactive content. ## Duplicate Routes {#duplicate-routes} You may accidentally create multiple pages that are meant to be accessed on the same route. When this happens, Docusaurus will warn you about duplicate routes when you run `yarn start` or `yarn build`, but the site will still be built successfully. The page that was created last will be accessible, but it will override other conflicting pages. To resolve this issue, you should modify or remove any conflicting routes.
website/versioned_docs/version-2.0.0-beta.5/guides/creating-pages.md
0
https://github.com/facebook/docusaurus/commit/578470a24c513c13e122139bd94671342c702980
[ 0.00017457045032642782, 0.00016870987019501626, 0.00016258875257335603, 0.00016878705355338752, 0.0000034931138088722946 ]
{ "id": 2, "code_window": [ " continue;\n", " }\n", "\n", " const cleanedLine = fileLine\n", " // Remove HTML tags.\n", " .replace(/<[^>]*>/g, '')\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " // Skip code block line.\n", " if (fileLine.trim().startsWith('```')) {\n", " inCode = !inCode;\n", " continue;\n", " } else if (inCode) {\n", " continue;\n", " }\n", "\n" ], "file_path": "packages/docusaurus-utils/src/markdownParser.ts", "type": "add", "edit_start_line_idx": 34 }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // Compare the 2 paths, ignoring trailing / export const isSamePath = ( path1: string | undefined, path2: string | undefined, ): boolean => { const normalize = (pathname: string | undefined) => { return !pathname || pathname?.endsWith('/') ? pathname : `${pathname}/`; }; return normalize(path1) === normalize(path2); };
packages/docusaurus-theme-common/src/utils/pathUtils.ts
0
https://github.com/facebook/docusaurus/commit/578470a24c513c13e122139bd94671342c702980
[ 0.0001753667602315545, 0.0001750379742588848, 0.00017470918828621507, 0.0001750379742588848, 3.2878597266972065e-7 ]
{ "id": 2, "code_window": [ " continue;\n", " }\n", "\n", " const cleanedLine = fileLine\n", " // Remove HTML tags.\n", " .replace(/<[^>]*>/g, '')\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " // Skip code block line.\n", " if (fileLine.trim().startsWith('```')) {\n", " inCode = !inCode;\n", " continue;\n", " } else if (inCode) {\n", " continue;\n", " }\n", "\n" ], "file_path": "packages/docusaurus-utils/src/markdownParser.ts", "type": "add", "edit_start_line_idx": 34 }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import clsx from 'clsx'; import LastUpdated from '@theme/LastUpdated'; import type {Props} from '@theme/DocItem'; import EditThisPage from '@theme/EditThisPage'; import TagsListInline, { Props as TagsListInlineProps, } from '@theme/TagsListInline'; import styles from './styles.module.css'; import {ThemeClassNames} from '@docusaurus/theme-common'; function TagsRow(props: TagsListInlineProps) { return ( <div className={clsx( ThemeClassNames.docs.docFooterTagsRow, 'row margin-bottom--sm', )}> <div className="col"> <TagsListInline {...props} /> </div> </div> ); } type EditMetaRowProps = Pick< Props['content']['metadata'], 'editUrl' | 'lastUpdatedAt' | 'lastUpdatedBy' | 'formattedLastUpdatedAt' >; function EditMetaRow({ editUrl, lastUpdatedAt, lastUpdatedBy, formattedLastUpdatedAt, }: EditMetaRowProps) { return ( <div className={clsx(ThemeClassNames.docs.docFooterEditMetaRow, 'row')}> <div className="col">{editUrl && <EditThisPage editUrl={editUrl} />}</div> <div className={clsx('col', styles.lastUpdated)}> {(lastUpdatedAt || lastUpdatedBy) && ( <LastUpdated lastUpdatedAt={lastUpdatedAt} formattedLastUpdatedAt={formattedLastUpdatedAt} lastUpdatedBy={lastUpdatedBy} /> )} </div> </div> ); } export default function DocItemFooter(props: Props): JSX.Element { const {content: DocContent} = props; const {metadata} = DocContent; const { editUrl, lastUpdatedAt, formattedLastUpdatedAt, lastUpdatedBy, tags, } = metadata; const canDisplayTagsRow = tags.length > 0; const canDisplayEditMetaRow = !!(editUrl || lastUpdatedAt || lastUpdatedBy); const canDisplayFooter = canDisplayTagsRow || canDisplayEditMetaRow; if (!canDisplayFooter) { return <></>; } return ( <footer className={clsx(ThemeClassNames.docs.docFooter, 'docusaurus-mt-lg')}> {canDisplayTagsRow && <TagsRow tags={tags} />} {canDisplayEditMetaRow && ( <EditMetaRow editUrl={editUrl} lastUpdatedAt={lastUpdatedAt} lastUpdatedBy={lastUpdatedBy} formattedLastUpdatedAt={formattedLastUpdatedAt} /> )} </footer> ); }
packages/docusaurus-theme-classic/src/theme/DocItemFooter/index.tsx
0
https://github.com/facebook/docusaurus/commit/578470a24c513c13e122139bd94671342c702980
[ 0.000488697667606175, 0.00023419116041623056, 0.00016555185720790178, 0.00017438763461541384, 0.0001096093692467548 ]
{ "id": 0, "code_window": [ "\n", " - ${{ if eq(parameters.VSCODE_BUILD_ALPINE_ARM64, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: vscode_cli_alpine_arm64_cli\n", "\n", " - ${{ if eq(parameters.VSCODE_BUILD_ALPINE, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}\n" ], "file_path": "build/azure-pipelines/alpine/cli-build-alpine.yml", "type": "add", "edit_start_line_idx": 95 }
parameters: - name: VSCODE_BUILD_ALPINE type: boolean default: false - name: VSCODE_BUILD_ALPINE_ARM64 type: boolean default: false - name: VSCODE_QUALITY type: string steps: - task: NodeTool@0 inputs: versionSource: fromFile versionFilePath: .nvmrc nodejsMirror: https://github.com/joaomoreno/node-mirror/releases/download - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: # Install yarn as the ARM64 build agent is using vanilla Ubuntu - ${{ if eq(parameters.VSCODE_BUILD_ALPINE_ARM64, true) }}: - task: Npm@1 displayName: Install yarn inputs: command: custom customCommand: install --global yarn - script: | set -e yarn --frozen-lockfile --ignore-optional workingDirectory: build displayName: Install pipeline build - template: ../cli/cli-apply-patches.yml - task: Npm@1 displayName: Download openssl prebuilt inputs: command: custom customCommand: pack @vscode-internal/[email protected] customRegistry: useFeed customFeed: "Monaco/openssl-prebuilt" workingDir: $(Build.ArtifactStagingDirectory) - script: | set -e mkdir $(Build.ArtifactStagingDirectory)/openssl tar -xvzf $(Build.ArtifactStagingDirectory)/vscode-internal-openssl-prebuilt-0.0.11.tgz --strip-components=1 --directory=$(Build.ArtifactStagingDirectory)/openssl displayName: Extract openssl prebuilt # inspired by: https://github.com/emk/rust-musl-builder/blob/main/Dockerfile - bash: | set -e sudo apt-get update sudo apt-get install -yq build-essential musl-dev musl-tools linux-libc-dev pkgconf xutils-dev lld sudo ln -s "/usr/bin/g++" "/usr/bin/musl-g++" || echo "link exists" displayName: Install musl build dependencies - template: ../cli/install-rust-posix.yml parameters: targets: - ${{ if eq(parameters.VSCODE_BUILD_ALPINE_ARM64, true) }}: - aarch64-unknown-linux-musl - ${{ if eq(parameters.VSCODE_BUILD_ALPINE, true) }}: - x86_64-unknown-linux-musl - ${{ if eq(parameters.VSCODE_BUILD_ALPINE_ARM64, true) }}: - template: ../cli/cli-compile.yml parameters: VSCODE_CLI_TARGET: aarch64-unknown-linux-musl VSCODE_CLI_ARTIFACT: vscode_cli_alpine_arm64_cli VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_CLI_ENV: CXX_aarch64-unknown-linux-musl: musl-g++ CC_aarch64-unknown-linux-musl: musl-gcc OPENSSL_LIB_DIR: $(Build.ArtifactStagingDirectory)/openssl/arm64-linux-musl/lib OPENSSL_INCLUDE_DIR: $(Build.ArtifactStagingDirectory)/openssl/arm64-linux-musl/include OPENSSL_STATIC: "1" - ${{ if eq(parameters.VSCODE_BUILD_ALPINE, true) }}: - template: ../cli/cli-compile.yml parameters: VSCODE_CLI_TARGET: x86_64-unknown-linux-musl VSCODE_CLI_ARTIFACT: vscode_cli_alpine_x64_cli VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_CLI_ENV: CXX_aarch64-unknown-linux-musl: musl-g++ CC_aarch64-unknown-linux-musl: musl-gcc OPENSSL_LIB_DIR: $(Build.ArtifactStagingDirectory)/openssl/x64-linux-musl/lib OPENSSL_INCLUDE_DIR: $(Build.ArtifactStagingDirectory)/openssl/x64-linux-musl/include OPENSSL_STATIC: "1" - ${{ if eq(parameters.VSCODE_BUILD_ALPINE_ARM64, true) }}: - template: ../cli/cli-publish.yml parameters: VSCODE_CLI_ARTIFACT: vscode_cli_alpine_arm64_cli - ${{ if eq(parameters.VSCODE_BUILD_ALPINE, true) }}: - template: ../cli/cli-publish.yml parameters: VSCODE_CLI_ARTIFACT: vscode_cli_alpine_x64_cli
build/azure-pipelines/alpine/cli-build-alpine.yml
1
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.9805164933204651, 0.20346984267234802, 0.0001669696212047711, 0.03185587748885155, 0.3403700888156891 ]
{ "id": 0, "code_window": [ "\n", " - ${{ if eq(parameters.VSCODE_BUILD_ALPINE_ARM64, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: vscode_cli_alpine_arm64_cli\n", "\n", " - ${{ if eq(parameters.VSCODE_BUILD_ALPINE, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}\n" ], "file_path": "build/azure-pipelines/alpine/cli-build-alpine.yml", "type": "add", "edit_start_line_idx": 95 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as aria from 'vs/base/browser/ui/aria/aria'; import { Action, IAction } from 'vs/base/common/actions'; import { distinct } from 'vs/base/common/arrays'; import { raceTimeout, RunOnceScheduler } from 'vs/base/common/async'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { isErrorWithActions } from 'vs/base/common/errorMessage'; import * as errors from 'vs/base/common/errors'; import { Emitter, Event } from 'vs/base/common/event'; import { DisposableStore, IDisposable } from 'vs/base/common/lifecycle'; import { deepClone, equals } from 'vs/base/common/objects'; import severity from 'vs/base/common/severity'; import { URI, URI as uri } from 'vs/base/common/uri'; import { generateUuid } from 'vs/base/common/uuid'; import { isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { ITextModel } from 'vs/editor/common/model'; import * as nls from 'vs/nls'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug'; import { IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { FileChangesEvent, FileChangeType, IFileService } from 'vs/platform/files/common/files'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput'; import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity'; import { IWorkspaceContextService, IWorkspaceFolder, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { IWorkspaceTrustRequestService } from 'vs/platform/workspace/common/workspaceTrust'; import { EditorsOrder } from 'vs/workbench/common/editor'; import { EditorInput } from 'vs/workbench/common/editor/editorInput'; import { IViewDescriptorService, ViewContainerLocation } from 'vs/workbench/common/views'; import { IViewsService } from 'vs/workbench/services/views/common/viewsService'; import { AdapterManager } from 'vs/workbench/contrib/debug/browser/debugAdapterManager'; import { DEBUG_CONFIGURE_COMMAND_ID, DEBUG_CONFIGURE_LABEL } from 'vs/workbench/contrib/debug/browser/debugCommands'; import { ConfigurationManager } from 'vs/workbench/contrib/debug/browser/debugConfigurationManager'; import { DebugMemoryFileSystemProvider } from 'vs/workbench/contrib/debug/browser/debugMemory'; import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession'; import { DebugTaskRunner, TaskRunResult } from 'vs/workbench/contrib/debug/browser/debugTaskRunner'; import { CALLSTACK_VIEW_ID, CONTEXT_BREAKPOINTS_EXIST, CONTEXT_HAS_DEBUGGED, CONTEXT_DEBUG_STATE, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_UX, CONTEXT_DISASSEMBLY_VIEW_FOCUS, CONTEXT_IN_DEBUG_MODE, debuggerDisabledMessage, DEBUG_MEMORY_SCHEME, getStateLabel, IAdapterManager, IBreakpoint, IBreakpointData, ICompound, IConfig, IConfigurationManager, IDebugConfiguration, IDebugModel, IDebugService, IDebugSession, IDebugSessionOptions, IEnablement, IExceptionBreakpoint, IGlobalConfig, ILaunch, IStackFrame, IThread, IViewModel, REPL_VIEW_ID, State, VIEWLET_ID, DEBUG_SCHEME, IBreakpointUpdateData } from 'vs/workbench/contrib/debug/common/debug'; import { DebugCompoundRoot } from 'vs/workbench/contrib/debug/common/debugCompoundRoot'; import { Debugger } from 'vs/workbench/contrib/debug/common/debugger'; import { Breakpoint, DataBreakpoint, DebugModel, FunctionBreakpoint, InstructionBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel'; import { Source } from 'vs/workbench/contrib/debug/common/debugSource'; import { DebugStorage } from 'vs/workbench/contrib/debug/common/debugStorage'; import { DebugTelemetry } from 'vs/workbench/contrib/debug/common/debugTelemetry'; import { getExtensionHostDebugSession, saveAllBeforeDebugStart } from 'vs/workbench/contrib/debug/common/debugUtils'; import { ViewModel } from 'vs/workbench/contrib/debug/common/debugViewModel'; import { DisassemblyViewInput } from 'vs/workbench/contrib/debug/common/disassemblyViewInput'; import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/contrib/files/common/files'; import { IActivityService, NumberBadge } from 'vs/workbench/services/activity/common/activity'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService'; import { ILifecycleService } from 'vs/workbench/services/lifecycle/common/lifecycle'; import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite'; export class DebugService implements IDebugService { declare readonly _serviceBrand: undefined; private readonly _onDidChangeState: Emitter<State>; private readonly _onDidNewSession: Emitter<IDebugSession>; private readonly _onWillNewSession: Emitter<IDebugSession>; private readonly _onDidEndSession: Emitter<{ session: IDebugSession; restart: boolean }>; private readonly restartingSessions = new Set<IDebugSession>(); private debugStorage: DebugStorage; private model: DebugModel; private viewModel: ViewModel; private telemetry: DebugTelemetry; private taskRunner: DebugTaskRunner; private configurationManager: ConfigurationManager; private adapterManager: AdapterManager; private readonly disposables = new DisposableStore(); private debugType!: IContextKey<string>; private debugState!: IContextKey<string>; private inDebugMode!: IContextKey<boolean>; private debugUx!: IContextKey<string>; private hasDebugged!: IContextKey<boolean>; private breakpointsExist!: IContextKey<boolean>; private disassemblyViewFocus!: IContextKey<boolean>; private breakpointsToSendOnResourceSaved: Set<URI>; private initializing = false; private _initializingOptions: IDebugSessionOptions | undefined; private previousState: State | undefined; private sessionCancellationTokens = new Map<string, CancellationTokenSource>(); private activity: IDisposable | undefined; private chosenEnvironments: { [key: string]: string }; private haveDoneLazySetup = false; constructor( @IEditorService private readonly editorService: IEditorService, @IPaneCompositePartService private readonly paneCompositeService: IPaneCompositePartService, @IViewsService private readonly viewsService: IViewsService, @IViewDescriptorService private readonly viewDescriptorService: IViewDescriptorService, @INotificationService private readonly notificationService: INotificationService, @IDialogService private readonly dialogService: IDialogService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @ILifecycleService private readonly lifecycleService: ILifecycleService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IExtensionService private readonly extensionService: IExtensionService, @IFileService private readonly fileService: IFileService, @IConfigurationService private readonly configurationService: IConfigurationService, @IExtensionHostDebugService private readonly extensionHostDebugService: IExtensionHostDebugService, @IActivityService private readonly activityService: IActivityService, @ICommandService private readonly commandService: ICommandService, @IQuickInputService private readonly quickInputService: IQuickInputService, @IWorkspaceTrustRequestService private readonly workspaceTrustRequestService: IWorkspaceTrustRequestService, @IUriIdentityService private readonly uriIdentityService: IUriIdentityService ) { this.breakpointsToSendOnResourceSaved = new Set<URI>(); this._onDidChangeState = new Emitter<State>(); this._onDidNewSession = new Emitter<IDebugSession>(); this._onWillNewSession = new Emitter<IDebugSession>(); this._onDidEndSession = new Emitter(); this.adapterManager = this.instantiationService.createInstance(AdapterManager, { onDidNewSession: this.onDidNewSession }); this.disposables.add(this.adapterManager); this.configurationManager = this.instantiationService.createInstance(ConfigurationManager, this.adapterManager); this.disposables.add(this.configurationManager); this.debugStorage = this.disposables.add(this.instantiationService.createInstance(DebugStorage)); this.chosenEnvironments = this.debugStorage.loadChosenEnvironments(); this.model = this.instantiationService.createInstance(DebugModel, this.debugStorage); this.telemetry = this.instantiationService.createInstance(DebugTelemetry, this.model); this.viewModel = new ViewModel(contextKeyService); this.taskRunner = this.instantiationService.createInstance(DebugTaskRunner); this.disposables.add(this.fileService.onDidFilesChange(e => this.onFileChanges(e))); this.disposables.add(this.lifecycleService.onWillShutdown(this.dispose, this)); this.disposables.add(this.extensionHostDebugService.onAttachSession(event => { const session = this.model.getSession(event.sessionId, true); if (session) { // EH was started in debug mode -> attach to it session.configuration.request = 'attach'; session.configuration.port = event.port; session.setSubId(event.subId); this.launchOrAttachToSession(session); } })); this.disposables.add(this.extensionHostDebugService.onTerminateSession(event => { const session = this.model.getSession(event.sessionId); if (session && session.subId === event.subId) { session.disconnect(); } })); this.disposables.add(this.viewModel.onDidFocusStackFrame(() => { this.onStateChange(); })); this.disposables.add(this.viewModel.onDidFocusSession((session: IDebugSession | undefined) => { this.onStateChange(); if (session) { this.setExceptionBreakpointFallbackSession(session.getId()); } })); this.disposables.add(Event.any(this.adapterManager.onDidRegisterDebugger, this.configurationManager.onDidSelectConfiguration)(() => { const debugUxValue = (this.state !== State.Inactive || (this.configurationManager.getAllConfigurations().length > 0 && this.adapterManager.hasEnabledDebuggers())) ? 'default' : 'simple'; this.debugUx.set(debugUxValue); this.debugStorage.storeDebugUxState(debugUxValue); })); this.disposables.add(this.model.onDidChangeCallStack(() => { const numberOfSessions = this.model.getSessions().filter(s => !s.parentSession).length; this.activity?.dispose(); if (numberOfSessions > 0) { const viewContainer = this.viewDescriptorService.getViewContainerByViewId(CALLSTACK_VIEW_ID); if (viewContainer) { this.activity = this.activityService.showViewContainerActivity(viewContainer.id, { badge: new NumberBadge(numberOfSessions, n => n === 1 ? nls.localize('1activeSession', "1 active session") : nls.localize('nActiveSessions', "{0} active sessions", n)) }); } } })); this.disposables.add(editorService.onDidActiveEditorChange(() => { this.contextKeyService.bufferChangeEvents(() => { if (editorService.activeEditor === DisassemblyViewInput.instance) { this.disassemblyViewFocus.set(true); } else { // This key can be initialized a tick after this event is fired this.disassemblyViewFocus?.reset(); } }); })); this.disposables.add(this.lifecycleService.onBeforeShutdown(() => { for (const editor of editorService.editors) { // Editors will not be valid on window reload, so close them. if (editor.resource?.scheme === DEBUG_MEMORY_SCHEME) { editor.dispose(); } } })); this.initContextKeys(contextKeyService); } private initContextKeys(contextKeyService: IContextKeyService): void { queueMicrotask(() => { contextKeyService.bufferChangeEvents(() => { this.debugType = CONTEXT_DEBUG_TYPE.bindTo(contextKeyService); this.debugState = CONTEXT_DEBUG_STATE.bindTo(contextKeyService); this.hasDebugged = CONTEXT_HAS_DEBUGGED.bindTo(contextKeyService); this.inDebugMode = CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService); this.debugUx = CONTEXT_DEBUG_UX.bindTo(contextKeyService); this.debugUx.set(this.debugStorage.loadDebugUxState()); this.breakpointsExist = CONTEXT_BREAKPOINTS_EXIST.bindTo(contextKeyService); // Need to set disassemblyViewFocus here to make it in the same context as the debug event handlers this.disassemblyViewFocus = CONTEXT_DISASSEMBLY_VIEW_FOCUS.bindTo(contextKeyService); }); const setBreakpointsExistContext = () => this.breakpointsExist.set(!!(this.model.getBreakpoints().length || this.model.getDataBreakpoints().length || this.model.getFunctionBreakpoints().length)); setBreakpointsExistContext(); this.disposables.add(this.model.onDidChangeBreakpoints(() => setBreakpointsExistContext())); }); } getModel(): IDebugModel { return this.model; } getViewModel(): IViewModel { return this.viewModel; } getConfigurationManager(): IConfigurationManager { return this.configurationManager; } getAdapterManager(): IAdapterManager { return this.adapterManager; } sourceIsNotAvailable(uri: uri): void { this.model.sourceIsNotAvailable(uri); } dispose(): void { this.disposables.dispose(); } //---- state management get state(): State { const focusedSession = this.viewModel.focusedSession; if (focusedSession) { return focusedSession.state; } return this.initializing ? State.Initializing : State.Inactive; } get initializingOptions(): IDebugSessionOptions | undefined { return this._initializingOptions; } private startInitializingState(options?: IDebugSessionOptions): void { if (!this.initializing) { this.initializing = true; this._initializingOptions = options; this.onStateChange(); } } private endInitializingState(): void { if (this.initializing) { this.initializing = false; this._initializingOptions = undefined; this.onStateChange(); } } private cancelTokens(id: string | undefined): void { if (id) { const token = this.sessionCancellationTokens.get(id); if (token) { token.cancel(); this.sessionCancellationTokens.delete(id); } } else { this.sessionCancellationTokens.forEach(t => t.cancel()); this.sessionCancellationTokens.clear(); } } private onStateChange(): void { const state = this.state; if (this.previousState !== state) { this.contextKeyService.bufferChangeEvents(() => { this.debugState.set(getStateLabel(state)); this.inDebugMode.set(state !== State.Inactive); // Only show the simple ux if debug is not yet started and if no launch.json exists const debugUxValue = ((state !== State.Inactive && state !== State.Initializing) || (this.adapterManager.hasEnabledDebuggers() && this.configurationManager.selectedConfiguration.name)) ? 'default' : 'simple'; this.debugUx.set(debugUxValue); this.debugStorage.storeDebugUxState(debugUxValue); }); this.previousState = state; this._onDidChangeState.fire(state); } } get onDidChangeState(): Event<State> { return this._onDidChangeState.event; } get onDidNewSession(): Event<IDebugSession> { return this._onDidNewSession.event; } get onWillNewSession(): Event<IDebugSession> { return this._onWillNewSession.event; } get onDidEndSession(): Event<{ session: IDebugSession; restart: boolean }> { return this._onDidEndSession.event; } private lazySetup() { if (!this.haveDoneLazySetup) { // Registering fs providers is slow // https://github.com/microsoft/vscode/issues/159886 this.disposables.add(this.fileService.registerProvider(DEBUG_MEMORY_SCHEME, new DebugMemoryFileSystemProvider(this))); this.haveDoneLazySetup = true; } } //---- life cycle management /** * main entry point * properly manages compounds, checks for errors and handles the initializing state. */ async startDebugging(launch: ILaunch | undefined, configOrName?: IConfig | string, options?: IDebugSessionOptions, saveBeforeStart = !options?.parentSession): Promise<boolean> { const message = options && options.noDebug ? nls.localize('runTrust', "Running executes build tasks and program code from your workspace.") : nls.localize('debugTrust', "Debugging executes build tasks and program code from your workspace."); const trust = await this.workspaceTrustRequestService.requestWorkspaceTrust({ message }); if (!trust) { return false; } this.lazySetup(); this.startInitializingState(options); this.hasDebugged.set(true); try { // make sure to save all files and that the configuration is up to date await this.extensionService.activateByEvent('onDebug'); if (saveBeforeStart) { await saveAllBeforeDebugStart(this.configurationService, this.editorService); } await this.extensionService.whenInstalledExtensionsRegistered(); let config: IConfig | undefined; let compound: ICompound | undefined; if (!configOrName) { configOrName = this.configurationManager.selectedConfiguration.name; } if (typeof configOrName === 'string' && launch) { config = launch.getConfiguration(configOrName); compound = launch.getCompound(configOrName); } else if (typeof configOrName !== 'string') { config = configOrName; } if (compound) { // we are starting a compound debug, first do some error checking and than start each configuration in the compound if (!compound.configurations) { throw new Error(nls.localize({ key: 'compoundMustHaveConfigurations', comment: ['compound indicates a "compounds" configuration item', '"configurations" is an attribute and should not be localized'] }, "Compound must have \"configurations\" attribute set in order to start multiple configurations.")); } if (compound.preLaunchTask) { const taskResult = await this.taskRunner.runTaskAndCheckErrors(launch?.workspace || this.contextService.getWorkspace(), compound.preLaunchTask); if (taskResult === TaskRunResult.Failure) { this.endInitializingState(); return false; } } if (compound.stopAll) { options = { ...options, compoundRoot: new DebugCompoundRoot() }; } const values = await Promise.all(compound.configurations.map(configData => { const name = typeof configData === 'string' ? configData : configData.name; if (name === compound.name) { return Promise.resolve(false); } let launchForName: ILaunch | undefined; if (typeof configData === 'string') { const launchesContainingName = this.configurationManager.getLaunches().filter(l => !!l.getConfiguration(name)); if (launchesContainingName.length === 1) { launchForName = launchesContainingName[0]; } else if (launch && launchesContainingName.length > 1 && launchesContainingName.indexOf(launch) >= 0) { // If there are multiple launches containing the configuration give priority to the configuration in the current launch launchForName = launch; } else { throw new Error(launchesContainingName.length === 0 ? nls.localize('noConfigurationNameInWorkspace', "Could not find launch configuration '{0}' in the workspace.", name) : nls.localize('multipleConfigurationNamesInWorkspace', "There are multiple launch configurations '{0}' in the workspace. Use folder name to qualify the configuration.", name)); } } else if (configData.folder) { const launchesMatchingConfigData = this.configurationManager.getLaunches().filter(l => l.workspace && l.workspace.name === configData.folder && !!l.getConfiguration(configData.name)); if (launchesMatchingConfigData.length === 1) { launchForName = launchesMatchingConfigData[0]; } else { throw new Error(nls.localize('noFolderWithName', "Can not find folder with name '{0}' for configuration '{1}' in compound '{2}'.", configData.folder, configData.name, compound.name)); } } return this.createSession(launchForName, launchForName!.getConfiguration(name), options); })); const result = values.every(success => !!success); // Compound launch is a success only if each configuration launched successfully this.endInitializingState(); return result; } if (configOrName && !config) { const message = !!launch ? nls.localize('configMissing', "Configuration '{0}' is missing in 'launch.json'.", typeof configOrName === 'string' ? configOrName : configOrName.name) : nls.localize('launchJsonDoesNotExist', "'launch.json' does not exist for passed workspace folder."); throw new Error(message); } const result = await this.createSession(launch, config, options); this.endInitializingState(); return result; } catch (err) { // make sure to get out of initializing state, and propagate the result this.notificationService.error(err); this.endInitializingState(); return Promise.reject(err); } } /** * gets the debugger for the type, resolves configurations by providers, substitutes variables and runs prelaunch tasks */ private async createSession(launch: ILaunch | undefined, config: IConfig | undefined, options?: IDebugSessionOptions): Promise<boolean> { // We keep the debug type in a separate variable 'type' so that a no-folder config has no attributes. // Storing the type in the config would break extensions that assume that the no-folder case is indicated by an empty config. let type: string | undefined; if (config) { type = config.type; } else { // a no-folder workspace has no launch.config config = Object.create(null); } if (options && options.noDebug) { config!.noDebug = true; } else if (options && typeof options.noDebug === 'undefined' && options.parentSession && options.parentSession.configuration.noDebug) { config!.noDebug = true; } const unresolvedConfig = deepClone(config); let guess: Debugger | undefined; let activeEditor: EditorInput | undefined; if (!type) { activeEditor = this.editorService.activeEditor; if (activeEditor && activeEditor.resource) { type = this.chosenEnvironments[activeEditor.resource.toString()]; } if (!type) { guess = await this.adapterManager.guessDebugger(false); if (guess) { type = guess.type; } } } const initCancellationToken = new CancellationTokenSource(); const sessionId = generateUuid(); this.sessionCancellationTokens.set(sessionId, initCancellationToken); const configByProviders = await this.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config!, initCancellationToken.token); // a falsy config indicates an aborted launch if (configByProviders && configByProviders.type) { try { let resolvedConfig = await this.substituteVariables(launch, configByProviders); if (!resolvedConfig) { // User cancelled resolving of interactive variables, silently return return false; } if (initCancellationToken.token.isCancellationRequested) { // User cancelled, silently return return false; } const workspace = launch?.workspace || this.contextService.getWorkspace(); const taskResult = await this.taskRunner.runTaskAndCheckErrors(workspace, resolvedConfig.preLaunchTask); if (taskResult === TaskRunResult.Failure) { return false; } const cfg = await this.configurationManager.resolveDebugConfigurationWithSubstitutedVariables(launch && launch.workspace ? launch.workspace.uri : undefined, resolvedConfig.type, resolvedConfig, initCancellationToken.token); if (!cfg) { if (launch && type && cfg === null && !initCancellationToken.token.isCancellationRequested) { // show launch.json only for "config" being "null". await launch.openConfigFile({ preserveFocus: true, type }, initCancellationToken.token); } return false; } resolvedConfig = cfg; const dbg = this.adapterManager.getDebugger(resolvedConfig.type); if (!dbg || (configByProviders.request !== 'attach' && configByProviders.request !== 'launch')) { let message: string; if (configByProviders.request !== 'attach' && configByProviders.request !== 'launch') { message = configByProviders.request ? nls.localize('debugRequestNotSupported', "Attribute '{0}' has an unsupported value '{1}' in the chosen debug configuration.", 'request', configByProviders.request) : nls.localize('debugRequesMissing', "Attribute '{0}' is missing from the chosen debug configuration.", 'request'); } else { message = resolvedConfig.type ? nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", resolvedConfig.type) : nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."); } const actionList: IAction[] = []; actionList.push(new Action( 'installAdditionalDebuggers', nls.localize({ key: 'installAdditionalDebuggers', comment: ['Placeholder is the debug type, so for example "node", "python"'] }, "Install {0} Extension", resolvedConfig.type), undefined, true, async () => this.commandService.executeCommand('debug.installAdditionalDebuggers', resolvedConfig?.type) )); await this.showError(message, actionList); return false; } if (!dbg.enabled) { await this.showError(debuggerDisabledMessage(dbg.type), []); return false; } const result = await this.doCreateSession(sessionId, launch?.workspace, { resolved: resolvedConfig, unresolved: unresolvedConfig }, options); if (result && guess && activeEditor && activeEditor.resource) { // Remeber user choice of environment per active editor to make starting debugging smoother #124770 this.chosenEnvironments[activeEditor.resource.toString()] = guess.type; this.debugStorage.storeChosenEnvironments(this.chosenEnvironments); } return result; } catch (err) { if (err && err.message) { await this.showError(err.message); } else if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) { await this.showError(nls.localize('noFolderWorkspaceDebugError', "The active file can not be debugged. Make sure it is saved and that you have a debug extension installed for that file type.")); } if (launch && !initCancellationToken.token.isCancellationRequested) { await launch.openConfigFile({ preserveFocus: true }, initCancellationToken.token); } return false; } } if (launch && type && configByProviders === null && !initCancellationToken.token.isCancellationRequested) { // show launch.json only for "config" being "null". await launch.openConfigFile({ preserveFocus: true, type }, initCancellationToken.token); } return false; } /** * instantiates the new session, initializes the session, registers session listeners and reports telemetry */ private async doCreateSession(sessionId: string, root: IWorkspaceFolder | undefined, configuration: { resolved: IConfig; unresolved: IConfig | undefined }, options?: IDebugSessionOptions): Promise<boolean> { const session = this.instantiationService.createInstance(DebugSession, sessionId, configuration, root, this.model, options); if (options?.startedByUser && this.model.getSessions().some(s => s.getLabel() === session.getLabel()) && configuration.resolved.suppressMultipleSessionWarning !== true) { // There is already a session with the same name, prompt user #127721 const result = await this.dialogService.confirm({ message: nls.localize('multipleSession', "'{0}' is already running. Do you want to start another instance?", session.getLabel()) }); if (!result.confirmed) { return false; } } this.model.addSession(session); // register listeners as the very first thing! this.registerSessionListeners(session); // since the Session is now properly registered under its ID and hooked, we can announce it // this event doesn't go to extensions this._onWillNewSession.fire(session); const openDebug = this.configurationService.getValue<IDebugConfiguration>('debug').openDebug; // Open debug viewlet based on the visibility of the side bar and openDebug setting. Do not open for 'run without debug' if (!configuration.resolved.noDebug && (openDebug === 'openOnSessionStart' || (openDebug !== 'neverOpen' && this.viewModel.firstSessionStart)) && !session.suppressDebugView) { await this.paneCompositeService.openPaneComposite(VIEWLET_ID, ViewContainerLocation.Sidebar); } try { await this.launchOrAttachToSession(session); const internalConsoleOptions = session.configuration.internalConsoleOptions || this.configurationService.getValue<IDebugConfiguration>('debug').internalConsoleOptions; if (internalConsoleOptions === 'openOnSessionStart' || (this.viewModel.firstSessionStart && internalConsoleOptions === 'openOnFirstSessionStart')) { this.viewsService.openView(REPL_VIEW_ID, false); } this.viewModel.firstSessionStart = false; const showSubSessions = this.configurationService.getValue<IDebugConfiguration>('debug').showSubSessionsInToolBar; const sessions = this.model.getSessions(); const shownSessions = showSubSessions ? sessions : sessions.filter(s => !s.parentSession); if (shownSessions.length > 1) { this.viewModel.setMultiSessionView(true); } // since the initialized response has arrived announce the new Session (including extensions) this._onDidNewSession.fire(session); return true; } catch (error) { if (errors.isCancellationError(error)) { // don't show 'canceled' error messages to the user #7906 return false; } // Show the repl if some error got logged there #5870 if (session && session.getReplElements().length > 0) { this.viewsService.openView(REPL_VIEW_ID, false); } if (session.configuration && session.configuration.request === 'attach' && session.configuration.__autoAttach) { // ignore attach timeouts in auto attach mode return false; } const errorMessage = error instanceof Error ? error.message : error; if (error.showUser !== false) { // Only show the error when showUser is either not defined, or is true #128484 await this.showError(errorMessage, isErrorWithActions(error) ? error.actions : []); } return false; } } private async launchOrAttachToSession(session: IDebugSession, forceFocus = false): Promise<void> { const dbgr = this.adapterManager.getDebugger(session.configuration.type); try { await session.initialize(dbgr!); await session.launchOrAttach(session.configuration); const launchJsonExists = !!session.root && !!this.configurationService.getValue<IGlobalConfig>('launch', { resource: session.root.uri }); await this.telemetry.logDebugSessionStart(dbgr!, launchJsonExists); if (forceFocus || !this.viewModel.focusedSession || (session.parentSession === this.viewModel.focusedSession && session.compact)) { await this.focusStackFrame(undefined, undefined, session); } } catch (err) { if (this.viewModel.focusedSession === session) { await this.focusStackFrame(undefined); } return Promise.reject(err); } } private registerSessionListeners(session: DebugSession): void { const listenerDisposables = new DisposableStore(); this.disposables.add(listenerDisposables); const sessionRunningScheduler = listenerDisposables.add(new RunOnceScheduler(() => { // Do not immediatly defocus the stack frame if the session is running if (session.state === State.Running && this.viewModel.focusedSession === session) { this.viewModel.setFocus(undefined, this.viewModel.focusedThread, session, false); } }, 200)); listenerDisposables.add(session.onDidChangeState(() => { if (session.state === State.Running && this.viewModel.focusedSession === session) { sessionRunningScheduler.schedule(); } if (session === this.viewModel.focusedSession) { this.onStateChange(); } })); listenerDisposables.add(this.onDidEndSession(e => { if (e.session === session && !e.restart) { this.disposables.delete(listenerDisposables); } })); listenerDisposables.add(session.onDidEndAdapter(async adapterExitEvent => { if (adapterExitEvent) { if (adapterExitEvent.error) { this.notificationService.error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly ({0})", adapterExitEvent.error.message || adapterExitEvent.error.toString())); } this.telemetry.logDebugSessionStop(session, adapterExitEvent); } // 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905 const extensionDebugSession = getExtensionHostDebugSession(session); if (extensionDebugSession && extensionDebugSession.state === State.Running && extensionDebugSession.configuration.noDebug) { this.extensionHostDebugService.close(extensionDebugSession.getId()); } if (session.configuration.postDebugTask) { const root = session.root ?? this.contextService.getWorkspace(); try { await this.taskRunner.runTask(root, session.configuration.postDebugTask); } catch (err) { this.notificationService.error(err); } } this.endInitializingState(); this.cancelTokens(session.getId()); if (this.configurationService.getValue<IDebugConfiguration>('debug').closeReadonlyTabsOnEnd) { const editorsToClose = this.editorService.getEditors(EditorsOrder.SEQUENTIAL).filter(({ editor }) => { return editor.resource?.scheme === DEBUG_SCHEME && session.getId() === Source.getEncodedDebugData(editor.resource).sessionId; }); this.editorService.closeEditors(editorsToClose); } this._onDidEndSession.fire({ session, restart: this.restartingSessions.has(session) }); const focusedSession = this.viewModel.focusedSession; if (focusedSession && focusedSession.getId() === session.getId()) { const { session, thread, stackFrame } = getStackFrameThreadAndSessionToFocus(this.model, undefined, undefined, undefined, focusedSession); this.viewModel.setFocus(stackFrame, thread, session, false); } if (this.model.getSessions().length === 0) { this.viewModel.setMultiSessionView(false); if (this.layoutService.isVisible(Parts.SIDEBAR_PART) && this.configurationService.getValue<IDebugConfiguration>('debug').openExplorerOnEnd) { this.paneCompositeService.openPaneComposite(EXPLORER_VIEWLET_ID, ViewContainerLocation.Sidebar); } // Data breakpoints that can not be persisted should be cleared when a session ends const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => !dbp.canPersist); dataBreakpoints.forEach(dbp => this.model.removeDataBreakpoints(dbp.getId())); if (this.configurationService.getValue<IDebugConfiguration>('debug').console.closeOnEnd) { const debugConsoleContainer = this.viewDescriptorService.getViewContainerByViewId(REPL_VIEW_ID); if (debugConsoleContainer && this.viewsService.isViewContainerVisible(debugConsoleContainer.id)) { this.viewsService.closeViewContainer(debugConsoleContainer.id); } } } this.model.removeExceptionBreakpointsForSession(session.getId()); // session.dispose(); TODO@roblourens })); } async restartSession(session: IDebugSession, restartData?: any): Promise<any> { if (session.saveBeforeRestart) { await saveAllBeforeDebugStart(this.configurationService, this.editorService); } const isAutoRestart = !!restartData; const runTasks: () => Promise<TaskRunResult> = async () => { if (isAutoRestart) { // Do not run preLaunch and postDebug tasks for automatic restarts return Promise.resolve(TaskRunResult.Success); } const root = session.root || this.contextService.getWorkspace(); await this.taskRunner.runTask(root, session.configuration.preRestartTask); await this.taskRunner.runTask(root, session.configuration.postDebugTask); const taskResult1 = await this.taskRunner.runTaskAndCheckErrors(root, session.configuration.preLaunchTask); if (taskResult1 !== TaskRunResult.Success) { return taskResult1; } return this.taskRunner.runTaskAndCheckErrors(root, session.configuration.postRestartTask); }; const extensionDebugSession = getExtensionHostDebugSession(session); if (extensionDebugSession) { const taskResult = await runTasks(); if (taskResult === TaskRunResult.Success) { this.extensionHostDebugService.reload(extensionDebugSession.getId()); } return; } // Read the configuration again if a launch.json has been changed, if not just use the inmemory configuration let needsToSubstitute = false; let unresolved: IConfig | undefined; const launch = session.root ? this.configurationManager.getLaunch(session.root.uri) : undefined; if (launch) { unresolved = launch.getConfiguration(session.configuration.name); if (unresolved && !equals(unresolved, session.unresolvedConfiguration)) { // Take the type from the session since the debug extension might overwrite it #21316 unresolved.type = session.configuration.type; unresolved.noDebug = session.configuration.noDebug; needsToSubstitute = true; } } let resolved: IConfig | undefined | null = session.configuration; if (launch && needsToSubstitute && unresolved) { const initCancellationToken = new CancellationTokenSource(); this.sessionCancellationTokens.set(session.getId(), initCancellationToken); const resolvedByProviders = await this.configurationManager.resolveConfigurationByProviders(launch.workspace ? launch.workspace.uri : undefined, unresolved.type, unresolved, initCancellationToken.token); if (resolvedByProviders) { resolved = await this.substituteVariables(launch, resolvedByProviders); if (resolved && !initCancellationToken.token.isCancellationRequested) { resolved = await this.configurationManager.resolveDebugConfigurationWithSubstitutedVariables(launch && launch.workspace ? launch.workspace.uri : undefined, unresolved.type, resolved, initCancellationToken.token); } } else { resolved = resolvedByProviders; } } if (resolved) { session.setConfiguration({ resolved, unresolved }); } session.configuration.__restart = restartData; const doRestart = async (fn: () => Promise<boolean | undefined>) => { this.restartingSessions.add(session); let didRestart = false; try { didRestart = (await fn()) !== false; } catch (e) { didRestart = false; throw e; } finally { this.restartingSessions.delete(session); // we previously may have issued an onDidEndSession with restart: true, // assuming the adapter exited (in `registerSessionListeners`). But the // restart failed, so emit the final termination now. if (!didRestart) { this._onDidEndSession.fire({ session, restart: false }); } } }; if (session.capabilities.supportsRestartRequest) { const taskResult = await runTasks(); if (taskResult === TaskRunResult.Success) { await doRestart(async () => { await session.restart(); return true; }); } return; } const shouldFocus = !!this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId(); return doRestart(async () => { // If the restart is automatic -> disconnect, otherwise -> terminate #55064 if (isAutoRestart) { await session.disconnect(true); } else { await session.terminate(true); } return new Promise<boolean>((c, e) => { setTimeout(async () => { const taskResult = await runTasks(); if (taskResult !== TaskRunResult.Success) { return c(false); } if (!resolved) { return c(false); } try { await this.launchOrAttachToSession(session, shouldFocus); this._onDidNewSession.fire(session); c(true); } catch (error) { e(error); } }, 300); }); }); } async stopSession(session: IDebugSession | undefined, disconnect = false, suspend = false): Promise<any> { if (session) { return disconnect ? session.disconnect(undefined, suspend) : session.terminate(); } const sessions = this.model.getSessions(); if (sessions.length === 0) { this.taskRunner.cancel(); // User might have cancelled starting of a debug session, and in some cases the quick pick is left open await this.quickInputService.cancel(); this.endInitializingState(); this.cancelTokens(undefined); } return Promise.all(sessions.map(s => disconnect ? s.disconnect(undefined, suspend) : s.terminate())); } private async substituteVariables(launch: ILaunch | undefined, config: IConfig): Promise<IConfig | undefined> { const dbg = this.adapterManager.getDebugger(config.type); if (dbg) { let folder: IWorkspaceFolder | undefined = undefined; if (launch && launch.workspace) { folder = launch.workspace; } else { const folders = this.contextService.getWorkspace().folders; if (folders.length === 1) { folder = folders[0]; } } try { return await dbg.substituteVariables(folder, config); } catch (err) { this.showError(err.message, undefined, !!launch?.getConfiguration(config.name)); return undefined; // bail out } } return Promise.resolve(config); } private async showError(message: string, errorActions: ReadonlyArray<IAction> = [], promptLaunchJson = true): Promise<void> { const configureAction = new Action(DEBUG_CONFIGURE_COMMAND_ID, DEBUG_CONFIGURE_LABEL, undefined, true, () => this.commandService.executeCommand(DEBUG_CONFIGURE_COMMAND_ID)); // Don't append the standard command if id of any provided action indicates it is a command const actions = errorActions.filter((action) => action.id.endsWith('.command')).length > 0 ? errorActions : [...errorActions, ...(promptLaunchJson ? [configureAction] : [])]; await this.dialogService.prompt({ type: severity.Error, message, buttons: actions.map(action => ({ label: action.label, run: () => action.run() })), cancelButton: true }); } //---- focus management async focusStackFrame(_stackFrame: IStackFrame | undefined, _thread?: IThread, _session?: IDebugSession, options?: { explicit?: boolean; preserveFocus?: boolean; sideBySide?: boolean; pinned?: boolean }): Promise<void> { const { stackFrame, thread, session } = getStackFrameThreadAndSessionToFocus(this.model, _stackFrame, _thread, _session); if (stackFrame) { const editor = await stackFrame.openInEditor(this.editorService, options?.preserveFocus ?? true, options?.sideBySide, options?.pinned); if (editor) { if (editor.input === DisassemblyViewInput.instance) { // Go to address is invoked via setFocus } else { const control = editor.getControl(); if (stackFrame && isCodeEditor(control) && control.hasModel()) { const model = control.getModel(); const lineNumber = stackFrame.range.startLineNumber; if (lineNumber >= 1 && lineNumber <= model.getLineCount()) { const lineContent = control.getModel().getLineContent(lineNumber); aria.alert(nls.localize({ key: 'debuggingPaused', comment: ['First placeholder is the file line content, second placeholder is the reason why debugging is stopped, for example "breakpoint", third is the stack frame name, and last is the line number.'] }, "{0}, debugging paused {1}, {2}:{3}", lineContent, thread && thread.stoppedDetails ? `, reason ${thread.stoppedDetails.reason}` : '', stackFrame.source ? stackFrame.source.name : '', stackFrame.range.startLineNumber)); } } } } } if (session) { this.debugType.set(session.configuration.type); } else { this.debugType.reset(); } this.viewModel.setFocus(stackFrame, thread, session, !!options?.explicit); } //---- watches addWatchExpression(name?: string): void { const we = this.model.addWatchExpression(name); if (!name) { this.viewModel.setSelectedExpression(we, false); } this.debugStorage.storeWatchExpressions(this.model.getWatchExpressions()); } renameWatchExpression(id: string, newName: string): void { this.model.renameWatchExpression(id, newName); this.debugStorage.storeWatchExpressions(this.model.getWatchExpressions()); } moveWatchExpression(id: string, position: number): void { this.model.moveWatchExpression(id, position); this.debugStorage.storeWatchExpressions(this.model.getWatchExpressions()); } removeWatchExpressions(id?: string): void { this.model.removeWatchExpressions(id); this.debugStorage.storeWatchExpressions(this.model.getWatchExpressions()); } //---- breakpoints canSetBreakpointsIn(model: ITextModel): boolean { return this.adapterManager.canSetBreakpointsIn(model); } async enableOrDisableBreakpoints(enable: boolean, breakpoint?: IEnablement): Promise<void> { if (breakpoint) { this.model.setEnablement(breakpoint, enable); this.debugStorage.storeBreakpoints(this.model); if (breakpoint instanceof Breakpoint) { await this.makeTriggeredBreakpointsMatchEnablement(enable, breakpoint); await this.sendBreakpoints(breakpoint.originalUri); } else if (breakpoint instanceof FunctionBreakpoint) { await this.sendFunctionBreakpoints(); } else if (breakpoint instanceof DataBreakpoint) { await this.sendDataBreakpoints(); } else if (breakpoint instanceof InstructionBreakpoint) { await this.sendInstructionBreakpoints(); } else { await this.sendExceptionBreakpoints(); } } else { this.model.enableOrDisableAllBreakpoints(enable); this.debugStorage.storeBreakpoints(this.model); await this.sendAllBreakpoints(); } this.debugStorage.storeBreakpoints(this.model); } async addBreakpoints(uri: uri, rawBreakpoints: IBreakpointData[], ariaAnnounce = true): Promise<IBreakpoint[]> { const breakpoints = this.model.addBreakpoints(uri, rawBreakpoints); if (ariaAnnounce) { breakpoints.forEach(bp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", bp.lineNumber, uri.fsPath))); } // In some cases we need to store breakpoints before we send them because sending them can take a long time // And after sending them because the debug adapter can attach adapter data to a breakpoint this.debugStorage.storeBreakpoints(this.model); await this.sendBreakpoints(uri); this.debugStorage.storeBreakpoints(this.model); return breakpoints; } async updateBreakpoints(uri: uri, data: Map<string, IBreakpointUpdateData>, sendOnResourceSaved: boolean): Promise<void> { this.model.updateBreakpoints(data); this.debugStorage.storeBreakpoints(this.model); if (sendOnResourceSaved) { this.breakpointsToSendOnResourceSaved.add(uri); } else { await this.sendBreakpoints(uri); this.debugStorage.storeBreakpoints(this.model); } } async removeBreakpoints(id?: string): Promise<void> { const breakpoints = this.model.getBreakpoints(); const toRemove = breakpoints.filter(bp => !id || bp.getId() === id); // note: using the debugger-resolved uri for aria to reflect UI state toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.uri.fsPath))); const urisToClear = new Set(toRemove.map(bp => bp.originalUri.toString())); this.model.removeBreakpoints(toRemove); this.unlinkTriggeredBreakpoints(breakpoints, toRemove).forEach(uri => urisToClear.add(uri.toString())); this.debugStorage.storeBreakpoints(this.model); await Promise.all([...urisToClear].map(uri => this.sendBreakpoints(URI.parse(uri)))); } setBreakpointsActivated(activated: boolean): Promise<void> { this.model.setBreakpointsActivated(activated); return this.sendAllBreakpoints(); } addFunctionBreakpoint(name?: string, id?: string): void { this.model.addFunctionBreakpoint(name || '', id); } async updateFunctionBreakpoint(id: string, update: { name?: string; hitCondition?: string; condition?: string }): Promise<void> { this.model.updateFunctionBreakpoint(id, update); this.debugStorage.storeBreakpoints(this.model); await this.sendFunctionBreakpoints(); } async removeFunctionBreakpoints(id?: string): Promise<void> { this.model.removeFunctionBreakpoints(id); this.debugStorage.storeBreakpoints(this.model); await this.sendFunctionBreakpoints(); } async addDataBreakpoint(label: string, dataId: string, canPersist: boolean, accessTypes: DebugProtocol.DataBreakpointAccessType[] | undefined, accessType: DebugProtocol.DataBreakpointAccessType): Promise<void> { this.model.addDataBreakpoint(label, dataId, canPersist, accessTypes, accessType); this.debugStorage.storeBreakpoints(this.model); await this.sendDataBreakpoints(); this.debugStorage.storeBreakpoints(this.model); } async updateDataBreakpoint(id: string, update: { hitCondition?: string; condition?: string }): Promise<void> { this.model.updateDataBreakpoint(id, update); this.debugStorage.storeBreakpoints(this.model); await this.sendDataBreakpoints(); } async removeDataBreakpoints(id?: string): Promise<void> { this.model.removeDataBreakpoints(id); this.debugStorage.storeBreakpoints(this.model); await this.sendDataBreakpoints(); } async addInstructionBreakpoint(instructionReference: string, offset: number, address: bigint, condition?: string, hitCondition?: string): Promise<void> { this.model.addInstructionBreakpoint(instructionReference, offset, address, condition, hitCondition); this.debugStorage.storeBreakpoints(this.model); await this.sendInstructionBreakpoints(); this.debugStorage.storeBreakpoints(this.model); } async removeInstructionBreakpoints(instructionReference?: string, offset?: number): Promise<void> { this.model.removeInstructionBreakpoints(instructionReference, offset); this.debugStorage.storeBreakpoints(this.model); await this.sendInstructionBreakpoints(); } setExceptionBreakpointFallbackSession(sessionId: string) { this.model.setExceptionBreakpointFallbackSession(sessionId); this.debugStorage.storeBreakpoints(this.model); } setExceptionBreakpointsForSession(session: IDebugSession, data: DebugProtocol.ExceptionBreakpointsFilter[]): void { this.model.setExceptionBreakpointsForSession(session.getId(), data); this.debugStorage.storeBreakpoints(this.model); } async setExceptionBreakpointCondition(exceptionBreakpoint: IExceptionBreakpoint, condition: string | undefined): Promise<void> { this.model.setExceptionBreakpointCondition(exceptionBreakpoint, condition); this.debugStorage.storeBreakpoints(this.model); await this.sendExceptionBreakpoints(); } async sendAllBreakpoints(session?: IDebugSession): Promise<any> { const setBreakpointsPromises = distinct(this.model.getBreakpoints(), bp => bp.originalUri.toString()) .map(bp => this.sendBreakpoints(bp.originalUri, false, session)); // If sending breakpoints to one session which we know supports the configurationDone request, can make all requests in parallel if (session?.capabilities.supportsConfigurationDoneRequest) { await Promise.all([ ...setBreakpointsPromises, this.sendFunctionBreakpoints(session), this.sendDataBreakpoints(session), this.sendInstructionBreakpoints(session), this.sendExceptionBreakpoints(session), ]); } else { await Promise.all(setBreakpointsPromises); await this.sendFunctionBreakpoints(session); await this.sendDataBreakpoints(session); await this.sendInstructionBreakpoints(session); // send exception breakpoints at the end since some debug adapters may rely on the order - this was the case before // the configurationDone request was introduced. await this.sendExceptionBreakpoints(session); } } /** * Removes the condition of triggered breakpoints that depended on * breakpoints in `removedBreakpoints`. Returns the URIs of resources that * had their breakpoints changed in this way. */ private unlinkTriggeredBreakpoints(allBreakpoints: readonly IBreakpoint[], removedBreakpoints: readonly IBreakpoint[]): uri[] { const affectedUris: uri[] = []; for (const removed of removedBreakpoints) { for (const existing of allBreakpoints) { if (!removedBreakpoints.includes(existing) && existing.triggeredBy === removed.getId()) { this.model.updateBreakpoints(new Map([[existing.getId(), { triggeredBy: undefined }]])); affectedUris.push(existing.originalUri); } } } return affectedUris; } private async makeTriggeredBreakpointsMatchEnablement(enable: boolean, breakpoint: Breakpoint) { if (enable) { /** If the breakpoint is being enabled, also ensure its triggerer is enabled */ if (breakpoint.triggeredBy) { const trigger = this.model.getBreakpoints().find(bp => breakpoint.triggeredBy === bp.getId()); if (trigger && !trigger.enabled) { await this.enableOrDisableBreakpoints(enable, trigger); } } } /** Makes its triggeree states match the state of this breakpoint */ await Promise.all(this.model.getBreakpoints() .filter(bp => bp.triggeredBy === breakpoint.getId() && bp.enabled !== enable) .map(bp => this.enableOrDisableBreakpoints(enable, bp)) ); } public async sendBreakpoints(modelUri: uri, sourceModified = false, session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getBreakpoints({ originalUri: modelUri, enabledOnly: true }); await sendToOneOrAllSessions(this.model, session, async s => { if (!s.configuration.noDebug) { const sessionBps = breakpointsToSend.filter(bp => !bp.triggeredBy || bp.getSessionDidTrigger(s.getId())); await s.sendBreakpoints(modelUri, sessionBps, sourceModified); } }); } private async sendFunctionBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); await sendToOneOrAllSessions(this.model, session, async s => { if (s.capabilities.supportsFunctionBreakpoints && !s.configuration.noDebug) { await s.sendFunctionBreakpoints(breakpointsToSend); } }); } private async sendDataBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getDataBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); await sendToOneOrAllSessions(this.model, session, async s => { if (s.capabilities.supportsDataBreakpoints && !s.configuration.noDebug) { await s.sendDataBreakpoints(breakpointsToSend); } }); } private async sendInstructionBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getInstructionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); await sendToOneOrAllSessions(this.model, session, async s => { if (s.capabilities.supportsInstructionBreakpoints && !s.configuration.noDebug) { await s.sendInstructionBreakpoints(breakpointsToSend); } }); } private sendExceptionBreakpoints(session?: IDebugSession): Promise<void> { return sendToOneOrAllSessions(this.model, session, async s => { const enabledExceptionBps = this.model.getExceptionBreakpointsForSession(s.getId()).filter(exb => exb.enabled); if (s.capabilities.supportsConfigurationDoneRequest && (!s.capabilities.exceptionBreakpointFilters || s.capabilities.exceptionBreakpointFilters.length === 0)) { // Only call `setExceptionBreakpoints` as specified in dap protocol #90001 return; } if (!s.configuration.noDebug) { await s.sendExceptionBreakpoints(enabledExceptionBps); } }); } private onFileChanges(fileChangesEvent: FileChangesEvent): void { const toRemove = this.model.getBreakpoints().filter(bp => fileChangesEvent.contains(bp.originalUri, FileChangeType.DELETED)); if (toRemove.length) { this.model.removeBreakpoints(toRemove); } const toSend: URI[] = []; for (const uri of this.breakpointsToSendOnResourceSaved) { if (fileChangesEvent.contains(uri, FileChangeType.UPDATED)) { toSend.push(uri); } } for (const uri of toSend) { this.breakpointsToSendOnResourceSaved.delete(uri); this.sendBreakpoints(uri, true); } } async runTo(uri: uri, lineNumber: number, column?: number): Promise<void> { let breakpointToRemove: IBreakpoint | undefined; let threadToContinue = this.getViewModel().focusedThread; const addTempBreakPoint = async () => { const bpExists = !!(this.getModel().getBreakpoints({ column, lineNumber, uri }).length); if (!bpExists) { const addResult = await this.addAndValidateBreakpoints(uri, lineNumber, column); if (addResult.thread) { threadToContinue = addResult.thread; } if (addResult.breakpoint) { breakpointToRemove = addResult.breakpoint; } } return { threadToContinue, breakpointToRemove }; }; const removeTempBreakPoint = (state: State): boolean => { if (state === State.Stopped || state === State.Inactive) { if (breakpointToRemove) { this.removeBreakpoints(breakpointToRemove.getId()); } return true; } return false; }; await addTempBreakPoint(); if (this.state === State.Inactive) { // If no session exists start the debugger const { launch, name, getConfig } = this.getConfigurationManager().selectedConfiguration; const config = await getConfig(); const configOrName = config ? Object.assign(deepClone(config), {}) : name; const listener = this.onDidChangeState(state => { if (removeTempBreakPoint(state)) { listener.dispose(); } }); await this.startDebugging(launch, configOrName, undefined, true); } if (this.state === State.Stopped) { const focusedSession = this.getViewModel().focusedSession; if (!focusedSession || !threadToContinue) { return; } const listener = threadToContinue.session.onDidChangeState(() => { if (removeTempBreakPoint(focusedSession.state)) { listener.dispose(); } }); await threadToContinue.continue(); } } private async addAndValidateBreakpoints(uri: URI, lineNumber: number, column?: number) { const debugModel = this.getModel(); const viewModel = this.getViewModel(); const breakpoints = await this.addBreakpoints(uri, [{ lineNumber, column }], false); const breakpoint = breakpoints?.[0]; if (!breakpoint) { return { breakpoint: undefined, thread: viewModel.focusedThread }; } // If the breakpoint was not initially verified, wait up to 2s for it to become so. // Inherently racey if multiple sessions can verify async, but not solvable... if (!breakpoint.verified) { let listener: IDisposable; await raceTimeout(new Promise<void>(resolve => { listener = debugModel.onDidChangeBreakpoints(() => { if (breakpoint.verified) { resolve(); } }); }), 2000); listener!.dispose(); } // Look at paused threads for sessions that verified this bp. Prefer, in order: const enum Score { /** The focused thread */ Focused, /** Any other stopped thread of a session that verified the bp */ Verified, /** Any thread that verified and paused in the same file */ VerifiedAndPausedInFile, /** The focused thread if it verified the breakpoint */ VerifiedAndFocused, } let bestThread = viewModel.focusedThread; let bestScore = Score.Focused; for (const sessionId of breakpoint.sessionsThatVerified) { const session = debugModel.getSession(sessionId); if (!session) { continue; } const threads = session.getAllThreads().filter(t => t.stopped); if (bestScore < Score.VerifiedAndFocused) { if (viewModel.focusedThread && threads.includes(viewModel.focusedThread)) { bestThread = viewModel.focusedThread; bestScore = Score.VerifiedAndFocused; } } if (bestScore < Score.VerifiedAndPausedInFile) { const pausedInThisFile = threads.find(t => { const top = t.getTopStackFrame(); return top && this.uriIdentityService.extUri.isEqual(top.source.uri, uri); }); if (pausedInThisFile) { bestThread = pausedInThisFile; bestScore = Score.VerifiedAndPausedInFile; } } if (bestScore < Score.Verified) { bestThread = threads[0]; bestScore = Score.VerifiedAndPausedInFile; } } return { thread: bestThread, breakpoint }; } } export function getStackFrameThreadAndSessionToFocus(model: IDebugModel, stackFrame: IStackFrame | undefined, thread?: IThread, session?: IDebugSession, avoidSession?: IDebugSession): { stackFrame: IStackFrame | undefined; thread: IThread | undefined; session: IDebugSession | undefined } { if (!session) { if (stackFrame || thread) { session = stackFrame ? stackFrame.thread.session : thread!.session; } else { const sessions = model.getSessions(); const stoppedSession = sessions.find(s => s.state === State.Stopped); // Make sure to not focus session that is going down session = stoppedSession || sessions.find(s => s !== avoidSession && s !== avoidSession?.parentSession) || (sessions.length ? sessions[0] : undefined); } } if (!thread) { if (stackFrame) { thread = stackFrame.thread; } else { const threads = session ? session.getAllThreads() : undefined; const stoppedThread = threads && threads.find(t => t.stopped); thread = stoppedThread || (threads && threads.length ? threads[0] : undefined); } } if (!stackFrame && thread) { stackFrame = thread.getTopStackFrame(); } return { session, thread, stackFrame }; } async function sendToOneOrAllSessions(model: DebugModel, session: IDebugSession | undefined, send: (session: IDebugSession) => Promise<void>): Promise<void> { if (session) { await send(session); } else { await Promise.all(model.getSessions().map(s => send(s))); } }
src/vs/workbench/contrib/debug/browser/debugService.ts
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.0009049203945323825, 0.0001731386291794479, 0.0001618236128706485, 0.0001677820400800556, 0.00006126141670392826 ]
{ "id": 0, "code_window": [ "\n", " - ${{ if eq(parameters.VSCODE_BUILD_ALPINE_ARM64, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: vscode_cli_alpine_arm64_cli\n", "\n", " - ${{ if eq(parameters.VSCODE_BUILD_ALPINE, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}\n" ], "file_path": "build/azure-pipelines/alpine/cli-build-alpine.yml", "type": "add", "edit_start_line_idx": 95 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { workspace, extensions, Uri, EventEmitter, Disposable } from 'vscode'; import { Utils } from 'vscode-uri'; export function getCustomDataSource(toDispose: Disposable[]) { let pathsInWorkspace = getCustomDataPathsInAllWorkspaces(); let pathsInExtensions = getCustomDataPathsFromAllExtensions(); const onChange = new EventEmitter<void>(); toDispose.push(extensions.onDidChange(_ => { const newPathsInExtensions = getCustomDataPathsFromAllExtensions(); if (newPathsInExtensions.length !== pathsInExtensions.length || !newPathsInExtensions.every((val, idx) => val === pathsInExtensions[idx])) { pathsInExtensions = newPathsInExtensions; onChange.fire(); } })); toDispose.push(workspace.onDidChangeConfiguration(e => { if (e.affectsConfiguration('css.customData')) { pathsInWorkspace = getCustomDataPathsInAllWorkspaces(); onChange.fire(); } })); return { get uris() { return pathsInWorkspace.concat(pathsInExtensions); }, get onDidChange() { return onChange.event; } }; } function getCustomDataPathsInAllWorkspaces(): string[] { const workspaceFolders = workspace.workspaceFolders; const dataPaths: string[] = []; if (!workspaceFolders) { return dataPaths; } const collect = (paths: string[] | undefined, rootFolder: Uri) => { if (Array.isArray(paths)) { for (const path of paths) { if (typeof path === 'string') { dataPaths.push(Utils.resolvePath(rootFolder, path).toString()); } } } }; for (let i = 0; i < workspaceFolders.length; i++) { const folderUri = workspaceFolders[i].uri; const allCssConfig = workspace.getConfiguration('css', folderUri); const customDataInspect = allCssConfig.inspect<string[]>('customData'); if (customDataInspect) { collect(customDataInspect.workspaceFolderValue, folderUri); if (i === 0) { if (workspace.workspaceFile) { collect(customDataInspect.workspaceValue, workspace.workspaceFile); } collect(customDataInspect.globalValue, folderUri); } } } return dataPaths; } function getCustomDataPathsFromAllExtensions(): string[] { const dataPaths: string[] = []; for (const extension of extensions.all) { const customData = extension.packageJSON?.contributes?.css?.customData; if (Array.isArray(customData)) { for (const rp of customData) { dataPaths.push(Utils.joinPath(extension.extensionUri, rp).toString()); } } } return dataPaths; }
extensions/css-language-features/client/src/customData.ts
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.00018314657791052014, 0.000170087005244568, 0.00016406823124270886, 0.0001687439507804811, 0.000005239209713181481 ]
{ "id": 0, "code_window": [ "\n", " - ${{ if eq(parameters.VSCODE_BUILD_ALPINE_ARM64, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: vscode_cli_alpine_arm64_cli\n", "\n", " - ${{ if eq(parameters.VSCODE_BUILD_ALPINE, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}\n" ], "file_path": "build/azure-pipelines/alpine/cli-build-alpine.yml", "type": "add", "edit_start_line_idx": 95 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { LazyStatefulPromise, raceTimeout } from 'vs/base/common/async'; import { BugIndicatingError, onUnexpectedError } from 'vs/base/common/errors'; import { Emitter, Event } from 'vs/base/common/event'; import { IMarkdownString } from 'vs/base/common/htmlContent'; import { Disposable, DisposableStore, IDisposable, IReference, toDisposable } from 'vs/base/common/lifecycle'; import { parse } from 'vs/base/common/marshalling'; import { Schemas } from 'vs/base/common/network'; import { deepClone } from 'vs/base/common/objects'; import { autorun, derived, observableFromEvent } from 'vs/base/common/observable'; import { constObservable, mapObservableArrayCached } from 'vs/base/common/observableInternal/utils'; import { ThemeIcon } from 'vs/base/common/themables'; import { isDefined, isObject } from 'vs/base/common/types'; import { URI } from 'vs/base/common/uri'; import { ConstLazyPromise, IDocumentDiffItem, IMultiDiffEditorModel, LazyPromise } from 'vs/editor/browser/widget/multiDiffEditorWidget/model'; import { MultiDiffEditorViewModel } from 'vs/editor/browser/widget/multiDiffEditorWidget/multiDiffEditorViewModel'; import { IDiffEditorOptions } from 'vs/editor/common/config/editorOptions'; import { IResolvedTextEditorModel, ITextModelService } from 'vs/editor/common/services/resolverService'; import { ITextResourceConfigurationService } from 'vs/editor/common/services/textResourceConfiguration'; import { localize } from 'vs/nls'; import { ConfirmResult } from 'vs/platform/dialogs/common/dialogs'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IEditorConfiguration } from 'vs/workbench/browser/parts/editor/textEditor'; import { DEFAULT_EDITOR_ASSOCIATION, EditorInputCapabilities, EditorInputWithOptions, GroupIdentifier, IEditorSerializer, IResourceMultiDiffEditorInput, IRevertOptions, ISaveOptions, IUntypedEditorInput } from 'vs/workbench/common/editor'; import { EditorInput, IEditorCloseHandler } from 'vs/workbench/common/editor/editorInput'; import { MultiDiffEditorIcon } from 'vs/workbench/contrib/multiDiffEditor/browser/icons.contribution'; import { ConstResolvedMultiDiffSource, IMultiDiffSourceResolverService, IResolvedMultiDiffSource, MultiDiffEditorItem } from 'vs/workbench/contrib/multiDiffEditor/browser/multiDiffSourceResolverService'; import { ObservableLazyStatefulPromise } from 'vs/workbench/contrib/multiDiffEditor/browser/utils'; import { IEditorResolverService, RegisteredEditorPriority } from 'vs/workbench/services/editor/common/editorResolverService'; import { ILanguageSupport, ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; /* hot-reload:patch-prototype-methods */ export class MultiDiffEditorInput extends EditorInput implements ILanguageSupport { public static fromResourceMultiDiffEditorInput(input: IResourceMultiDiffEditorInput, instantiationService: IInstantiationService): MultiDiffEditorInput { if (!input.multiDiffSource && !input.resources) { throw new BugIndicatingError('MultiDiffEditorInput requires either multiDiffSource or resources'); } const multiDiffSource = input.multiDiffSource ?? URI.parse(`multi-diff-editor:${new Date().getMilliseconds().toString() + Math.random().toString()}`); return instantiationService.createInstance( MultiDiffEditorInput, multiDiffSource, input.label, input.resources?.map(resource => { return new MultiDiffEditorItem( resource.original.resource, resource.modified.resource, ); }), ); } public static fromSerialized(data: ISerializedMultiDiffEditorInput, instantiationService: IInstantiationService): MultiDiffEditorInput { return instantiationService.createInstance( MultiDiffEditorInput, URI.parse(data.multiDiffSourceUri), data.label, data.resources?.map(resource => new MultiDiffEditorItem( resource.originalUri ? URI.parse(resource.originalUri) : undefined, resource.modifiedUri ? URI.parse(resource.modifiedUri) : undefined, )) ); } static readonly ID: string = 'workbench.input.multiDiffEditor'; get resource(): URI | undefined { return this.multiDiffSource; } override get capabilities(): EditorInputCapabilities { return EditorInputCapabilities.Readonly; } override get typeId(): string { return MultiDiffEditorInput.ID; } private _name: string = ''; override getName(): string { return this._name; } override get editorId(): string { return DEFAULT_EDITOR_ASSOCIATION.id; } override getIcon(): ThemeIcon { return MultiDiffEditorIcon; } constructor( public readonly multiDiffSource: URI, public readonly label: string | undefined, public readonly initialResources: readonly MultiDiffEditorItem[] | undefined, @ITextModelService private readonly _textModelService: ITextModelService, @ITextResourceConfigurationService private readonly _textResourceConfigurationService: ITextResourceConfigurationService, @IInstantiationService private readonly _instantiationService: IInstantiationService, @IMultiDiffSourceResolverService private readonly _multiDiffSourceResolverService: IMultiDiffSourceResolverService, @ITextFileService private readonly _textFileService: ITextFileService, ) { super(); this._register(autorun((reader) => { /** @description Updates name */ const resources = this._resources.read(reader) ?? []; const label = this.label ?? localize('name', "Multi Diff Editor"); this._name = label + localize('files', " ({0} files)", resources?.length ?? 0); this._onDidChangeLabel.fire(); })); } public serialize(): ISerializedMultiDiffEditorInput { return { label: this.label, multiDiffSourceUri: this.multiDiffSource.toString(), resources: this.initialResources?.map(resource => ({ originalUri: resource.original?.toString(), modifiedUri: resource.modified?.toString(), })), }; } public setLanguageId(languageId: string, source?: string | undefined): void { const activeDiffItem = this._viewModel.requireValue().activeDiffItem.get(); const value = activeDiffItem?.entry?.value; if (!value) { return; } const target = value.modified ?? value.original; if (!target) { return; } target.setLanguage(languageId, source); } public async getViewModel(): Promise<MultiDiffEditorViewModel> { return this._viewModel.getPromise(); } private readonly _viewModel = new LazyStatefulPromise(async () => { const model = await this._createModel(); this._register(model); const vm = new MultiDiffEditorViewModel(model, this._instantiationService); this._register(vm); await raceTimeout(vm.waitForDiffs(), 1000); return vm; }); private async _createModel(): Promise<IMultiDiffEditorModel & IDisposable> { const source = await this._resolvedSource.getValue(); const textResourceConfigurationService = this._textResourceConfigurationService; // Enables delayed disposing const garbage = new DisposableStore(); const documentsWithPromises = mapObservableArrayCached(undefined, source.resources, async (r, store) => { /** @description documentsWithPromises */ let original: IReference<IResolvedTextEditorModel> | undefined; let modified: IReference<IResolvedTextEditorModel> | undefined; const store2 = new DisposableStore(); store.add(toDisposable(() => { // Mark the text model references as garbage when they get stale (don't dispose them yet) garbage.add(store2); })); try { [original, modified] = await Promise.all([ r.original ? this._textModelService.createModelReference(r.original) : undefined, r.modified ? this._textModelService.createModelReference(r.modified) : undefined, ]); if (original) { store.add(original); } if (modified) { store.add(modified); } } catch (e) { // e.g. "File seems to be binary and cannot be opened as text" console.error(e); onUnexpectedError(e); return undefined; } const uri = (r.modified ?? r.original)!; return new ConstLazyPromise<IDocumentDiffItem>({ original: original?.object.textEditorModel, modified: modified?.object.textEditorModel, get options() { return { ...getReadonlyConfiguration(modified?.object.isReadonly() ?? true), ...computeOptions(textResourceConfigurationService.getValue(uri)), } satisfies IDiffEditorOptions; }, onOptionsDidChange: h => this._textResourceConfigurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration(uri, 'editor') || e.affectsConfiguration(uri, 'diffEditor')) { h(); } }), }); }, i => JSON.stringify([i.modified?.toString(), i.original?.toString()])); let documents: readonly LazyPromise<IDocumentDiffItem>[] = []; const documentChangeEmitter = new Emitter<void>(); const p = Event.toPromise(documentChangeEmitter.event); const a = autorun(async reader => { /** @description Update documents */ const docsPromises = documentsWithPromises.read(reader); const docs = await Promise.all(docsPromises); documents = docs.filter(isDefined); documentChangeEmitter.fire(); garbage.clear(); // Only dispose text models after the documents have been updated }); await p; return { dispose: () => { a.dispose(); garbage.dispose(); }, onDidChange: documentChangeEmitter.event, get documents() { return documents; }, contextKeys: source.source?.contextKeys, }; } private readonly _resolvedSource = new ObservableLazyStatefulPromise(async () => { const source: IResolvedMultiDiffSource | undefined = this.initialResources ? new ConstResolvedMultiDiffSource(this.initialResources) : await this._multiDiffSourceResolverService.resolve(this.multiDiffSource); return { source, resources: source ? observableFromEvent(source.onDidChange, () => source.resources) : constObservable([]), }; }); override matches(otherInput: EditorInput | IUntypedEditorInput): boolean { if (super.matches(otherInput)) { return true; } if (otherInput instanceof MultiDiffEditorInput) { return this.multiDiffSource.toString() === otherInput.multiDiffSource.toString(); } return false; } private readonly _resources = derived(this, reader => this._resolvedSource.cachedValue.read(reader)?.value?.resources.read(reader)); private readonly _isDirtyObservables = mapObservableArrayCached(this, this._resources.map(r => r || []), res => { const isModifiedDirty = res.modified ? isUriDirty(this._textFileService, res.modified) : constObservable(false); const isOriginalDirty = res.original ? isUriDirty(this._textFileService, res.original) : constObservable(false); return derived(reader => /** @description modifiedDirty||originalDirty */ isModifiedDirty.read(reader) || isOriginalDirty.read(reader)); }, i => JSON.stringify([i.modified?.toString(), i.original?.toString()])); private readonly _isDirtyObservable = derived(this, reader => this._isDirtyObservables.read(reader).some(isDirty => isDirty.read(reader))) .keepObserved(this._store); override readonly onDidChangeDirty = Event.fromObservableLight(this._isDirtyObservable); override isDirty() { return this._isDirtyObservable.get(); } override async save(group: number, options?: ISaveOptions | undefined): Promise<EditorInput> { await this.doSaveOrRevert('save', group, options); return this; } override revert(group: GroupIdentifier, options?: IRevertOptions): Promise<void> { return this.doSaveOrRevert('revert', group, options); } private async doSaveOrRevert(mode: 'save', group: GroupIdentifier, options?: ISaveOptions): Promise<void>; private async doSaveOrRevert(mode: 'revert', group: GroupIdentifier, options?: IRevertOptions): Promise<void>; private async doSaveOrRevert(mode: 'save' | 'revert', group: GroupIdentifier, options?: ISaveOptions | IRevertOptions): Promise<void> { const items = this._viewModel.currentValue?.items.get(); if (items) { await Promise.all(items.map(async item => { const model = item.diffEditorViewModel.model; const handleOriginal = model.original.uri.scheme !== Schemas.untitled && this._textFileService.isDirty(model.original.uri); // match diff editor behaviour await Promise.all([ handleOriginal ? mode === 'save' ? this._textFileService.save(model.original.uri, options) : this._textFileService.revert(model.original.uri, options) : Promise.resolve(), mode === 'save' ? this._textFileService.save(model.modified.uri, options) : this._textFileService.revert(model.modified.uri, options), ]); })); } return undefined; } override readonly closeHandler: IEditorCloseHandler = { // TODO@bpasero TODO@hediet this is a workaround for // not having a better way to figure out if the // editors this input wraps around are opened or not async confirm() { return ConfirmResult.DONT_SAVE; }, showConfirm() { return false; } }; } function isUriDirty(textFileService: ITextFileService, uri: URI) { return observableFromEvent( Event.filter(textFileService.files.onDidChangeDirty, e => e.resource.toString() === uri.toString()), () => textFileService.isDirty(uri) ); } function getReadonlyConfiguration(isReadonly: boolean | IMarkdownString | undefined): { readOnly: boolean; readOnlyMessage: IMarkdownString | undefined } { return { readOnly: !!isReadonly, readOnlyMessage: typeof isReadonly !== 'boolean' ? isReadonly : undefined }; } function computeOptions(configuration: IEditorConfiguration): IDiffEditorOptions { const editorConfiguration = deepClone(configuration.editor); // Handle diff editor specially by merging in diffEditor configuration if (isObject(configuration.diffEditor)) { const diffEditorConfiguration: IDiffEditorOptions = deepClone(configuration.diffEditor); // User settings defines `diffEditor.codeLens`, but here we rename that to `diffEditor.diffCodeLens` to avoid collisions with `editor.codeLens`. diffEditorConfiguration.diffCodeLens = diffEditorConfiguration.codeLens; delete diffEditorConfiguration.codeLens; // User settings defines `diffEditor.wordWrap`, but here we rename that to `diffEditor.diffWordWrap` to avoid collisions with `editor.wordWrap`. diffEditorConfiguration.diffWordWrap = <'off' | 'on' | 'inherit' | undefined>diffEditorConfiguration.wordWrap; delete diffEditorConfiguration.wordWrap; Object.assign(editorConfiguration, diffEditorConfiguration); } return editorConfiguration; } export class MultiDiffEditorResolverContribution extends Disposable { static readonly ID = 'workbench.contrib.multiDiffEditorResolver'; constructor( @IEditorResolverService editorResolverService: IEditorResolverService, @IInstantiationService instantiationService: IInstantiationService, ) { super(); this._register(editorResolverService.registerEditor( `*`, { id: DEFAULT_EDITOR_ASSOCIATION.id, label: DEFAULT_EDITOR_ASSOCIATION.displayName, detail: DEFAULT_EDITOR_ASSOCIATION.providerDisplayName, priority: RegisteredEditorPriority.builtin }, {}, { createMultiDiffEditorInput: (diffListEditor: IResourceMultiDiffEditorInput): EditorInputWithOptions => { return { editor: MultiDiffEditorInput.fromResourceMultiDiffEditorInput(diffListEditor, instantiationService), }; }, } )); } } interface ISerializedMultiDiffEditorInput { multiDiffSourceUri: string; label: string | undefined; resources: { originalUri: string | undefined; modifiedUri: string | undefined; }[] | undefined; } export class MultiDiffEditorSerializer implements IEditorSerializer { canSerialize(editor: EditorInput): boolean { return editor instanceof MultiDiffEditorInput; } serialize(editor: MultiDiffEditorInput): string | undefined { return JSON.stringify(editor.serialize()); } deserialize(instantiationService: IInstantiationService, serializedEditor: string): EditorInput | undefined { try { const data = parse(serializedEditor) as ISerializedMultiDiffEditorInput; return MultiDiffEditorInput.fromSerialized(data, instantiationService); } catch (err) { onUnexpectedError(err); return undefined; } } }
src/vs/workbench/contrib/multiDiffEditor/browser/multiDiffEditorInput.ts
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.00019878621969837695, 0.00017048399604391307, 0.00016484790830872953, 0.0001699153654044494, 0.000005297998541209381 ]
{ "id": 1, "code_window": [ " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: vscode_cli_alpine_x64_cli\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}" ], "file_path": "build/azure-pipelines/alpine/cli-build-alpine.yml", "type": "add", "edit_start_line_idx": 100 }
parameters: - name: VSCODE_BUILD_LINUX type: boolean default: false - name: VSCODE_BUILD_LINUX_ARM64 type: boolean default: false - name: VSCODE_BUILD_LINUX_ARMHF type: boolean default: false - name: VSCODE_CHECK_ONLY type: boolean default: false - name: VSCODE_QUALITY type: string steps: - task: NodeTool@0 inputs: versionSource: fromFile versionFilePath: .nvmrc nodejsMirror: https://github.com/joaomoreno/node-mirror/releases/download - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - template: ../cli/cli-apply-patches.yml - task: Npm@1 displayName: Download openssl prebuilt inputs: command: custom customCommand: pack @vscode-internal/[email protected] customRegistry: useFeed customFeed: "Monaco/openssl-prebuilt" workingDir: $(Build.ArtifactStagingDirectory) - script: | set -e mkdir $(Build.ArtifactStagingDirectory)/openssl tar -xvzf $(Build.ArtifactStagingDirectory)/vscode-internal-openssl-prebuilt-0.0.11.tgz --strip-components=1 --directory=$(Build.ArtifactStagingDirectory)/openssl displayName: Extract openssl prebuilt - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - script: node build/setup-npm-registry.js $NPM_REGISTRY condition: and(succeeded(), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM Registry - script: | set -e npm config set registry "$NPM_REGISTRY" --location=project # npm >v7 deprecated the `always-auth` config option, refs npm/cli@72a7eeb # following is a workaround for yarn to send authorization header # for GET requests to the registry. echo "always-auth=true" >> .npmrc yarn config set registry "$NPM_REGISTRY" condition: and(succeeded(), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM & Yarn - task: npmAuthenticate@0 inputs: workingFile: .npmrc condition: and(succeeded(), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM Authentication - script: | set -e for i in {1..5}; do # try 5 times yarn --cwd build --frozen-lockfile --check-files && break if [ $i -eq 3 ]; then echo "Yarn failed too many times" >&2 exit 1 fi echo "Yarn failed $i, trying again..." done displayName: Install build dependencies - script: | set -e mkdir -p $(Build.SourcesDirectory)/.build displayName: Create .build folder for misc dependencies - template: ../cli/install-rust-posix.yml parameters: targets: - ${{ if eq(parameters.VSCODE_BUILD_LINUX_ARM64, true) }}: - aarch64-unknown-linux-gnu - ${{ if eq(parameters.VSCODE_BUILD_LINUX, true) }}: - x86_64-unknown-linux-gnu - ${{ if eq(parameters.VSCODE_BUILD_LINUX_ARMHF, true) }}: - armv7-unknown-linux-gnueabihf - ${{ if eq(parameters.VSCODE_BUILD_LINUX_ARM64, true) }}: - template: ../cli/cli-compile.yml parameters: VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_CLI_TARGET: aarch64-unknown-linux-gnu VSCODE_CLI_ARTIFACT: vscode_cli_linux_arm64_cli VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }} VSCODE_CLI_ENV: OPENSSL_LIB_DIR: $(Build.ArtifactStagingDirectory)/openssl/arm64-linux/lib OPENSSL_INCLUDE_DIR: $(Build.ArtifactStagingDirectory)/openssl/arm64-linux/include SYSROOT_ARCH: arm64 - ${{ if eq(parameters.VSCODE_BUILD_LINUX, true) }}: - template: ../cli/cli-compile.yml parameters: VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_CLI_TARGET: x86_64-unknown-linux-gnu VSCODE_CLI_ARTIFACT: vscode_cli_linux_x64_cli VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }} VSCODE_CLI_ENV: OPENSSL_LIB_DIR: $(Build.ArtifactStagingDirectory)/openssl/x64-linux/lib OPENSSL_INCLUDE_DIR: $(Build.ArtifactStagingDirectory)/openssl/x64-linux/include SYSROOT_ARCH: amd64 - ${{ if eq(parameters.VSCODE_BUILD_LINUX_ARMHF, true) }}: - template: ../cli/cli-compile.yml parameters: VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_CLI_TARGET: armv7-unknown-linux-gnueabihf VSCODE_CLI_ARTIFACT: vscode_cli_linux_armhf_cli VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }} VSCODE_CLI_ENV: OPENSSL_LIB_DIR: $(Build.ArtifactStagingDirectory)/openssl/arm-linux/lib OPENSSL_INCLUDE_DIR: $(Build.ArtifactStagingDirectory)/openssl/arm-linux/include SYSROOT_ARCH: armhf - ${{ if eq(parameters.VSCODE_BUILD_LINUX_ARMHF, true) }}: - template: ../cli/cli-publish.yml parameters: VSCODE_CLI_ARTIFACT: vscode_cli_linux_armhf_cli - ${{ if eq(parameters.VSCODE_BUILD_LINUX, true) }}: - template: ../cli/cli-publish.yml parameters: VSCODE_CLI_ARTIFACT: vscode_cli_linux_x64_cli - ${{ if eq(parameters.VSCODE_BUILD_LINUX_ARM64, true) }}: - template: ../cli/cli-publish.yml parameters: VSCODE_CLI_ARTIFACT: vscode_cli_linux_arm64_cli
build/azure-pipelines/linux/cli-build-linux.yml
1
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.9959527254104614, 0.15470655262470245, 0.0001670032215770334, 0.0021907235495746136, 0.29393064975738525 ]
{ "id": 1, "code_window": [ " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: vscode_cli_alpine_x64_cli\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}" ], "file_path": "build/azure-pipelines/alpine/cli-build-alpine.yml", "type": "add", "edit_start_line_idx": 100 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; import { ActionsOrientation } from 'vs/base/browser/ui/actionbar/actionbar'; import { IActivityService } from 'vs/workbench/services/activity/common/activity'; import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IDisposable, DisposableStore, Disposable, DisposableMap } from 'vs/base/common/lifecycle'; import { IColorTheme } from 'vs/platform/theme/common/themeService'; import { CompositeBar, ICompositeBarItem, CompositeDragAndDrop } from 'vs/workbench/browser/parts/compositeBar'; import { Dimension, createCSSRule, asCSSUrl, isMouseEvent } from 'vs/base/browser/dom'; import { IStorageService, StorageScope, StorageTarget, IProfileStorageValueChangeEvent } from 'vs/platform/storage/common/storage'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { URI, UriComponents } from 'vs/base/common/uri'; import { ToggleCompositePinnedAction, ICompositeBarColors, IActivityHoverOptions, ToggleCompositeBadgeAction, CompositeBarAction, ICompositeBar, ICompositeBarActionItem } from 'vs/workbench/browser/parts/compositeBarActions'; import { IViewDescriptorService, ViewContainer, IViewContainerModel, ViewContainerLocation } from 'vs/workbench/common/views'; import { IContextKeyService, ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { isString } from 'vs/base/common/types'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { isNative } from 'vs/base/common/platform'; import { Before2D, ICompositeDragAndDrop } from 'vs/workbench/browser/dnd'; import { ThemeIcon } from 'vs/base/common/themables'; import { IAction, toAction } from 'vs/base/common/actions'; import { StringSHA1 } from 'vs/base/common/hash'; import { GestureEvent } from 'vs/base/browser/touch'; import { IPaneCompositePart } from 'vs/workbench/browser/parts/paneCompositePart'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; interface IPlaceholderViewContainer { readonly id: string; readonly name?: string; readonly iconUrl?: UriComponents; readonly themeIcon?: ThemeIcon; readonly isBuiltin?: boolean; readonly views?: { when?: string }[]; // TODO @sandy081: Remove this after a while. Migrated to visible in IViewContainerWorkspaceState readonly visible?: boolean; } interface IPinnedViewContainer { readonly id: string; readonly pinned: boolean; readonly order?: number; // TODO @sandy081: Remove this after a while. Migrated to visible in IViewContainerWorkspaceState readonly visible: boolean; } interface IViewContainerWorkspaceState { readonly id: string; readonly visible: boolean; } interface ICachedViewContainer { readonly id: string; name?: string; icon?: URI | ThemeIcon; readonly pinned: boolean; readonly order?: number; visible: boolean; isBuiltin?: boolean; views?: { when?: string }[]; } export interface IPaneCompositeBarOptions { readonly partContainerClass: string; readonly pinnedViewContainersKey: string; readonly placeholderViewContainersKey: string; readonly viewContainersWorkspaceStateKey: string; readonly icon: boolean; readonly compact?: boolean; readonly iconSize: number; readonly recomputeSizes: boolean; readonly orientation: ActionsOrientation; readonly compositeSize: number; readonly overflowActionSize: number; readonly preventLoopNavigation?: boolean; readonly activityHoverOptions: IActivityHoverOptions; readonly fillExtraContextMenuActions: (actions: IAction[], e?: MouseEvent | GestureEvent) => void; readonly colors: (theme: IColorTheme) => ICompositeBarColors; } export class PaneCompositeBar extends Disposable { private readonly viewContainerDisposables = this._register(new DisposableMap<string, IDisposable>()); private readonly location: ViewContainerLocation; private readonly compositeBar: CompositeBar; readonly dndHandler: ICompositeDragAndDrop; private readonly compositeActions = new Map<string, { activityAction: ViewContainerActivityAction; pinnedAction: ToggleCompositePinnedAction; badgeAction: ToggleCompositeBadgeAction }>(); private hasExtensionsRegistered: boolean = false; constructor( protected readonly options: IPaneCompositeBarOptions, private readonly part: Parts, private readonly paneCompositePart: IPaneCompositePart, @IInstantiationService protected readonly instantiationService: IInstantiationService, @IStorageService private readonly storageService: IStorageService, @IExtensionService private readonly extensionService: IExtensionService, @IViewDescriptorService private readonly viewDescriptorService: IViewDescriptorService, @IContextKeyService protected readonly contextKeyService: IContextKeyService, @IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService, @IWorkbenchLayoutService protected readonly layoutService: IWorkbenchLayoutService, ) { super(); this.location = paneCompositePart.partId === Parts.PANEL_PART ? ViewContainerLocation.Panel : paneCompositePart.partId === Parts.AUXILIARYBAR_PART ? ViewContainerLocation.AuxiliaryBar : ViewContainerLocation.Sidebar; this.dndHandler = new CompositeDragAndDrop(this.viewDescriptorService, this.location, async (id: string, focus?: boolean) => { return await this.paneCompositePart.openPaneComposite(id, focus) ?? null; }, (from: string, to: string, before?: Before2D) => this.compositeBar.move(from, to, this.options.orientation === ActionsOrientation.VERTICAL ? before?.verticallyBefore : before?.horizontallyBefore), () => this.compositeBar.getCompositeBarItems(), ); const cachedItems = this.cachedViewContainers .map(container => ({ id: container.id, name: container.name, visible: !this.shouldBeHidden(container.id, container), order: container.order, pinned: container.pinned, })); this.compositeBar = this.createCompositeBar(cachedItems); this.onDidRegisterViewContainers(this.getViewContainers()); this.registerListeners(); } private createCompositeBar(cachedItems: ICompositeBarItem[]) { return this._register(this.instantiationService.createInstance(CompositeBar, cachedItems, { icon: this.options.icon, compact: this.options.compact, orientation: this.options.orientation, activityHoverOptions: this.options.activityHoverOptions, preventLoopNavigation: this.options.preventLoopNavigation, openComposite: async (compositeId, preserveFocus) => { return (await this.paneCompositePart.openPaneComposite(compositeId, !preserveFocus)) ?? null; }, getActivityAction: compositeId => this.getCompositeActions(compositeId).activityAction, getCompositePinnedAction: compositeId => this.getCompositeActions(compositeId).pinnedAction, getCompositeBadgeAction: compositeId => this.getCompositeActions(compositeId).badgeAction, getOnCompositeClickAction: compositeId => this.getCompositeActions(compositeId).activityAction, fillExtraContextMenuActions: (actions, e) => this.options.fillExtraContextMenuActions(actions, e), getContextMenuActionsForComposite: compositeId => this.getContextMenuActionsForComposite(compositeId), getDefaultCompositeId: () => this.viewDescriptorService.getDefaultViewContainer(this.location)?.id, dndHandler: this.dndHandler, compositeSize: this.options.compositeSize, overflowActionSize: this.options.overflowActionSize, colors: theme => this.options.colors(theme), })); } private getContextMenuActionsForComposite(compositeId: string): IAction[] { const actions: IAction[] = []; const viewContainer = this.viewDescriptorService.getViewContainerById(compositeId)!; const defaultLocation = this.viewDescriptorService.getDefaultViewContainerLocation(viewContainer)!; if (defaultLocation !== this.viewDescriptorService.getViewContainerLocation(viewContainer)) { actions.push(toAction({ id: 'resetLocationAction', label: localize('resetLocation', "Reset Location"), run: () => this.viewDescriptorService.moveViewContainerToLocation(viewContainer, defaultLocation, undefined, 'resetLocationAction') })); } else { const viewContainerModel = this.viewDescriptorService.getViewContainerModel(viewContainer); if (viewContainerModel.allViewDescriptors.length === 1) { const viewToReset = viewContainerModel.allViewDescriptors[0]; const defaultContainer = this.viewDescriptorService.getDefaultContainerById(viewToReset.id)!; if (defaultContainer !== viewContainer) { actions.push(toAction({ id: 'resetLocationAction', label: localize('resetLocation', "Reset Location"), run: () => this.viewDescriptorService.moveViewsToContainer([viewToReset], defaultContainer, undefined, 'resetLocationAction') })); } } } return actions; } private registerListeners(): void { // View Container Changes this._register(this.viewDescriptorService.onDidChangeViewContainers(({ added, removed }) => this.onDidChangeViewContainers(added, removed))); this._register(this.viewDescriptorService.onDidChangeContainerLocation(({ viewContainer, from, to }) => this.onDidChangeViewContainerLocation(viewContainer, from, to))); // View Container Visibility Changes this._register(this.paneCompositePart.onDidPaneCompositeOpen(e => this.onDidChangeViewContainerVisibility(e.getId(), true))); this._register(this.paneCompositePart.onDidPaneCompositeClose(e => this.onDidChangeViewContainerVisibility(e.getId(), false))); // Extension registration this.extensionService.whenInstalledExtensionsRegistered().then(() => { if (this._store.isDisposed) { return; } this.onDidRegisterExtensions(); this._register(this.compositeBar.onDidChange(() => this.saveCachedViewContainers())); this._register(this.storageService.onDidChangeValue(StorageScope.PROFILE, this.options.pinnedViewContainersKey, this._store)(e => this.onDidPinnedViewContainersStorageValueChange(e))); }); } private onDidChangeViewContainers(added: readonly { container: ViewContainer; location: ViewContainerLocation }[], removed: readonly { container: ViewContainer; location: ViewContainerLocation }[]) { removed.filter(({ location }) => location === this.location).forEach(({ container }) => this.onDidDeregisterViewContainer(container)); this.onDidRegisterViewContainers(added.filter(({ location }) => location === this.location).map(({ container }) => container)); } private onDidChangeViewContainerLocation(container: ViewContainer, from: ViewContainerLocation, to: ViewContainerLocation) { if (from === this.location) { this.onDidDeregisterViewContainer(container); } if (to === this.location) { this.onDidRegisterViewContainers([container]); // Open view container if part is visible and there is no other view container opened const visibleComposites = this.compositeBar.getVisibleComposites(); if (!this.paneCompositePart.getActivePaneComposite() && this.layoutService.isVisible(this.paneCompositePart.partId) && visibleComposites.length) { this.paneCompositePart.openPaneComposite(visibleComposites[0].id); } } } private onDidChangeViewContainerVisibility(id: string, visible: boolean) { if (visible) { // Activate view container action on opening of a view container this.onDidViewContainerVisible(id); } else { // Deactivate view container action on close this.compositeBar.deactivateComposite(id); } } private onDidRegisterExtensions(): void { this.hasExtensionsRegistered = true; // show/hide/remove composites for (const { id } of this.cachedViewContainers) { const viewContainer = this.getViewContainer(id); if (viewContainer) { this.showOrHideViewContainer(viewContainer); } else { if (this.viewDescriptorService.isViewContainerRemovedPermanently(id)) { this.removeComposite(id); } else { this.hideComposite(id); } } } this.saveCachedViewContainers(); } private onDidViewContainerVisible(id: string): void { const viewContainer = this.getViewContainer(id); if (viewContainer) { // Update the composite bar by adding this.addComposite(viewContainer); this.compositeBar.activateComposite(viewContainer.id); if (this.shouldBeHidden(viewContainer)) { const viewContainerModel = this.viewDescriptorService.getViewContainerModel(viewContainer); if (viewContainerModel.activeViewDescriptors.length === 0) { // Update the composite bar by hiding this.hideComposite(viewContainer.id); } } } } create(parent: HTMLElement): HTMLElement { return this.compositeBar.create(parent); } private getCompositeActions(compositeId: string): { activityAction: ViewContainerActivityAction; pinnedAction: ToggleCompositePinnedAction; badgeAction: ToggleCompositeBadgeAction } { let compositeActions = this.compositeActions.get(compositeId); if (!compositeActions) { const viewContainer = this.getViewContainer(compositeId); if (viewContainer) { const viewContainerModel = this.viewDescriptorService.getViewContainerModel(viewContainer); compositeActions = { activityAction: this._register(this.instantiationService.createInstance(ViewContainerActivityAction, this.toCompositeBarActionItemFrom(viewContainerModel), this.part, this.paneCompositePart)), pinnedAction: this._register(new ToggleCompositePinnedAction(this.toCompositeBarActionItemFrom(viewContainerModel), this.compositeBar)), badgeAction: this._register(new ToggleCompositeBadgeAction(this.toCompositeBarActionItemFrom(viewContainerModel), this.compositeBar)) }; } else { const cachedComposite = this.cachedViewContainers.filter(c => c.id === compositeId)[0]; compositeActions = { activityAction: this._register(this.instantiationService.createInstance(PlaceHolderViewContainerActivityAction, this.toCompositeBarActionItem(compositeId, cachedComposite?.name ?? compositeId, cachedComposite?.icon, undefined), this.part, this.paneCompositePart)), pinnedAction: this._register(new PlaceHolderToggleCompositePinnedAction(compositeId, this.compositeBar)), badgeAction: this._register(new PlaceHolderToggleCompositeBadgeAction(compositeId, this.compositeBar)) }; } this.compositeActions.set(compositeId, compositeActions); } return compositeActions; } private onDidRegisterViewContainers(viewContainers: readonly ViewContainer[]): void { for (const viewContainer of viewContainers) { this.addComposite(viewContainer); // Pin it by default if it is new const cachedViewContainer = this.cachedViewContainers.filter(({ id }) => id === viewContainer.id)[0]; if (!cachedViewContainer) { this.compositeBar.pin(viewContainer.id); } // Active const visibleViewContainer = this.paneCompositePart.getActivePaneComposite(); if (visibleViewContainer?.getId() === viewContainer.id) { this.compositeBar.activateComposite(viewContainer.id); } const viewContainerModel = this.viewDescriptorService.getViewContainerModel(viewContainer); this.updateCompositeBarActionItem(viewContainer, viewContainerModel); this.showOrHideViewContainer(viewContainer); const disposables = new DisposableStore(); disposables.add(viewContainerModel.onDidChangeContainerInfo(() => this.updateCompositeBarActionItem(viewContainer, viewContainerModel))); disposables.add(viewContainerModel.onDidChangeActiveViewDescriptors(() => this.showOrHideViewContainer(viewContainer))); this.viewContainerDisposables.set(viewContainer.id, disposables); } } private onDidDeregisterViewContainer(viewContainer: ViewContainer): void { this.viewContainerDisposables.deleteAndDispose(viewContainer.id); this.removeComposite(viewContainer.id); } private updateCompositeBarActionItem(viewContainer: ViewContainer, viewContainerModel: IViewContainerModel): void { const compositeBarActionItem = this.toCompositeBarActionItemFrom(viewContainerModel); const { activityAction, pinnedAction } = this.getCompositeActions(viewContainer.id); activityAction.updateCompositeBarActionItem(compositeBarActionItem); if (pinnedAction instanceof PlaceHolderToggleCompositePinnedAction) { pinnedAction.setActivity(compositeBarActionItem); } if (this.options.recomputeSizes) { this.compositeBar.recomputeSizes(); } this.saveCachedViewContainers(); } private toCompositeBarActionItemFrom(viewContainerModel: IViewContainerModel): ICompositeBarActionItem { return this.toCompositeBarActionItem(viewContainerModel.viewContainer.id, viewContainerModel.title, viewContainerModel.icon, viewContainerModel.keybindingId); } private toCompositeBarActionItem(id: string, name: string, icon: URI | ThemeIcon | undefined, keybindingId: string | undefined): ICompositeBarActionItem { let classNames: string[] | undefined = undefined; let iconUrl: URI | undefined = undefined; if (this.options.icon) { if (URI.isUri(icon)) { iconUrl = icon; const cssUrl = asCSSUrl(icon); const hash = new StringSHA1(); hash.update(cssUrl); const iconId = `activity-${id.replace(/\./g, '-')}-${hash.digest()}`; const iconClass = `.monaco-workbench .${this.options.partContainerClass} .monaco-action-bar .action-label.${iconId}`; classNames = [iconId, 'uri-icon']; createCSSRule(iconClass, ` mask: ${cssUrl} no-repeat 50% 50%; mask-size: ${this.options.iconSize}px; -webkit-mask: ${cssUrl} no-repeat 50% 50%; -webkit-mask-size: ${this.options.iconSize}px; mask-origin: padding; -webkit-mask-origin: padding; `); } else if (ThemeIcon.isThemeIcon(icon)) { classNames = ThemeIcon.asClassNameArray(icon); } } return { id, name, classNames, iconUrl, keybindingId }; } private showOrHideViewContainer(viewContainer: ViewContainer): void { if (this.shouldBeHidden(viewContainer)) { this.hideComposite(viewContainer.id); } else { this.addComposite(viewContainer); } } private shouldBeHidden(viewContainerOrId: string | ViewContainer, cachedViewContainer?: ICachedViewContainer): boolean { const viewContainer = isString(viewContainerOrId) ? this.getViewContainer(viewContainerOrId) : viewContainerOrId; const viewContainerId = isString(viewContainerOrId) ? viewContainerOrId : viewContainerOrId.id; if (viewContainer) { if (viewContainer.hideIfEmpty) { if (this.viewDescriptorService.getViewContainerModel(viewContainer).activeViewDescriptors.length > 0) { return false; } } else { return false; } } // Check cache only if extensions are not yet registered and current window is not native (desktop) remote connection window if (!this.hasExtensionsRegistered && !(this.part === Parts.SIDEBAR_PART && this.environmentService.remoteAuthority && isNative)) { cachedViewContainer = cachedViewContainer || this.cachedViewContainers.find(({ id }) => id === viewContainerId); // Show builtin ViewContainer if not registered yet if (!viewContainer && cachedViewContainer?.isBuiltin && cachedViewContainer?.visible) { return false; } if (cachedViewContainer?.views?.length) { return cachedViewContainer.views.every(({ when }) => !!when && !this.contextKeyService.contextMatchesRules(ContextKeyExpr.deserialize(when))); } } return true; } private addComposite(viewContainer: ViewContainer): void { this.compositeBar.addComposite({ id: viewContainer.id, name: typeof viewContainer.title === 'string' ? viewContainer.title : viewContainer.title.value, order: viewContainer.order, requestedIndex: viewContainer.requestedIndex }); } private hideComposite(compositeId: string): void { this.compositeBar.hideComposite(compositeId); const compositeActions = this.compositeActions.get(compositeId); if (compositeActions) { compositeActions.activityAction.dispose(); compositeActions.pinnedAction.dispose(); this.compositeActions.delete(compositeId); } } private removeComposite(compositeId: string): void { this.compositeBar.removeComposite(compositeId); const compositeActions = this.compositeActions.get(compositeId); if (compositeActions) { compositeActions.activityAction.dispose(); compositeActions.pinnedAction.dispose(); this.compositeActions.delete(compositeId); } } getPinnedPaneCompositeIds(): string[] { const pinnedCompositeIds = this.compositeBar.getPinnedComposites().map(v => v.id); return this.getViewContainers() .filter(v => this.compositeBar.isPinned(v.id)) .sort((v1, v2) => pinnedCompositeIds.indexOf(v1.id) - pinnedCompositeIds.indexOf(v2.id)) .map(v => v.id); } getVisiblePaneCompositeIds(): string[] { return this.compositeBar.getVisibleComposites() .filter(v => this.paneCompositePart.getActivePaneComposite()?.getId() === v.id || this.compositeBar.isPinned(v.id)) .map(v => v.id); } getContextMenuActions(): IAction[] { return this.compositeBar.getContextMenuActions(); } focus(index?: number): void { this.compositeBar.focus(index); } layout(width: number, height: number): void { this.compositeBar.layout(new Dimension(width, height)); } private getViewContainer(id: string): ViewContainer | undefined { const viewContainer = this.viewDescriptorService.getViewContainerById(id); return viewContainer && this.viewDescriptorService.getViewContainerLocation(viewContainer) === this.location ? viewContainer : undefined; } private getViewContainers(): readonly ViewContainer[] { return this.viewDescriptorService.getViewContainersByLocation(this.location); } private onDidPinnedViewContainersStorageValueChange(e: IProfileStorageValueChangeEvent): void { if (this.pinnedViewContainersValue !== this.getStoredPinnedViewContainersValue() /* This checks if current window changed the value or not */) { this._placeholderViewContainersValue = undefined; this._pinnedViewContainersValue = undefined; this._cachedViewContainers = undefined; const newCompositeItems: ICompositeBarItem[] = []; const compositeItems = this.compositeBar.getCompositeBarItems(); for (const cachedViewContainer of this.cachedViewContainers) { newCompositeItems.push({ id: cachedViewContainer.id, name: cachedViewContainer.name, order: cachedViewContainer.order, pinned: cachedViewContainer.pinned, visible: cachedViewContainer.visible && !!this.getViewContainer(cachedViewContainer.id), }); } for (const viewContainer of this.getViewContainers()) { // Add missing view containers if (!newCompositeItems.some(({ id }) => id === viewContainer.id)) { const index = compositeItems.findIndex(({ id }) => id === viewContainer.id); if (index !== -1) { const compositeItem = compositeItems[index]; newCompositeItems.splice(index, 0, { id: viewContainer.id, name: typeof viewContainer.title === 'string' ? viewContainer.title : viewContainer.title.value, order: compositeItem.order, pinned: compositeItem.pinned, visible: compositeItem.visible, }); } else { newCompositeItems.push({ id: viewContainer.id, name: typeof viewContainer.title === 'string' ? viewContainer.title : viewContainer.title.value, order: viewContainer.order, pinned: true, visible: !this.shouldBeHidden(viewContainer), }); } } } this.compositeBar.setCompositeBarItems(newCompositeItems); } } private saveCachedViewContainers(): void { const state: ICachedViewContainer[] = []; const compositeItems = this.compositeBar.getCompositeBarItems(); for (const compositeItem of compositeItems) { const viewContainer = this.getViewContainer(compositeItem.id); if (viewContainer) { const viewContainerModel = this.viewDescriptorService.getViewContainerModel(viewContainer); const views: { when: string | undefined }[] = []; for (const { when } of viewContainerModel.allViewDescriptors) { views.push({ when: when ? when.serialize() : undefined }); } state.push({ id: compositeItem.id, name: viewContainerModel.title, icon: URI.isUri(viewContainerModel.icon) && this.environmentService.remoteAuthority ? undefined : viewContainerModel.icon, // Do not cache uri icons with remote connection views, pinned: compositeItem.pinned, order: compositeItem.order, visible: compositeItem.visible, isBuiltin: !viewContainer.extensionId }); } else { state.push({ id: compositeItem.id, name: compositeItem.name, pinned: compositeItem.pinned, order: compositeItem.order, visible: false, isBuiltin: false }); } } this.storeCachedViewContainersState(state); } private _cachedViewContainers: ICachedViewContainer[] | undefined = undefined; private get cachedViewContainers(): ICachedViewContainer[] { if (this._cachedViewContainers === undefined) { this._cachedViewContainers = this.getPinnedViewContainers(); for (const placeholderViewContainer of this.getPlaceholderViewContainers()) { const cachedViewContainer = this._cachedViewContainers.find(cached => cached.id === placeholderViewContainer.id); if (cachedViewContainer) { cachedViewContainer.visible = placeholderViewContainer.visible ?? cachedViewContainer.visible; cachedViewContainer.name = placeholderViewContainer.name; cachedViewContainer.icon = placeholderViewContainer.themeIcon ? placeholderViewContainer.themeIcon : placeholderViewContainer.iconUrl ? URI.revive(placeholderViewContainer.iconUrl) : undefined; if (URI.isUri(cachedViewContainer.icon) && this.environmentService.remoteAuthority) { cachedViewContainer.icon = undefined; // Do not cache uri icons with remote connection } cachedViewContainer.views = placeholderViewContainer.views; cachedViewContainer.isBuiltin = placeholderViewContainer.isBuiltin; } } for (const viewContainerWorkspaceState of this.getViewContainersWorkspaceState()) { const cachedViewContainer = this._cachedViewContainers.find(cached => cached.id === viewContainerWorkspaceState.id); if (cachedViewContainer) { cachedViewContainer.visible = viewContainerWorkspaceState.visible ?? cachedViewContainer.visible; } } } return this._cachedViewContainers; } private storeCachedViewContainersState(cachedViewContainers: ICachedViewContainer[]): void { const pinnedViewContainers = this.getPinnedViewContainers(); this.setPinnedViewContainers(cachedViewContainers.map(({ id, pinned, order }) => (<IPinnedViewContainer>{ id, pinned, visible: pinnedViewContainers.find(({ id: pinnedId }) => pinnedId === id)?.visible, order }))); this.setPlaceholderViewContainers(cachedViewContainers.map(({ id, icon, name, views, isBuiltin }) => (<IPlaceholderViewContainer>{ id, iconUrl: URI.isUri(icon) ? icon : undefined, themeIcon: ThemeIcon.isThemeIcon(icon) ? icon : undefined, name, isBuiltin, views }))); this.setViewContainersWorkspaceState(cachedViewContainers.map(({ id, visible }) => (<IViewContainerWorkspaceState>{ id, visible, }))); } private getPinnedViewContainers(): IPinnedViewContainer[] { return JSON.parse(this.pinnedViewContainersValue); } private setPinnedViewContainers(pinnedViewContainers: IPinnedViewContainer[]): void { this.pinnedViewContainersValue = JSON.stringify(pinnedViewContainers); } private _pinnedViewContainersValue: string | undefined; private get pinnedViewContainersValue(): string { if (!this._pinnedViewContainersValue) { this._pinnedViewContainersValue = this.getStoredPinnedViewContainersValue(); } return this._pinnedViewContainersValue; } private set pinnedViewContainersValue(pinnedViewContainersValue: string) { if (this.pinnedViewContainersValue !== pinnedViewContainersValue) { this._pinnedViewContainersValue = pinnedViewContainersValue; this.setStoredPinnedViewContainersValue(pinnedViewContainersValue); } } private getStoredPinnedViewContainersValue(): string { return this.storageService.get(this.options.pinnedViewContainersKey, StorageScope.PROFILE, '[]'); } private setStoredPinnedViewContainersValue(value: string): void { this.storageService.store(this.options.pinnedViewContainersKey, value, StorageScope.PROFILE, StorageTarget.USER); } private getPlaceholderViewContainers(): IPlaceholderViewContainer[] { return JSON.parse(this.placeholderViewContainersValue); } private setPlaceholderViewContainers(placeholderViewContainers: IPlaceholderViewContainer[]): void { this.placeholderViewContainersValue = JSON.stringify(placeholderViewContainers); } private _placeholderViewContainersValue: string | undefined; private get placeholderViewContainersValue(): string { if (!this._placeholderViewContainersValue) { this._placeholderViewContainersValue = this.getStoredPlaceholderViewContainersValue(); } return this._placeholderViewContainersValue; } private set placeholderViewContainersValue(placeholderViewContainesValue: string) { if (this.placeholderViewContainersValue !== placeholderViewContainesValue) { this._placeholderViewContainersValue = placeholderViewContainesValue; this.setStoredPlaceholderViewContainersValue(placeholderViewContainesValue); } } private getStoredPlaceholderViewContainersValue(): string { return this.storageService.get(this.options.placeholderViewContainersKey, StorageScope.PROFILE, '[]'); } private setStoredPlaceholderViewContainersValue(value: string): void { this.storageService.store(this.options.placeholderViewContainersKey, value, StorageScope.PROFILE, StorageTarget.MACHINE); } private getViewContainersWorkspaceState(): IViewContainerWorkspaceState[] { return JSON.parse(this.viewContainersWorkspaceStateValue); } private setViewContainersWorkspaceState(viewContainersWorkspaceState: IViewContainerWorkspaceState[]): void { this.viewContainersWorkspaceStateValue = JSON.stringify(viewContainersWorkspaceState); } private _viewContainersWorkspaceStateValue: string | undefined; private get viewContainersWorkspaceStateValue(): string { if (!this._viewContainersWorkspaceStateValue) { this._viewContainersWorkspaceStateValue = this.getStoredViewContainersWorkspaceStateValue(); } return this._viewContainersWorkspaceStateValue; } private set viewContainersWorkspaceStateValue(viewContainersWorkspaceStateValue: string) { if (this.viewContainersWorkspaceStateValue !== viewContainersWorkspaceStateValue) { this._viewContainersWorkspaceStateValue = viewContainersWorkspaceStateValue; this.setStoredViewContainersWorkspaceStateValue(viewContainersWorkspaceStateValue); } } private getStoredViewContainersWorkspaceStateValue(): string { return this.storageService.get(this.options.viewContainersWorkspaceStateKey, StorageScope.WORKSPACE, '[]'); } private setStoredViewContainersWorkspaceStateValue(value: string): void { this.storageService.store(this.options.viewContainersWorkspaceStateKey, value, StorageScope.WORKSPACE, StorageTarget.MACHINE); } } class ViewContainerActivityAction extends CompositeBarAction { private static readonly preventDoubleClickDelay = 300; private lastRun = 0; constructor( compositeBarActionItem: ICompositeBarActionItem, private readonly part: Parts, private readonly paneCompositePart: IPaneCompositePart, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService, @ITelemetryService private readonly telemetryService: ITelemetryService, @IConfigurationService private readonly configurationService: IConfigurationService, @IActivityService private readonly activityService: IActivityService, ) { super(compositeBarActionItem); this.updateActivity(); this._register(this.activityService.onDidChangeActivity(viewContainerOrAction => { if (!isString(viewContainerOrAction) && viewContainerOrAction.id === this.compositeBarActionItem.id) { this.updateActivity(); } })); } updateCompositeBarActionItem(compositeBarActionItem: ICompositeBarActionItem): void { this.compositeBarActionItem = compositeBarActionItem; } private updateActivity(): void { const activities = this.activityService.getViewContainerActivities(this.compositeBarActionItem.id); this.activity = activities[0]; } override async run(event: { preserveFocus: boolean }): Promise<void> { if (isMouseEvent(event) && event.button === 2) { return; // do not run on right click } // prevent accident trigger on a doubleclick (to help nervous people) const now = Date.now(); if (now > this.lastRun /* https://github.com/microsoft/vscode/issues/25830 */ && now - this.lastRun < ViewContainerActivityAction.preventDoubleClickDelay) { return; } this.lastRun = now; const focus = (event && 'preserveFocus' in event) ? !event.preserveFocus : true; if (this.part === Parts.ACTIVITYBAR_PART) { const sideBarVisible = this.layoutService.isVisible(Parts.SIDEBAR_PART); const activeViewlet = this.paneCompositePart.getActivePaneComposite(); const focusBehavior = this.configurationService.getValue<string>('workbench.activityBar.iconClickBehavior'); if (sideBarVisible && activeViewlet?.getId() === this.compositeBarActionItem.id) { switch (focusBehavior) { case 'focus': this.logAction('refocus'); this.paneCompositePart.openPaneComposite(this.compositeBarActionItem.id, focus); break; case 'toggle': default: // Hide sidebar if selected viewlet already visible this.logAction('hide'); this.layoutService.setPartHidden(true, Parts.SIDEBAR_PART); break; } return; } this.logAction('show'); } await this.paneCompositePart.openPaneComposite(this.compositeBarActionItem.id, focus); return this.activate(); } private logAction(action: string) { type ActivityBarActionClassification = { owner: 'sbatten'; comment: 'Event logged when an activity bar action is triggered.'; viewletId: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The view in the activity bar for which the action was performed.' }; action: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The action that was performed. e.g. "hide", "show", or "refocus"' }; }; this.telemetryService.publicLog2<{ viewletId: String; action: String }, ActivityBarActionClassification>('activityBarAction', { viewletId: this.compositeBarActionItem.id, action }); } } class PlaceHolderViewContainerActivityAction extends ViewContainerActivityAction { } class PlaceHolderToggleCompositePinnedAction extends ToggleCompositePinnedAction { constructor(id: string, compositeBar: ICompositeBar) { super({ id, name: id, classNames: undefined }, compositeBar); } setActivity(activity: ICompositeBarActionItem): void { this.label = activity.name; } } class PlaceHolderToggleCompositeBadgeAction extends ToggleCompositeBadgeAction { constructor(id: string, compositeBar: ICompositeBar) { super({ id, name: id, classNames: undefined }, compositeBar); } setCompositeBarActionItem(actionItem: ICompositeBarActionItem): void { this.label = actionItem.name; } }
src/vs/workbench/browser/parts/paneCompositeBar.ts
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.00027732489979825914, 0.00017230257799383253, 0.0001579685922479257, 0.00016972370212897658, 0.000015217938198475167 ]
{ "id": 1, "code_window": [ " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: vscode_cli_alpine_x64_cli\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}" ], "file_path": "build/azure-pipelines/alpine/cli-build-alpine.yml", "type": "add", "edit_start_line_idx": 100 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Iterable } from 'vs/base/common/iterator'; import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import { isEqual } from 'vs/base/common/resources'; import { ThemeIcon } from 'vs/base/common/themables'; import { URI, UriComponents } from 'vs/base/common/uri'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { ILanguageService } from 'vs/editor/common/languages/language'; import { localize, localize2 } from 'vs/nls'; import { MenuId, MenuRegistry, registerAction2 } from 'vs/platform/actions/common/actions'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { EditorsOrder } from 'vs/workbench/common/editor'; import { IDebugService } from 'vs/workbench/contrib/debug/common/debug'; import { InlineChatController } from 'vs/workbench/contrib/inlineChat/browser/inlineChatController'; import { CTX_INLINE_CHAT_FOCUSED } from 'vs/workbench/contrib/inlineChat/common/inlineChat'; import { insertCell } from 'vs/workbench/contrib/notebook/browser/controller/cellOperations'; import { CELL_TITLE_CELL_GROUP_ID, CellToolbarOrder, INotebookActionContext, INotebookCellActionContext, INotebookCellToolbarActionContext, INotebookCommandContext, NOTEBOOK_EDITOR_WIDGET_ACTION_WEIGHT, NotebookAction, NotebookCellAction, NotebookMultiCellAction, cellExecutionArgs, executeNotebookCondition, getContextFromActiveEditor, getContextFromUri, parseMultiCellExecutionArgs } from 'vs/workbench/contrib/notebook/browser/controller/coreActions'; import { CellEditState, CellFocusMode, EXECUTE_CELL_COMMAND_ID, IFocusNotebookCellOptions, ScrollToRevealBehavior } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import * as icons from 'vs/workbench/contrib/notebook/browser/notebookIcons'; import { CellKind, CellUri, NotebookSetting } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { NOTEBOOK_CELL_EXECUTING, NOTEBOOK_CELL_EXECUTION_STATE, NOTEBOOK_CELL_LIST_FOCUSED, NOTEBOOK_CELL_TYPE, NOTEBOOK_HAS_RUNNING_CELL, NOTEBOOK_HAS_SOMETHING_RUNNING, NOTEBOOK_INTERRUPTIBLE_KERNEL, NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_KERNEL_COUNT, NOTEBOOK_KERNEL_SOURCE_COUNT, NOTEBOOK_LAST_CELL_FAILED, NOTEBOOK_MISSING_KERNEL_EXTENSION } from 'vs/workbench/contrib/notebook/common/notebookContextKeys'; import { NotebookEditorInput } from 'vs/workbench/contrib/notebook/common/notebookEditorInput'; import { INotebookExecutionStateService } from 'vs/workbench/contrib/notebook/common/notebookExecutionStateService'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; const EXECUTE_NOTEBOOK_COMMAND_ID = 'notebook.execute'; const CANCEL_NOTEBOOK_COMMAND_ID = 'notebook.cancelExecution'; const INTERRUPT_NOTEBOOK_COMMAND_ID = 'notebook.interruptExecution'; const CANCEL_CELL_COMMAND_ID = 'notebook.cell.cancelExecution'; const EXECUTE_CELL_FOCUS_CONTAINER_COMMAND_ID = 'notebook.cell.executeAndFocusContainer'; const EXECUTE_CELL_SELECT_BELOW = 'notebook.cell.executeAndSelectBelow'; const EXECUTE_CELL_INSERT_BELOW = 'notebook.cell.executeAndInsertBelow'; const EXECUTE_CELL_AND_BELOW = 'notebook.cell.executeCellAndBelow'; const EXECUTE_CELLS_ABOVE = 'notebook.cell.executeCellsAbove'; const RENDER_ALL_MARKDOWN_CELLS = 'notebook.renderAllMarkdownCells'; const REVEAL_RUNNING_CELL = 'notebook.revealRunningCell'; const REVEAL_LAST_FAILED_CELL = 'notebook.revealLastFailedCell'; // If this changes, update getCodeCellExecutionContextKeyService to match export const executeCondition = ContextKeyExpr.and( NOTEBOOK_CELL_TYPE.isEqualTo('code'), ContextKeyExpr.or( ContextKeyExpr.greater(NOTEBOOK_KERNEL_COUNT.key, 0), ContextKeyExpr.greater(NOTEBOOK_KERNEL_SOURCE_COUNT.key, 0), NOTEBOOK_MISSING_KERNEL_EXTENSION )); export const executeThisCellCondition = ContextKeyExpr.and( executeCondition, NOTEBOOK_CELL_EXECUTING.toNegated()); function renderAllMarkdownCells(context: INotebookActionContext): void { for (let i = 0; i < context.notebookEditor.getLength(); i++) { const cell = context.notebookEditor.cellAt(i); if (cell.cellKind === CellKind.Markup) { cell.updateEditState(CellEditState.Preview, 'renderAllMarkdownCells'); } } } async function runCell(editorGroupsService: IEditorGroupsService, context: INotebookActionContext): Promise<void> { const group = editorGroupsService.activeGroup; if (group) { if (group.activeEditor) { group.pinEditor(group.activeEditor); } } if (context.ui && context.cell) { await context.notebookEditor.executeNotebookCells(Iterable.single(context.cell)); if (context.autoReveal) { const cellIndex = context.notebookEditor.getCellIndex(context.cell); context.notebookEditor.revealCellRangeInView({ start: cellIndex, end: cellIndex + 1 }); } } else if (context.selectedCells?.length || context.cell) { const selectedCells = context.selectedCells?.length ? context.selectedCells : [context.cell!]; await context.notebookEditor.executeNotebookCells(selectedCells); const firstCell = selectedCells[0]; if (firstCell && context.autoReveal) { const cellIndex = context.notebookEditor.getCellIndex(firstCell); context.notebookEditor.revealCellRangeInView({ start: cellIndex, end: cellIndex + 1 }); } } let foundEditor: ICodeEditor | undefined = undefined; for (const [, codeEditor] of context.notebookEditor.codeEditors) { if (isEqual(codeEditor.getModel()?.uri, (context.cell ?? context.selectedCells?.[0])?.uri)) { foundEditor = codeEditor; break; } } if (!foundEditor) { return; } const controller = InlineChatController.get(foundEditor); if (!controller) { return; } controller.createSnapshot(); } registerAction2(class RenderAllMarkdownCellsAction extends NotebookAction { constructor() { super({ id: RENDER_ALL_MARKDOWN_CELLS, title: localize('notebookActions.renderMarkdown', "Render All Markdown Cells"), }); } async runWithContext(accessor: ServicesAccessor, context: INotebookActionContext): Promise<void> { renderAllMarkdownCells(context); } }); registerAction2(class ExecuteNotebookAction extends NotebookAction { constructor() { super({ id: EXECUTE_NOTEBOOK_COMMAND_ID, title: localize('notebookActions.executeNotebook', "Run All"), icon: icons.executeAllIcon, metadata: { description: localize('notebookActions.executeNotebook', "Run All"), args: [ { name: 'uri', description: 'The document uri' } ] }, menu: [ { id: MenuId.EditorTitle, order: -1, group: 'navigation', when: ContextKeyExpr.and( NOTEBOOK_IS_ACTIVE_EDITOR, executeNotebookCondition, ContextKeyExpr.or(NOTEBOOK_INTERRUPTIBLE_KERNEL.toNegated(), NOTEBOOK_HAS_SOMETHING_RUNNING.toNegated()), ContextKeyExpr.notEquals('config.notebook.globalToolbar', true) ) }, { id: MenuId.NotebookToolbar, order: -1, group: 'navigation/execute', when: ContextKeyExpr.and( executeNotebookCondition, ContextKeyExpr.or( NOTEBOOK_INTERRUPTIBLE_KERNEL.toNegated(), NOTEBOOK_HAS_SOMETHING_RUNNING.toNegated(), ), ContextKeyExpr.and(NOTEBOOK_HAS_SOMETHING_RUNNING, NOTEBOOK_INTERRUPTIBLE_KERNEL.toNegated())?.negate(), ContextKeyExpr.equals('config.notebook.globalToolbar', true) ) } ] }); } override getEditorContextFromArgsOrActive(accessor: ServicesAccessor, context?: UriComponents): INotebookActionContext | undefined { return getContextFromUri(accessor, context) ?? getContextFromActiveEditor(accessor.get(IEditorService)); } async runWithContext(accessor: ServicesAccessor, context: INotebookActionContext): Promise<void> { renderAllMarkdownCells(context); const editorService = accessor.get(IEditorService); const editor = editorService.getEditors(EditorsOrder.MOST_RECENTLY_ACTIVE).find( editor => editor.editor instanceof NotebookEditorInput && editor.editor.viewType === context.notebookEditor.textModel.viewType && editor.editor.resource.toString() === context.notebookEditor.textModel.uri.toString()); const editorGroupService = accessor.get(IEditorGroupsService); if (editor) { const group = editorGroupService.getGroup(editor.groupId); group?.pinEditor(editor.editor); } return context.notebookEditor.executeNotebookCells(); } }); registerAction2(class ExecuteCell extends NotebookMultiCellAction { constructor() { super({ id: EXECUTE_CELL_COMMAND_ID, precondition: executeThisCellCondition, title: localize('notebookActions.execute', "Execute Cell"), keybinding: { when: NOTEBOOK_CELL_LIST_FOCUSED, primary: KeyMod.WinCtrl | KeyCode.Enter, win: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.Enter }, weight: NOTEBOOK_EDITOR_WIDGET_ACTION_WEIGHT }, menu: { id: MenuId.NotebookCellExecutePrimary, when: executeThisCellCondition, group: 'inline' }, metadata: { description: localize('notebookActions.execute', "Execute Cell"), args: cellExecutionArgs }, icon: icons.executeIcon }); } override parseArgs(accessor: ServicesAccessor, ...args: any[]): INotebookCommandContext | undefined { return parseMultiCellExecutionArgs(accessor, ...args); } async runWithContext(accessor: ServicesAccessor, context: INotebookCommandContext | INotebookCellToolbarActionContext): Promise<void> { const editorGroupsService = accessor.get(IEditorGroupsService); if (context.ui) { await context.notebookEditor.focusNotebookCell(context.cell, 'container', { skipReveal: true }); } await runCell(editorGroupsService, context); } }); registerAction2(class ExecuteAboveCells extends NotebookMultiCellAction { constructor() { super({ id: EXECUTE_CELLS_ABOVE, precondition: executeCondition, title: localize('notebookActions.executeAbove', "Execute Above Cells"), menu: [ { id: MenuId.NotebookCellExecute, when: ContextKeyExpr.and( executeCondition, ContextKeyExpr.equals(`config.${NotebookSetting.consolidatedRunButton}`, true)) }, { id: MenuId.NotebookCellTitle, order: CellToolbarOrder.ExecuteAboveCells, group: CELL_TITLE_CELL_GROUP_ID, when: ContextKeyExpr.and( executeCondition, ContextKeyExpr.equals(`config.${NotebookSetting.consolidatedRunButton}`, false)) } ], icon: icons.executeAboveIcon }); } override parseArgs(accessor: ServicesAccessor, ...args: any[]): INotebookCommandContext | undefined { return parseMultiCellExecutionArgs(accessor, ...args); } async runWithContext(accessor: ServicesAccessor, context: INotebookCommandContext | INotebookCellToolbarActionContext): Promise<void> { let endCellIdx: number | undefined = undefined; if (context.ui) { endCellIdx = context.notebookEditor.getCellIndex(context.cell); await context.notebookEditor.focusNotebookCell(context.cell, 'container', { skipReveal: true }); } else { endCellIdx = Math.min(...context.selectedCells.map(cell => context.notebookEditor.getCellIndex(cell))); } if (typeof endCellIdx === 'number') { const range = { start: 0, end: endCellIdx }; const cells = context.notebookEditor.getCellsInRange(range); context.notebookEditor.executeNotebookCells(cells); } } }); registerAction2(class ExecuteCellAndBelow extends NotebookMultiCellAction { constructor() { super({ id: EXECUTE_CELL_AND_BELOW, precondition: executeCondition, title: localize('notebookActions.executeBelow', "Execute Cell and Below"), menu: [ { id: MenuId.NotebookCellExecute, when: ContextKeyExpr.and( executeCondition, ContextKeyExpr.equals(`config.${NotebookSetting.consolidatedRunButton}`, true)) }, { id: MenuId.NotebookCellTitle, order: CellToolbarOrder.ExecuteCellAndBelow, group: CELL_TITLE_CELL_GROUP_ID, when: ContextKeyExpr.and( executeCondition, ContextKeyExpr.equals(`config.${NotebookSetting.consolidatedRunButton}`, false)) } ], icon: icons.executeBelowIcon }); } override parseArgs(accessor: ServicesAccessor, ...args: any[]): INotebookCommandContext | undefined { return parseMultiCellExecutionArgs(accessor, ...args); } async runWithContext(accessor: ServicesAccessor, context: INotebookCommandContext | INotebookCellToolbarActionContext): Promise<void> { let startCellIdx: number | undefined = undefined; if (context.ui) { startCellIdx = context.notebookEditor.getCellIndex(context.cell); await context.notebookEditor.focusNotebookCell(context.cell, 'container', { skipReveal: true }); } else { startCellIdx = Math.min(...context.selectedCells.map(cell => context.notebookEditor.getCellIndex(cell))); } if (typeof startCellIdx === 'number') { const range = { start: startCellIdx, end: context.notebookEditor.getLength() }; const cells = context.notebookEditor.getCellsInRange(range); context.notebookEditor.executeNotebookCells(cells); } } }); registerAction2(class ExecuteCellFocusContainer extends NotebookMultiCellAction { constructor() { super({ id: EXECUTE_CELL_FOCUS_CONTAINER_COMMAND_ID, precondition: executeThisCellCondition, title: localize('notebookActions.executeAndFocusContainer', "Execute Cell and Focus Container"), metadata: { description: localize('notebookActions.executeAndFocusContainer', "Execute Cell and Focus Container"), args: cellExecutionArgs }, icon: icons.executeIcon }); } override parseArgs(accessor: ServicesAccessor, ...args: any[]): INotebookCommandContext | undefined { return parseMultiCellExecutionArgs(accessor, ...args); } async runWithContext(accessor: ServicesAccessor, context: INotebookCommandContext | INotebookCellToolbarActionContext): Promise<void> { const editorGroupsService = accessor.get(IEditorGroupsService); if (context.ui) { await context.notebookEditor.focusNotebookCell(context.cell, 'container', { skipReveal: true }); } else { const firstCell = context.selectedCells[0]; if (firstCell) { await context.notebookEditor.focusNotebookCell(firstCell, 'container', { skipReveal: true }); } } await runCell(editorGroupsService, context); } }); const cellCancelCondition = ContextKeyExpr.or( ContextKeyExpr.equals(NOTEBOOK_CELL_EXECUTION_STATE.key, 'executing'), ContextKeyExpr.equals(NOTEBOOK_CELL_EXECUTION_STATE.key, 'pending'), ); registerAction2(class CancelExecuteCell extends NotebookMultiCellAction { constructor() { super({ id: CANCEL_CELL_COMMAND_ID, precondition: cellCancelCondition, title: localize('notebookActions.cancel', "Stop Cell Execution"), icon: icons.stopIcon, menu: { id: MenuId.NotebookCellExecutePrimary, when: cellCancelCondition, group: 'inline' }, metadata: { description: localize('notebookActions.cancel', "Stop Cell Execution"), args: [ { name: 'options', description: 'The cell range options', schema: { 'type': 'object', 'required': ['ranges'], 'properties': { 'ranges': { 'type': 'array', items: [ { 'type': 'object', 'required': ['start', 'end'], 'properties': { 'start': { 'type': 'number' }, 'end': { 'type': 'number' } } } ] }, 'document': { 'type': 'object', 'description': 'The document uri', } } } } ] }, }); } override parseArgs(accessor: ServicesAccessor, ...args: any[]): INotebookCommandContext | undefined { return parseMultiCellExecutionArgs(accessor, ...args); } async runWithContext(accessor: ServicesAccessor, context: INotebookCommandContext | INotebookCellToolbarActionContext): Promise<void> { if (context.ui) { await context.notebookEditor.focusNotebookCell(context.cell, 'container', { skipReveal: true }); return context.notebookEditor.cancelNotebookCells(Iterable.single(context.cell)); } else { return context.notebookEditor.cancelNotebookCells(context.selectedCells); } } }); registerAction2(class ExecuteCellSelectBelow extends NotebookCellAction { constructor() { super({ id: EXECUTE_CELL_SELECT_BELOW, precondition: ContextKeyExpr.or(executeThisCellCondition, NOTEBOOK_CELL_TYPE.isEqualTo('markup')), title: localize('notebookActions.executeAndSelectBelow', "Execute Notebook Cell and Select Below"), keybinding: { when: ContextKeyExpr.and( NOTEBOOK_CELL_LIST_FOCUSED, CTX_INLINE_CHAT_FOCUSED.negate() ), primary: KeyMod.Shift | KeyCode.Enter, weight: NOTEBOOK_EDITOR_WIDGET_ACTION_WEIGHT }, }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext): Promise<void> { const editorGroupsService = accessor.get(IEditorGroupsService); const idx = context.notebookEditor.getCellIndex(context.cell); if (typeof idx !== 'number') { return; } const languageService = accessor.get(ILanguageService); const config = accessor.get(IConfigurationService); const scrollBehavior = config.getValue(NotebookSetting.scrollToRevealCell); let focusOptions: IFocusNotebookCellOptions; if (scrollBehavior === 'none') { focusOptions = { skipReveal: true }; } else { focusOptions = { revealBehavior: scrollBehavior === 'fullCell' ? ScrollToRevealBehavior.fullCell : ScrollToRevealBehavior.firstLine }; } if (context.cell.cellKind === CellKind.Markup) { const nextCell = context.notebookEditor.cellAt(idx + 1); context.cell.updateEditState(CellEditState.Preview, EXECUTE_CELL_SELECT_BELOW); if (nextCell) { await context.notebookEditor.focusNotebookCell(nextCell, 'container', focusOptions); } else { const newCell = insertCell(languageService, context.notebookEditor, idx, CellKind.Markup, 'below'); if (newCell) { await context.notebookEditor.focusNotebookCell(newCell, 'editor', focusOptions); } } return; } else { const nextCell = context.notebookEditor.cellAt(idx + 1); if (nextCell) { await context.notebookEditor.focusNotebookCell(nextCell, 'container', focusOptions); } else { const newCell = insertCell(languageService, context.notebookEditor, idx, CellKind.Code, 'below'); if (newCell) { await context.notebookEditor.focusNotebookCell(newCell, 'editor', focusOptions); } } return runCell(editorGroupsService, context); } } }); registerAction2(class ExecuteCellInsertBelow extends NotebookCellAction { constructor() { super({ id: EXECUTE_CELL_INSERT_BELOW, precondition: ContextKeyExpr.or(executeThisCellCondition, NOTEBOOK_CELL_TYPE.isEqualTo('markup')), title: localize('notebookActions.executeAndInsertBelow', "Execute Notebook Cell and Insert Below"), keybinding: { when: NOTEBOOK_CELL_LIST_FOCUSED, primary: KeyMod.Alt | KeyCode.Enter, weight: NOTEBOOK_EDITOR_WIDGET_ACTION_WEIGHT }, }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext): Promise<void> { const editorGroupsService = accessor.get(IEditorGroupsService); const idx = context.notebookEditor.getCellIndex(context.cell); const languageService = accessor.get(ILanguageService); const newFocusMode = context.cell.focusMode === CellFocusMode.Editor ? 'editor' : 'container'; const newCell = insertCell(languageService, context.notebookEditor, idx, context.cell.cellKind, 'below'); if (newCell) { await context.notebookEditor.focusNotebookCell(newCell, newFocusMode); } if (context.cell.cellKind === CellKind.Markup) { context.cell.updateEditState(CellEditState.Preview, EXECUTE_CELL_INSERT_BELOW); } else { runCell(editorGroupsService, context); } } }); class CancelNotebook extends NotebookAction { override getEditorContextFromArgsOrActive(accessor: ServicesAccessor, context?: UriComponents): INotebookActionContext | undefined { return getContextFromUri(accessor, context) ?? getContextFromActiveEditor(accessor.get(IEditorService)); } async runWithContext(accessor: ServicesAccessor, context: INotebookActionContext): Promise<void> { return context.notebookEditor.cancelNotebookCells(); } } registerAction2(class CancelAllNotebook extends CancelNotebook { constructor() { super({ id: CANCEL_NOTEBOOK_COMMAND_ID, title: localize2('notebookActions.cancelNotebook', "Stop Execution"), icon: icons.stopIcon, menu: [ { id: MenuId.EditorTitle, order: -1, group: 'navigation', when: ContextKeyExpr.and( NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_HAS_SOMETHING_RUNNING, NOTEBOOK_INTERRUPTIBLE_KERNEL.toNegated(), ContextKeyExpr.notEquals('config.notebook.globalToolbar', true) ) }, { id: MenuId.NotebookToolbar, order: -1, group: 'navigation/execute', when: ContextKeyExpr.and( NOTEBOOK_HAS_SOMETHING_RUNNING, NOTEBOOK_INTERRUPTIBLE_KERNEL.toNegated(), ContextKeyExpr.equals('config.notebook.globalToolbar', true) ) } ] }); } }); registerAction2(class InterruptNotebook extends CancelNotebook { constructor() { super({ id: INTERRUPT_NOTEBOOK_COMMAND_ID, title: localize2('notebookActions.interruptNotebook', "Interrupt"), precondition: ContextKeyExpr.and( NOTEBOOK_HAS_SOMETHING_RUNNING, NOTEBOOK_INTERRUPTIBLE_KERNEL ), icon: icons.stopIcon, menu: [ { id: MenuId.EditorTitle, order: -1, group: 'navigation', when: ContextKeyExpr.and( NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_HAS_SOMETHING_RUNNING, NOTEBOOK_INTERRUPTIBLE_KERNEL, ContextKeyExpr.notEquals('config.notebook.globalToolbar', true) ) }, { id: MenuId.NotebookToolbar, order: -1, group: 'navigation/execute', when: ContextKeyExpr.and( NOTEBOOK_HAS_SOMETHING_RUNNING, NOTEBOOK_INTERRUPTIBLE_KERNEL, ContextKeyExpr.equals('config.notebook.globalToolbar', true) ) }, { id: MenuId.InteractiveToolbar, group: 'navigation/execute' } ] }); } }); MenuRegistry.appendMenuItem(MenuId.NotebookToolbar, { title: localize('revealRunningCellShort', "Go To"), submenu: MenuId.NotebookCellExecuteGoTo, group: 'navigation/execute', order: 20, icon: ThemeIcon.modify(icons.executingStateIcon, 'spin') }); registerAction2(class RevealRunningCellAction extends NotebookAction { constructor() { super({ id: REVEAL_RUNNING_CELL, title: localize('revealRunningCell', "Go to Running Cell"), tooltip: localize('revealRunningCell', "Go to Running Cell"), shortTitle: localize('revealRunningCell', "Go to Running Cell"), precondition: NOTEBOOK_HAS_RUNNING_CELL, menu: [ { id: MenuId.EditorTitle, when: ContextKeyExpr.and( NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_HAS_RUNNING_CELL, ContextKeyExpr.notEquals('config.notebook.globalToolbar', true) ), group: 'navigation', order: 0 }, { id: MenuId.NotebookCellExecuteGoTo, when: ContextKeyExpr.and( NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_HAS_RUNNING_CELL, ContextKeyExpr.equals('config.notebook.globalToolbar', true) ), group: 'navigation/execute', order: 20 }, { id: MenuId.InteractiveToolbar, when: ContextKeyExpr.and( NOTEBOOK_HAS_RUNNING_CELL, ContextKeyExpr.equals('activeEditor', 'workbench.editor.interactive') ), group: 'navigation', order: 10 } ], icon: ThemeIcon.modify(icons.executingStateIcon, 'spin') }); } async runWithContext(accessor: ServicesAccessor, context: INotebookActionContext): Promise<void> { const notebookExecutionStateService = accessor.get(INotebookExecutionStateService); const notebook = context.notebookEditor.textModel.uri; const executingCells = notebookExecutionStateService.getCellExecutionsForNotebook(notebook); if (executingCells[0]) { const topStackFrameCell = this.findCellAtTopFrame(accessor, notebook); const focusHandle = topStackFrameCell ?? executingCells[0].cellHandle; const cell = context.notebookEditor.getCellByHandle(focusHandle); if (cell) { context.notebookEditor.focusNotebookCell(cell, 'container'); } } } private findCellAtTopFrame(accessor: ServicesAccessor, notebook: URI): number | undefined { const debugService = accessor.get(IDebugService); for (const session of debugService.getModel().getSessions()) { for (const thread of session.getAllThreads()) { const sf = thread.getTopStackFrame(); if (sf) { const parsed = CellUri.parse(sf.source.uri); if (parsed && parsed.notebook.toString() === notebook.toString()) { return parsed.handle; } } } } return undefined; } }); registerAction2(class RevealLastFailedCellAction extends NotebookAction { constructor() { super({ id: REVEAL_LAST_FAILED_CELL, title: localize('revealLastFailedCell', "Go to Most Recently Failed Cell"), tooltip: localize('revealLastFailedCell', "Go to Most Recently Failed Cell"), shortTitle: localize('revealLastFailedCellShort', "Go to Most Recently Failed Cell"), precondition: NOTEBOOK_LAST_CELL_FAILED, menu: [ { id: MenuId.EditorTitle, when: ContextKeyExpr.and( NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_LAST_CELL_FAILED, NOTEBOOK_HAS_RUNNING_CELL.toNegated(), ContextKeyExpr.notEquals('config.notebook.globalToolbar', true) ), group: 'navigation', order: 0 }, { id: MenuId.NotebookCellExecuteGoTo, when: ContextKeyExpr.and( NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_LAST_CELL_FAILED, NOTEBOOK_HAS_RUNNING_CELL.toNegated(), ContextKeyExpr.equals('config.notebook.globalToolbar', true) ), group: 'navigation/execute', order: 20 }, ], icon: icons.errorStateIcon, }); } async runWithContext(accessor: ServicesAccessor, context: INotebookActionContext): Promise<void> { const notebookExecutionStateService = accessor.get(INotebookExecutionStateService); const notebook = context.notebookEditor.textModel.uri; const lastFailedCellHandle = notebookExecutionStateService.getLastFailedCellForNotebook(notebook); if (lastFailedCellHandle !== undefined) { const lastFailedCell = context.notebookEditor.getCellByHandle(lastFailedCellHandle); if (lastFailedCell) { context.notebookEditor.focusNotebookCell(lastFailedCell, 'container'); } } } });
src/vs/workbench/contrib/notebook/browser/controller/executeActions.ts
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.001251592650078237, 0.00019019271712750196, 0.0001636108208913356, 0.00017112534260377288, 0.0001292734668822959 ]
{ "id": 1, "code_window": [ " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: vscode_cli_alpine_x64_cli\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}" ], "file_path": "build/azure-pipelines/alpine/cli-build-alpine.yml", "type": "add", "edit_start_line_idx": 100 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CancellationToken } from 'vs/base/common/cancellation'; import { Disposable, DisposableMap } from 'vs/base/common/lifecycle'; import { ExtHostAiRelatedInformationShape, ExtHostContext, MainContext, MainThreadAiRelatedInformationShape } from 'vs/workbench/api/common/extHost.protocol'; import { RelatedInformationType } from 'vs/workbench/api/common/extHostTypes'; import { IAiRelatedInformationProvider, IAiRelatedInformationService, RelatedInformationResult } from 'vs/workbench/services/aiRelatedInformation/common/aiRelatedInformation'; import { IExtHostContext, extHostNamedCustomer } from 'vs/workbench/services/extensions/common/extHostCustomers'; @extHostNamedCustomer(MainContext.MainThreadAiRelatedInformation) export class MainThreadAiRelatedInformation extends Disposable implements MainThreadAiRelatedInformationShape { private readonly _proxy: ExtHostAiRelatedInformationShape; private readonly _registrations = this._register(new DisposableMap<number>()); constructor( context: IExtHostContext, @IAiRelatedInformationService private readonly _aiRelatedInformationService: IAiRelatedInformationService, ) { super(); this._proxy = context.getProxy(ExtHostContext.ExtHostAiRelatedInformation); } $getAiRelatedInformation(query: string, types: RelatedInformationType[]): Promise<RelatedInformationResult[]> { // TODO: use a real cancellation token return this._aiRelatedInformationService.getRelatedInformation(query, types, CancellationToken.None); } $registerAiRelatedInformationProvider(handle: number, type: RelatedInformationType): void { const provider: IAiRelatedInformationProvider = { provideAiRelatedInformation: (query, token) => { return this._proxy.$provideAiRelatedInformation(handle, query, token); }, }; this._registrations.set(handle, this._aiRelatedInformationService.registerAiRelatedInformationProvider(type, provider)); } $unregisterAiRelatedInformationProvider(handle: number): void { this._registrations.deleteAndDispose(handle); } }
src/vs/workbench/api/browser/mainThreadAiRelatedInformation.ts
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.00017171473882626742, 0.00016998822684399784, 0.0001675491948844865, 0.00016977684572339058, 0.0000015001171504991362 ]
{ "id": 2, "code_window": [ " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_darwin_x64_cli\n", "\n", " - ${{ if eq(parameters.VSCODE_BUILD_MACOS_ARM64, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_darwin_arm64_cli\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}\n" ], "file_path": "build/azure-pipelines/darwin/cli-build-darwin.yml", "type": "add", "edit_start_line_idx": 72 }
parameters: - name: VSCODE_BUILD_ALPINE type: boolean default: false - name: VSCODE_BUILD_ALPINE_ARM64 type: boolean default: false - name: VSCODE_QUALITY type: string steps: - task: NodeTool@0 inputs: versionSource: fromFile versionFilePath: .nvmrc nodejsMirror: https://github.com/joaomoreno/node-mirror/releases/download - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: # Install yarn as the ARM64 build agent is using vanilla Ubuntu - ${{ if eq(parameters.VSCODE_BUILD_ALPINE_ARM64, true) }}: - task: Npm@1 displayName: Install yarn inputs: command: custom customCommand: install --global yarn - script: | set -e yarn --frozen-lockfile --ignore-optional workingDirectory: build displayName: Install pipeline build - template: ../cli/cli-apply-patches.yml - task: Npm@1 displayName: Download openssl prebuilt inputs: command: custom customCommand: pack @vscode-internal/[email protected] customRegistry: useFeed customFeed: "Monaco/openssl-prebuilt" workingDir: $(Build.ArtifactStagingDirectory) - script: | set -e mkdir $(Build.ArtifactStagingDirectory)/openssl tar -xvzf $(Build.ArtifactStagingDirectory)/vscode-internal-openssl-prebuilt-0.0.11.tgz --strip-components=1 --directory=$(Build.ArtifactStagingDirectory)/openssl displayName: Extract openssl prebuilt # inspired by: https://github.com/emk/rust-musl-builder/blob/main/Dockerfile - bash: | set -e sudo apt-get update sudo apt-get install -yq build-essential musl-dev musl-tools linux-libc-dev pkgconf xutils-dev lld sudo ln -s "/usr/bin/g++" "/usr/bin/musl-g++" || echo "link exists" displayName: Install musl build dependencies - template: ../cli/install-rust-posix.yml parameters: targets: - ${{ if eq(parameters.VSCODE_BUILD_ALPINE_ARM64, true) }}: - aarch64-unknown-linux-musl - ${{ if eq(parameters.VSCODE_BUILD_ALPINE, true) }}: - x86_64-unknown-linux-musl - ${{ if eq(parameters.VSCODE_BUILD_ALPINE_ARM64, true) }}: - template: ../cli/cli-compile.yml parameters: VSCODE_CLI_TARGET: aarch64-unknown-linux-musl VSCODE_CLI_ARTIFACT: vscode_cli_alpine_arm64_cli VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_CLI_ENV: CXX_aarch64-unknown-linux-musl: musl-g++ CC_aarch64-unknown-linux-musl: musl-gcc OPENSSL_LIB_DIR: $(Build.ArtifactStagingDirectory)/openssl/arm64-linux-musl/lib OPENSSL_INCLUDE_DIR: $(Build.ArtifactStagingDirectory)/openssl/arm64-linux-musl/include OPENSSL_STATIC: "1" - ${{ if eq(parameters.VSCODE_BUILD_ALPINE, true) }}: - template: ../cli/cli-compile.yml parameters: VSCODE_CLI_TARGET: x86_64-unknown-linux-musl VSCODE_CLI_ARTIFACT: vscode_cli_alpine_x64_cli VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_CLI_ENV: CXX_aarch64-unknown-linux-musl: musl-g++ CC_aarch64-unknown-linux-musl: musl-gcc OPENSSL_LIB_DIR: $(Build.ArtifactStagingDirectory)/openssl/x64-linux-musl/lib OPENSSL_INCLUDE_DIR: $(Build.ArtifactStagingDirectory)/openssl/x64-linux-musl/include OPENSSL_STATIC: "1" - ${{ if eq(parameters.VSCODE_BUILD_ALPINE_ARM64, true) }}: - template: ../cli/cli-publish.yml parameters: VSCODE_CLI_ARTIFACT: vscode_cli_alpine_arm64_cli - ${{ if eq(parameters.VSCODE_BUILD_ALPINE, true) }}: - template: ../cli/cli-publish.yml parameters: VSCODE_CLI_ARTIFACT: vscode_cli_alpine_x64_cli
build/azure-pipelines/alpine/cli-build-alpine.yml
1
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.13810692727565765, 0.027128081768751144, 0.00016944239905569702, 0.002329528331756592, 0.04064931720495224 ]
{ "id": 2, "code_window": [ " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_darwin_x64_cli\n", "\n", " - ${{ if eq(parameters.VSCODE_BUILD_MACOS_ARM64, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_darwin_arm64_cli\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}\n" ], "file_path": "build/azure-pipelines/darwin/cli-build-darwin.yml", "type": "add", "edit_start_line_idx": 72 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { main } from './sign'; import * as path from 'path'; main([ process.env['EsrpCliDllPath']!, 'sign-windows', process.env['ESRPPKI']!, process.env['ESRPAADUsername']!, process.env['ESRPAADPassword']!, path.dirname(process.argv[2]), path.basename(process.argv[2]) ]);
build/azure-pipelines/common/sign-win32.ts
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.0001704027090454474, 0.0001686536124907434, 0.0001669045159360394, 0.0001686536124907434, 0.0000017490965547040105 ]
{ "id": 2, "code_window": [ " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_darwin_x64_cli\n", "\n", " - ${{ if eq(parameters.VSCODE_BUILD_MACOS_ARM64, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_darwin_arm64_cli\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}\n" ], "file_path": "build/azure-pipelines/darwin/cli-build-darwin.yml", "type": "add", "edit_start_line_idx": 72 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { SequencerByKey } from 'vs/base/common/async'; import { IEncryptionService } from 'vs/platform/encryption/common/encryptionService'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { IStorageService, InMemoryStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage'; import { Emitter, Event } from 'vs/base/common/event'; import { ILogService } from 'vs/platform/log/common/log'; import { Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import { Lazy } from 'vs/base/common/lazy'; export const ISecretStorageService = createDecorator<ISecretStorageService>('secretStorageService'); export interface ISecretStorageProvider { type: 'in-memory' | 'persisted' | 'unknown'; get(key: string): Promise<string | undefined>; set(key: string, value: string): Promise<void>; delete(key: string): Promise<void>; } export interface ISecretStorageService extends ISecretStorageProvider { readonly _serviceBrand: undefined; onDidChangeSecret: Event<string>; } export class BaseSecretStorageService extends Disposable implements ISecretStorageService { declare readonly _serviceBrand: undefined; private readonly _storagePrefix = 'secret://'; protected readonly onDidChangeSecretEmitter = this._register(new Emitter<string>()); onDidChangeSecret: Event<string> = this.onDidChangeSecretEmitter.event; protected readonly _sequencer = new SequencerByKey<string>(); private _type: 'in-memory' | 'persisted' | 'unknown' = 'unknown'; private readonly _onDidChangeValueDisposable = this._register(new DisposableStore()); constructor( private readonly _useInMemoryStorage: boolean, @IStorageService private _storageService: IStorageService, @IEncryptionService protected _encryptionService: IEncryptionService, @ILogService protected readonly _logService: ILogService, ) { super(); } /** * @Note initialize must be called first so that this can be resolved properly * otherwise it will return 'unknown'. */ get type() { return this._type; } private _lazyStorageService: Lazy<Promise<IStorageService>> = new Lazy(() => this.initialize()); protected get resolvedStorageService() { return this._lazyStorageService.value; } get(key: string): Promise<string | undefined> { return this._sequencer.queue(key, async () => { const storageService = await this.resolvedStorageService; const fullKey = this.getKey(key); this._logService.trace('[secrets] getting secret for key:', fullKey); const encrypted = storageService.get(fullKey, StorageScope.APPLICATION); if (!encrypted) { this._logService.trace('[secrets] no secret found for key:', fullKey); return undefined; } try { this._logService.trace('[secrets] decrypting gotten secret for key:', fullKey); // If the storage service is in-memory, we don't need to decrypt const result = this._type === 'in-memory' ? encrypted : await this._encryptionService.decrypt(encrypted); this._logService.trace('[secrets] decrypted secret for key:', fullKey); return result; } catch (e) { this._logService.error(e); this.delete(key); return undefined; } }); } set(key: string, value: string): Promise<void> { return this._sequencer.queue(key, async () => { const storageService = await this.resolvedStorageService; this._logService.trace('[secrets] encrypting secret for key:', key); let encrypted; try { // If the storage service is in-memory, we don't need to encrypt encrypted = this._type === 'in-memory' ? value : await this._encryptionService.encrypt(value); } catch (e) { this._logService.error(e); throw e; } const fullKey = this.getKey(key); this._logService.trace('[secrets] storing encrypted secret for key:', fullKey); storageService.store(fullKey, encrypted, StorageScope.APPLICATION, StorageTarget.MACHINE); this._logService.trace('[secrets] stored encrypted secret for key:', fullKey); }); } delete(key: string): Promise<void> { return this._sequencer.queue(key, async () => { const storageService = await this.resolvedStorageService; const fullKey = this.getKey(key); this._logService.trace('[secrets] deleting secret for key:', fullKey); storageService.remove(fullKey, StorageScope.APPLICATION); this._logService.trace('[secrets] deleted secret for key:', fullKey); }); } private async initialize(): Promise<IStorageService> { let storageService; if (!this._useInMemoryStorage && await this._encryptionService.isEncryptionAvailable()) { this._logService.trace(`[SecretStorageService] Encryption is available, using persisted storage`); this._type = 'persisted'; storageService = this._storageService; } else { // If we already have an in-memory storage service, we don't need to recreate it if (this._type === 'in-memory') { return this._storageService; } this._logService.trace('[SecretStorageService] Encryption is not available, falling back to in-memory storage'); this._type = 'in-memory'; storageService = this._register(new InMemoryStorageService()); } this._onDidChangeValueDisposable.clear(); this._onDidChangeValueDisposable.add(storageService.onDidChangeValue(StorageScope.APPLICATION, undefined, this._onDidChangeValueDisposable)(e => { this.onDidChangeValue(e.key); })); return storageService; } protected reinitialize(): void { this._lazyStorageService = new Lazy(() => this.initialize()); } private onDidChangeValue(key: string): void { if (!key.startsWith(this._storagePrefix)) { return; } const secretKey = key.slice(this._storagePrefix.length); this._logService.trace(`[SecretStorageService] Notifying change in value for secret: ${secretKey}`); this.onDidChangeSecretEmitter.fire(secretKey); } private getKey(key: string): string { return `${this._storagePrefix}${key}`; } }
src/vs/platform/secrets/common/secrets.ts
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.00017549323092680424, 0.00017103890422731638, 0.0001663266884861514, 0.00017096713418141007, 0.000002387787390034646 ]
{ "id": 2, "code_window": [ " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_darwin_x64_cli\n", "\n", " - ${{ if eq(parameters.VSCODE_BUILD_MACOS_ARM64, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_darwin_arm64_cli\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}\n" ], "file_path": "build/azure-pipelines/darwin/cli-build-darwin.yml", "type": "add", "edit_start_line_idx": 72 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { strictEqual } from 'assert'; import { getUNCHost } from 'vs/base/node/unc'; import { ensureNoDisposablesAreLeakedInTestSuite } from 'vs/base/test/common/utils'; suite('UNC', () => { test('getUNCHost', () => { strictEqual(getUNCHost(undefined), undefined); strictEqual(getUNCHost(null), undefined); strictEqual(getUNCHost('/'), undefined); strictEqual(getUNCHost('/foo'), undefined); strictEqual(getUNCHost('c:'), undefined); strictEqual(getUNCHost('c:\\'), undefined); strictEqual(getUNCHost('c:\\foo'), undefined); strictEqual(getUNCHost('c:\\foo\\\\server\\path'), undefined); strictEqual(getUNCHost('\\'), undefined); strictEqual(getUNCHost('\\\\'), undefined); strictEqual(getUNCHost('\\\\localhost'), undefined); strictEqual(getUNCHost('\\\\localhost\\'), 'localhost'); strictEqual(getUNCHost('\\\\localhost\\a'), 'localhost'); strictEqual(getUNCHost('\\\\.'), undefined); strictEqual(getUNCHost('\\\\?'), undefined); strictEqual(getUNCHost('\\\\.\\localhost'), '.'); strictEqual(getUNCHost('\\\\?\\localhost'), '?'); strictEqual(getUNCHost('\\\\.\\UNC\\localhost'), '.'); strictEqual(getUNCHost('\\\\?\\UNC\\localhost'), '?'); strictEqual(getUNCHost('\\\\.\\UNC\\localhost\\'), 'localhost'); strictEqual(getUNCHost('\\\\?\\UNC\\localhost\\'), 'localhost'); strictEqual(getUNCHost('\\\\.\\UNC\\localhost\\a'), 'localhost'); strictEqual(getUNCHost('\\\\?\\UNC\\localhost\\a'), 'localhost'); }); ensureNoDisposablesAreLeakedInTestSuite(); });
src/vs/base/test/node/unc.test.ts
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.0001725964102661237, 0.0001702321897028014, 0.00016926122771110386, 0.0001693306548986584, 0.000001301206111747888 ]
{ "id": 3, "code_window": [ " - ${{ if eq(parameters.VSCODE_BUILD_MACOS_ARM64, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_darwin_arm64_cli\n" ], "labels": [ "keep", "keep", "keep", "add" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}" ], "file_path": "build/azure-pipelines/darwin/cli-build-darwin.yml", "type": "add", "edit_start_line_idx": 77 }
parameters: - name: VSCODE_BUILD_ALPINE type: boolean default: false - name: VSCODE_BUILD_ALPINE_ARM64 type: boolean default: false - name: VSCODE_QUALITY type: string steps: - task: NodeTool@0 inputs: versionSource: fromFile versionFilePath: .nvmrc nodejsMirror: https://github.com/joaomoreno/node-mirror/releases/download - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: # Install yarn as the ARM64 build agent is using vanilla Ubuntu - ${{ if eq(parameters.VSCODE_BUILD_ALPINE_ARM64, true) }}: - task: Npm@1 displayName: Install yarn inputs: command: custom customCommand: install --global yarn - script: | set -e yarn --frozen-lockfile --ignore-optional workingDirectory: build displayName: Install pipeline build - template: ../cli/cli-apply-patches.yml - task: Npm@1 displayName: Download openssl prebuilt inputs: command: custom customCommand: pack @vscode-internal/[email protected] customRegistry: useFeed customFeed: "Monaco/openssl-prebuilt" workingDir: $(Build.ArtifactStagingDirectory) - script: | set -e mkdir $(Build.ArtifactStagingDirectory)/openssl tar -xvzf $(Build.ArtifactStagingDirectory)/vscode-internal-openssl-prebuilt-0.0.11.tgz --strip-components=1 --directory=$(Build.ArtifactStagingDirectory)/openssl displayName: Extract openssl prebuilt # inspired by: https://github.com/emk/rust-musl-builder/blob/main/Dockerfile - bash: | set -e sudo apt-get update sudo apt-get install -yq build-essential musl-dev musl-tools linux-libc-dev pkgconf xutils-dev lld sudo ln -s "/usr/bin/g++" "/usr/bin/musl-g++" || echo "link exists" displayName: Install musl build dependencies - template: ../cli/install-rust-posix.yml parameters: targets: - ${{ if eq(parameters.VSCODE_BUILD_ALPINE_ARM64, true) }}: - aarch64-unknown-linux-musl - ${{ if eq(parameters.VSCODE_BUILD_ALPINE, true) }}: - x86_64-unknown-linux-musl - ${{ if eq(parameters.VSCODE_BUILD_ALPINE_ARM64, true) }}: - template: ../cli/cli-compile.yml parameters: VSCODE_CLI_TARGET: aarch64-unknown-linux-musl VSCODE_CLI_ARTIFACT: vscode_cli_alpine_arm64_cli VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_CLI_ENV: CXX_aarch64-unknown-linux-musl: musl-g++ CC_aarch64-unknown-linux-musl: musl-gcc OPENSSL_LIB_DIR: $(Build.ArtifactStagingDirectory)/openssl/arm64-linux-musl/lib OPENSSL_INCLUDE_DIR: $(Build.ArtifactStagingDirectory)/openssl/arm64-linux-musl/include OPENSSL_STATIC: "1" - ${{ if eq(parameters.VSCODE_BUILD_ALPINE, true) }}: - template: ../cli/cli-compile.yml parameters: VSCODE_CLI_TARGET: x86_64-unknown-linux-musl VSCODE_CLI_ARTIFACT: vscode_cli_alpine_x64_cli VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_CLI_ENV: CXX_aarch64-unknown-linux-musl: musl-g++ CC_aarch64-unknown-linux-musl: musl-gcc OPENSSL_LIB_DIR: $(Build.ArtifactStagingDirectory)/openssl/x64-linux-musl/lib OPENSSL_INCLUDE_DIR: $(Build.ArtifactStagingDirectory)/openssl/x64-linux-musl/include OPENSSL_STATIC: "1" - ${{ if eq(parameters.VSCODE_BUILD_ALPINE_ARM64, true) }}: - template: ../cli/cli-publish.yml parameters: VSCODE_CLI_ARTIFACT: vscode_cli_alpine_arm64_cli - ${{ if eq(parameters.VSCODE_BUILD_ALPINE, true) }}: - template: ../cli/cli-publish.yml parameters: VSCODE_CLI_ARTIFACT: vscode_cli_alpine_x64_cli
build/azure-pipelines/alpine/cli-build-alpine.yml
1
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.04300032928586006, 0.012966344133019447, 0.00016540165233891457, 0.0018759311642497778, 0.01627415418624878 ]
{ "id": 3, "code_window": [ " - ${{ if eq(parameters.VSCODE_BUILD_MACOS_ARM64, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_darwin_arm64_cli\n" ], "labels": [ "keep", "keep", "keep", "add" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}" ], "file_path": "build/azure-pipelines/darwin/cli-build-darwin.yml", "type": "add", "edit_start_line_idx": 77 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nodeCrypto from 'crypto'; export const crypto: Crypto = nodeCrypto.webcrypto as any;
extensions/microsoft-authentication/src/node/crypto.ts
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.00017384241800755262, 0.00017384241800755262, 0.00017384241800755262, 0.00017384241800755262, 0 ]
{ "id": 3, "code_window": [ " - ${{ if eq(parameters.VSCODE_BUILD_MACOS_ARM64, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_darwin_arm64_cli\n" ], "labels": [ "keep", "keep", "keep", "add" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}" ], "file_path": "build/azure-pipelines/darwin/cli-build-darwin.yml", "type": "add", "edit_start_line_idx": 77 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Emitter, Event } from 'vs/base/common/event'; import { IModelDecorationOptions, IModelDecorationsChangeAccessor, IModelDeltaDecoration, ITextModel } from 'vs/editor/common/model'; import { FoldingRegion, FoldingRegions, ILineRange, FoldRange, FoldSource } from './foldingRanges'; import { hash } from 'vs/base/common/hash'; export interface IDecorationProvider { getDecorationOption(isCollapsed: boolean, isHidden: boolean, isManual: boolean): IModelDecorationOptions; changeDecorations<T>(callback: (changeAccessor: IModelDecorationsChangeAccessor) => T): T | null; removeDecorations(decorationIds: string[]): void; } export interface FoldingModelChangeEvent { model: FoldingModel; collapseStateChanged?: FoldingRegion[]; } interface ILineMemento extends ILineRange { checksum?: number; isCollapsed?: boolean; source?: FoldSource; } export type CollapseMemento = ILineMemento[]; export class FoldingModel { private readonly _textModel: ITextModel; private readonly _decorationProvider: IDecorationProvider; private _regions: FoldingRegions; private _editorDecorationIds: string[]; private readonly _updateEventEmitter = new Emitter<FoldingModelChangeEvent>(); public readonly onDidChange: Event<FoldingModelChangeEvent> = this._updateEventEmitter.event; public get regions(): FoldingRegions { return this._regions; } public get textModel() { return this._textModel; } public get decorationProvider() { return this._decorationProvider; } constructor(textModel: ITextModel, decorationProvider: IDecorationProvider) { this._textModel = textModel; this._decorationProvider = decorationProvider; this._regions = new FoldingRegions(new Uint32Array(0), new Uint32Array(0)); this._editorDecorationIds = []; } public toggleCollapseState(toggledRegions: FoldingRegion[]) { if (!toggledRegions.length) { return; } toggledRegions = toggledRegions.sort((r1, r2) => r1.regionIndex - r2.regionIndex); const processed: { [key: string]: boolean | undefined } = {}; this._decorationProvider.changeDecorations(accessor => { let k = 0; // index from [0 ... this.regions.length] let dirtyRegionEndLine = -1; // end of the range where decorations need to be updated let lastHiddenLine = -1; // the end of the last hidden lines const updateDecorationsUntil = (index: number) => { while (k < index) { const endLineNumber = this._regions.getEndLineNumber(k); const isCollapsed = this._regions.isCollapsed(k); if (endLineNumber <= dirtyRegionEndLine) { const isManual = this.regions.getSource(k) !== FoldSource.provider; accessor.changeDecorationOptions(this._editorDecorationIds[k], this._decorationProvider.getDecorationOption(isCollapsed, endLineNumber <= lastHiddenLine, isManual)); } if (isCollapsed && endLineNumber > lastHiddenLine) { lastHiddenLine = endLineNumber; } k++; } }; for (const region of toggledRegions) { const index = region.regionIndex; const editorDecorationId = this._editorDecorationIds[index]; if (editorDecorationId && !processed[editorDecorationId]) { processed[editorDecorationId] = true; updateDecorationsUntil(index); // update all decorations up to current index using the old dirtyRegionEndLine const newCollapseState = !this._regions.isCollapsed(index); this._regions.setCollapsed(index, newCollapseState); dirtyRegionEndLine = Math.max(dirtyRegionEndLine, this._regions.getEndLineNumber(index)); } } updateDecorationsUntil(this._regions.length); }); this._updateEventEmitter.fire({ model: this, collapseStateChanged: toggledRegions }); } public removeManualRanges(ranges: ILineRange[]) { const newFoldingRanges: FoldRange[] = new Array(); const intersects = (foldRange: FoldRange) => { for (const range of ranges) { if (!(range.startLineNumber > foldRange.endLineNumber || foldRange.startLineNumber > range.endLineNumber)) { return true; } } return false; }; for (let i = 0; i < this._regions.length; i++) { const foldRange = this._regions.toFoldRange(i); if (foldRange.source === FoldSource.provider || !intersects(foldRange)) { newFoldingRanges.push(foldRange); } } this.updatePost(FoldingRegions.fromFoldRanges(newFoldingRanges)); } public update(newRegions: FoldingRegions, blockedLineNumers: number[] = []): void { const foldedOrManualRanges = this._currentFoldedOrManualRanges(blockedLineNumers); const newRanges = FoldingRegions.sanitizeAndMerge(newRegions, foldedOrManualRanges, this._textModel.getLineCount()); this.updatePost(FoldingRegions.fromFoldRanges(newRanges)); } public updatePost(newRegions: FoldingRegions) { const newEditorDecorations: IModelDeltaDecoration[] = []; let lastHiddenLine = -1; for (let index = 0, limit = newRegions.length; index < limit; index++) { const startLineNumber = newRegions.getStartLineNumber(index); const endLineNumber = newRegions.getEndLineNumber(index); const isCollapsed = newRegions.isCollapsed(index); const isManual = newRegions.getSource(index) !== FoldSource.provider; const decorationRange = { startLineNumber: startLineNumber, startColumn: this._textModel.getLineMaxColumn(startLineNumber), endLineNumber: endLineNumber, endColumn: this._textModel.getLineMaxColumn(endLineNumber) + 1 }; newEditorDecorations.push({ range: decorationRange, options: this._decorationProvider.getDecorationOption(isCollapsed, endLineNumber <= lastHiddenLine, isManual) }); if (isCollapsed && endLineNumber > lastHiddenLine) { lastHiddenLine = endLineNumber; } } this._decorationProvider.changeDecorations(accessor => this._editorDecorationIds = accessor.deltaDecorations(this._editorDecorationIds, newEditorDecorations)); this._regions = newRegions; this._updateEventEmitter.fire({ model: this }); } private _currentFoldedOrManualRanges(blockedLineNumers: number[] = []): FoldRange[] { const isBlocked = (startLineNumber: number, endLineNumber: number) => { for (const blockedLineNumber of blockedLineNumers) { if (startLineNumber < blockedLineNumber && blockedLineNumber <= endLineNumber) { // first line is visible return true; } } return false; }; const foldedRanges: FoldRange[] = []; for (let i = 0, limit = this._regions.length; i < limit; i++) { let isCollapsed = this.regions.isCollapsed(i); const source = this.regions.getSource(i); if (isCollapsed || source !== FoldSource.provider) { const foldRange = this._regions.toFoldRange(i); const decRange = this._textModel.getDecorationRange(this._editorDecorationIds[i]); if (decRange) { if (isCollapsed && isBlocked(decRange.startLineNumber, decRange.endLineNumber)) { isCollapsed = false; // uncollapse is the range is blocked } foldedRanges.push({ startLineNumber: decRange.startLineNumber, endLineNumber: decRange.endLineNumber, type: foldRange.type, isCollapsed, source }); } } } return foldedRanges; } /** * Collapse state memento, for persistence only */ public getMemento(): CollapseMemento | undefined { const foldedOrManualRanges = this._currentFoldedOrManualRanges(); const result: ILineMemento[] = []; const maxLineNumber = this._textModel.getLineCount(); for (let i = 0, limit = foldedOrManualRanges.length; i < limit; i++) { const range = foldedOrManualRanges[i]; if (range.startLineNumber >= range.endLineNumber || range.startLineNumber < 1 || range.endLineNumber > maxLineNumber) { continue; } const checksum = this._getLinesChecksum(range.startLineNumber + 1, range.endLineNumber); result.push({ startLineNumber: range.startLineNumber, endLineNumber: range.endLineNumber, isCollapsed: range.isCollapsed, source: range.source, checksum: checksum }); } return (result.length > 0) ? result : undefined; } /** * Apply persisted state, for persistence only */ public applyMemento(state: CollapseMemento) { if (!Array.isArray(state)) { return; } const rangesToRestore: FoldRange[] = []; const maxLineNumber = this._textModel.getLineCount(); for (const range of state) { if (range.startLineNumber >= range.endLineNumber || range.startLineNumber < 1 || range.endLineNumber > maxLineNumber) { continue; } const checksum = this._getLinesChecksum(range.startLineNumber + 1, range.endLineNumber); if (!range.checksum || checksum === range.checksum) { rangesToRestore.push({ startLineNumber: range.startLineNumber, endLineNumber: range.endLineNumber, type: undefined, isCollapsed: range.isCollapsed ?? true, source: range.source ?? FoldSource.provider }); } } const newRanges = FoldingRegions.sanitizeAndMerge(this._regions, rangesToRestore, maxLineNumber); this.updatePost(FoldingRegions.fromFoldRanges(newRanges)); } private _getLinesChecksum(lineNumber1: number, lineNumber2: number): number { const h = hash(this._textModel.getLineContent(lineNumber1) + this._textModel.getLineContent(lineNumber2)); return h % 1000000; // 6 digits is plenty } public dispose() { this._decorationProvider.removeDecorations(this._editorDecorationIds); } getAllRegionsAtLine(lineNumber: number, filter?: (r: FoldingRegion, level: number) => boolean): FoldingRegion[] { const result: FoldingRegion[] = []; if (this._regions) { let index = this._regions.findRange(lineNumber); let level = 1; while (index >= 0) { const current = this._regions.toRegion(index); if (!filter || filter(current, level)) { result.push(current); } level++; index = current.parentIndex; } } return result; } getRegionAtLine(lineNumber: number): FoldingRegion | null { if (this._regions) { const index = this._regions.findRange(lineNumber); if (index >= 0) { return this._regions.toRegion(index); } } return null; } getRegionsInside(region: FoldingRegion | null, filter?: RegionFilter | RegionFilterWithLevel): FoldingRegion[] { const result: FoldingRegion[] = []; const index = region ? region.regionIndex + 1 : 0; const endLineNumber = region ? region.endLineNumber : Number.MAX_VALUE; if (filter && filter.length === 2) { const levelStack: FoldingRegion[] = []; for (let i = index, len = this._regions.length; i < len; i++) { const current = this._regions.toRegion(i); if (this._regions.getStartLineNumber(i) < endLineNumber) { while (levelStack.length > 0 && !current.containedBy(levelStack[levelStack.length - 1])) { levelStack.pop(); } levelStack.push(current); if (filter(current, levelStack.length)) { result.push(current); } } else { break; } } } else { for (let i = index, len = this._regions.length; i < len; i++) { const current = this._regions.toRegion(i); if (this._regions.getStartLineNumber(i) < endLineNumber) { if (!filter || (filter as RegionFilter)(current)) { result.push(current); } } else { break; } } } return result; } } type RegionFilter = (r: FoldingRegion) => boolean; type RegionFilterWithLevel = (r: FoldingRegion, level: number) => boolean; /** * Collapse or expand the regions at the given locations * @param levels The number of levels. Use 1 to only impact the regions at the location, use Number.MAX_VALUE for all levels. * @param lineNumbers the location of the regions to collapse or expand, or if not set, all regions in the model. */ export function toggleCollapseState(foldingModel: FoldingModel, levels: number, lineNumbers: number[]) { const toToggle: FoldingRegion[] = []; for (const lineNumber of lineNumbers) { const region = foldingModel.getRegionAtLine(lineNumber); if (region) { const doCollapse = !region.isCollapsed; toToggle.push(region); if (levels > 1) { const regionsInside = foldingModel.getRegionsInside(region, (r, level: number) => r.isCollapsed !== doCollapse && level < levels); toToggle.push(...regionsInside); } } } foldingModel.toggleCollapseState(toToggle); } /** * Collapse or expand the regions at the given locations including all children. * @param doCollapse Whether to collapse or expand * @param levels The number of levels. Use 1 to only impact the regions at the location, use Number.MAX_VALUE for all levels. * @param lineNumbers the location of the regions to collapse or expand, or if not set, all regions in the model. */ export function setCollapseStateLevelsDown(foldingModel: FoldingModel, doCollapse: boolean, levels = Number.MAX_VALUE, lineNumbers?: number[]): void { const toToggle: FoldingRegion[] = []; if (lineNumbers && lineNumbers.length > 0) { for (const lineNumber of lineNumbers) { const region = foldingModel.getRegionAtLine(lineNumber); if (region) { if (region.isCollapsed !== doCollapse) { toToggle.push(region); } if (levels > 1) { const regionsInside = foldingModel.getRegionsInside(region, (r, level: number) => r.isCollapsed !== doCollapse && level < levels); toToggle.push(...regionsInside); } } } } else { const regionsInside = foldingModel.getRegionsInside(null, (r, level: number) => r.isCollapsed !== doCollapse && level < levels); toToggle.push(...regionsInside); } foldingModel.toggleCollapseState(toToggle); } /** * Collapse or expand the regions at the given locations including all parents. * @param doCollapse Whether to collapse or expand * @param levels The number of levels. Use 1 to only impact the regions at the location, use Number.MAX_VALUE for all levels. * @param lineNumbers the location of the regions to collapse or expand. */ export function setCollapseStateLevelsUp(foldingModel: FoldingModel, doCollapse: boolean, levels: number, lineNumbers: number[]): void { const toToggle: FoldingRegion[] = []; for (const lineNumber of lineNumbers) { const regions = foldingModel.getAllRegionsAtLine(lineNumber, (region, level) => region.isCollapsed !== doCollapse && level <= levels); toToggle.push(...regions); } foldingModel.toggleCollapseState(toToggle); } /** * Collapse or expand a region at the given locations. If the inner most region is already collapsed/expanded, uses the first parent instead. * @param doCollapse Whether to collapse or expand * @param lineNumbers the location of the regions to collapse or expand. */ export function setCollapseStateUp(foldingModel: FoldingModel, doCollapse: boolean, lineNumbers: number[]): void { const toToggle: FoldingRegion[] = []; for (const lineNumber of lineNumbers) { const regions = foldingModel.getAllRegionsAtLine(lineNumber, (region,) => region.isCollapsed !== doCollapse); if (regions.length > 0) { toToggle.push(regions[0]); } } foldingModel.toggleCollapseState(toToggle); } /** * Folds or unfolds all regions that have a given level, except if they contain one of the blocked lines. * @param foldLevel level. Level == 1 is the top level * @param doCollapse Whether to collapse or expand */ export function setCollapseStateAtLevel(foldingModel: FoldingModel, foldLevel: number, doCollapse: boolean, blockedLineNumbers: number[]): void { const filter = (region: FoldingRegion, level: number) => level === foldLevel && region.isCollapsed !== doCollapse && !blockedLineNumbers.some(line => region.containsLine(line)); const toToggle = foldingModel.getRegionsInside(null, filter); foldingModel.toggleCollapseState(toToggle); } /** * Folds or unfolds all regions, except if they contain or are contained by a region of one of the blocked lines. * @param doCollapse Whether to collapse or expand * @param blockedLineNumbers the location of regions to not collapse or expand */ export function setCollapseStateForRest(foldingModel: FoldingModel, doCollapse: boolean, blockedLineNumbers: number[]): void { const filteredRegions: FoldingRegion[] = []; for (const lineNumber of blockedLineNumbers) { const regions = foldingModel.getAllRegionsAtLine(lineNumber, undefined); if (regions.length > 0) { filteredRegions.push(regions[0]); } } const filter = (region: FoldingRegion) => filteredRegions.every((filteredRegion) => !filteredRegion.containedBy(region) && !region.containedBy(filteredRegion)) && region.isCollapsed !== doCollapse; const toToggle = foldingModel.getRegionsInside(null, filter); foldingModel.toggleCollapseState(toToggle); } /** * Folds all regions for which the lines start with a given regex * @param foldingModel the folding model */ export function setCollapseStateForMatchingLines(foldingModel: FoldingModel, regExp: RegExp, doCollapse: boolean): void { const editorModel = foldingModel.textModel; const regions = foldingModel.regions; const toToggle: FoldingRegion[] = []; for (let i = regions.length - 1; i >= 0; i--) { if (doCollapse !== regions.isCollapsed(i)) { const startLineNumber = regions.getStartLineNumber(i); if (regExp.test(editorModel.getLineContent(startLineNumber))) { toToggle.push(regions.toRegion(i)); } } } foldingModel.toggleCollapseState(toToggle); } /** * Folds all regions of the given type * @param foldingModel the folding model */ export function setCollapseStateForType(foldingModel: FoldingModel, type: string, doCollapse: boolean): void { const regions = foldingModel.regions; const toToggle: FoldingRegion[] = []; for (let i = regions.length - 1; i >= 0; i--) { if (doCollapse !== regions.isCollapsed(i) && type === regions.getType(i)) { toToggle.push(regions.toRegion(i)); } } foldingModel.toggleCollapseState(toToggle); } /** * Get line to go to for parent fold of current line * @param lineNumber the current line number * @param foldingModel the folding model * * @return Parent fold start line */ export function getParentFoldLine(lineNumber: number, foldingModel: FoldingModel): number | null { let startLineNumber: number | null = null; const foldingRegion = foldingModel.getRegionAtLine(lineNumber); if (foldingRegion !== null) { startLineNumber = foldingRegion.startLineNumber; // If current line is not the start of the current fold, go to top line of current fold. If not, go to parent fold if (lineNumber === startLineNumber) { const parentFoldingIdx = foldingRegion.parentIndex; if (parentFoldingIdx !== -1) { startLineNumber = foldingModel.regions.getStartLineNumber(parentFoldingIdx); } else { startLineNumber = null; } } } return startLineNumber; } /** * Get line to go to for previous fold at the same level of current line * @param lineNumber the current line number * @param foldingModel the folding model * * @return Previous fold start line */ export function getPreviousFoldLine(lineNumber: number, foldingModel: FoldingModel): number | null { let foldingRegion = foldingModel.getRegionAtLine(lineNumber); // If on the folding range start line, go to previous sibling. if (foldingRegion !== null && foldingRegion.startLineNumber === lineNumber) { // If current line is not the start of the current fold, go to top line of current fold. If not, go to previous fold. if (lineNumber !== foldingRegion.startLineNumber) { return foldingRegion.startLineNumber; } else { // Find min line number to stay within parent. const expectedParentIndex = foldingRegion.parentIndex; let minLineNumber = 0; if (expectedParentIndex !== -1) { minLineNumber = foldingModel.regions.getStartLineNumber(foldingRegion.parentIndex); } // Find fold at same level. while (foldingRegion !== null) { if (foldingRegion.regionIndex > 0) { foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex - 1); // Keep at same level. if (foldingRegion.startLineNumber <= minLineNumber) { return null; } else if (foldingRegion.parentIndex === expectedParentIndex) { return foldingRegion.startLineNumber; } } else { return null; } } } } else { // Go to last fold that's before the current line. if (foldingModel.regions.length > 0) { foldingRegion = foldingModel.regions.toRegion(foldingModel.regions.length - 1); while (foldingRegion !== null) { // Found fold before current line. if (foldingRegion.startLineNumber < lineNumber) { return foldingRegion.startLineNumber; } if (foldingRegion.regionIndex > 0) { foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex - 1); } else { foldingRegion = null; } } } } return null; } /** * Get line to go to next fold at the same level of current line * @param lineNumber the current line number * @param foldingModel the folding model * * @return Next fold start line */ export function getNextFoldLine(lineNumber: number, foldingModel: FoldingModel): number | null { let foldingRegion = foldingModel.getRegionAtLine(lineNumber); // If on the folding range start line, go to next sibling. if (foldingRegion !== null && foldingRegion.startLineNumber === lineNumber) { // Find max line number to stay within parent. const expectedParentIndex = foldingRegion.parentIndex; let maxLineNumber = 0; if (expectedParentIndex !== -1) { maxLineNumber = foldingModel.regions.getEndLineNumber(foldingRegion.parentIndex); } else if (foldingModel.regions.length === 0) { return null; } else { maxLineNumber = foldingModel.regions.getEndLineNumber(foldingModel.regions.length - 1); } // Find fold at same level. while (foldingRegion !== null) { if (foldingRegion.regionIndex < foldingModel.regions.length) { foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex + 1); // Keep at same level. if (foldingRegion.startLineNumber >= maxLineNumber) { return null; } else if (foldingRegion.parentIndex === expectedParentIndex) { return foldingRegion.startLineNumber; } } else { return null; } } } else { // Go to first fold that's after the current line. if (foldingModel.regions.length > 0) { foldingRegion = foldingModel.regions.toRegion(0); while (foldingRegion !== null) { // Found fold after current line. if (foldingRegion.startLineNumber > lineNumber) { return foldingRegion.startLineNumber; } if (foldingRegion.regionIndex < foldingModel.regions.length) { foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex + 1); } else { foldingRegion = null; } } } } return null; }
src/vs/editor/contrib/folding/browser/foldingModel.ts
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.00017535389633849263, 0.0001695470418781042, 0.00016292365035042167, 0.00016934776795096695, 0.00000243173485614534 ]
{ "id": 3, "code_window": [ " - ${{ if eq(parameters.VSCODE_BUILD_MACOS_ARM64, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_darwin_arm64_cli\n" ], "labels": [ "keep", "keep", "keep", "add" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}" ], "file_path": "build/azure-pipelines/darwin/cli-build-darwin.yml", "type": "add", "edit_start_line_idx": 77 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-workbench > .notifications-center { position: absolute; z-index: 1000; right: 8px; bottom: 31px; display: none; overflow: hidden; border-radius: 4px; } .monaco-workbench.nostatusbar > .notifications-center { bottom: 8px; } .monaco-workbench > .notifications-center.visible { display: block; } /* Header */ .monaco-workbench > .notifications-center > .notifications-center-header { display: flex; align-items: center; padding-left: 8px; padding-right: 5px; height: 35px; } .monaco-workbench > .notifications-center > .notifications-center-header > .notifications-center-header-title { text-transform: uppercase; font-size: 11px; } .monaco-workbench > .notifications-center > .notifications-center-header > .notifications-center-header-toolbar { flex: 1; } .monaco-workbench > .notifications-center > .notifications-center-header > .notifications-center-header-toolbar .actions-container { justify-content: flex-end; } .monaco-workbench > .notifications-center .notifications-list-container .monaco-list-row[data-last-element="false"] > .notification-list-item { border-bottom: 1px solid var(--vscode-notifications-border); } .monaco-workbench > .notifications-center .notifications-list-container, .monaco-workbench > .notifications-center .notifications-list-container .monaco-scrollable-element, .monaco-workbench > .notifications-center .notifications-list-container .notification-list-item { border-radius: 0; } /* Icons */ .monaco-workbench > .notifications-center .codicon.codicon-error { color: var(--vscode-notificationsErrorIcon-foreground) !important; } .monaco-workbench > .notifications-center .codicon.codicon-warning { color: var(--vscode-notificationsWarningIcon-foreground) !important; } .monaco-workbench > .notifications-center .codicon.codicon-info { color: var(--vscode-notificationsInfoIcon-foreground) !important; }
src/vs/workbench/browser/parts/notifications/media/notificationsCenter.css
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.000174016720848158, 0.00016877414600457996, 0.00016543761012144387, 0.00016864696226548404, 0.000002430190761515405 ]
{ "id": 4, "code_window": [ " - ${{ if eq(parameters.VSCODE_BUILD_LINUX_ARMHF, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: vscode_cli_linux_armhf_cli\n", "\n", " - ${{ if eq(parameters.VSCODE_BUILD_LINUX, true) }}:\n", " - template: ../cli/cli-publish.yml\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}\n" ], "file_path": "build/azure-pipelines/linux/cli-build-linux.yml", "type": "add", "edit_start_line_idx": 131 }
parameters: - name: VSCODE_QUALITY type: string - name: VSCODE_BUILD_MACOS type: boolean default: false - name: VSCODE_BUILD_MACOS_ARM64 type: boolean default: false - name: VSCODE_CHECK_ONLY type: boolean default: false steps: - task: NodeTool@0 inputs: versionSource: fromFile versionFilePath: .nvmrc nodejsMirror: https://github.com/joaomoreno/node-mirror/releases/download - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - template: ../cli/cli-apply-patches.yml - task: Npm@1 displayName: Download openssl prebuilt inputs: command: custom customCommand: pack @vscode-internal/[email protected] customRegistry: useFeed customFeed: "Monaco/openssl-prebuilt" workingDir: $(Build.ArtifactStagingDirectory) - script: | set -e mkdir $(Build.ArtifactStagingDirectory)/openssl tar -xvzf $(Build.ArtifactStagingDirectory)/vscode-internal-openssl-prebuilt-0.0.11.tgz --strip-components=1 --directory=$(Build.ArtifactStagingDirectory)/openssl displayName: Extract openssl prebuilt - template: ../cli/install-rust-posix.yml parameters: targets: - ${{ if eq(parameters.VSCODE_BUILD_MACOS, true) }}: - x86_64-apple-darwin - ${{ if eq(parameters.VSCODE_BUILD_MACOS_ARM64, true) }}: - aarch64-apple-darwin - ${{ if eq(parameters.VSCODE_BUILD_MACOS, true) }}: - template: ../cli/cli-compile.yml parameters: VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_CLI_TARGET: x86_64-apple-darwin VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_darwin_x64_cli VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }} VSCODE_CLI_ENV: OPENSSL_LIB_DIR: $(Build.ArtifactStagingDirectory)/openssl/x64-osx/lib OPENSSL_INCLUDE_DIR: $(Build.ArtifactStagingDirectory)/openssl/x64-osx/include - ${{ if eq(parameters.VSCODE_BUILD_MACOS_ARM64, true) }}: - template: ../cli/cli-compile.yml parameters: VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_CLI_TARGET: aarch64-apple-darwin VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_darwin_arm64_cli VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }} VSCODE_CLI_ENV: OPENSSL_LIB_DIR: $(Build.ArtifactStagingDirectory)/openssl/arm64-osx/lib OPENSSL_INCLUDE_DIR: $(Build.ArtifactStagingDirectory)/openssl/arm64-osx/include - ${{ if eq(parameters.VSCODE_BUILD_MACOS, true) }}: - template: ../cli/cli-publish.yml parameters: VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_darwin_x64_cli - ${{ if eq(parameters.VSCODE_BUILD_MACOS_ARM64, true) }}: - template: ../cli/cli-publish.yml parameters: VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_darwin_arm64_cli
build/azure-pipelines/darwin/cli-build-darwin.yml
1
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.8815845847129822, 0.13556832075119019, 0.00017205991025548428, 0.006920455489307642, 0.2862429916858673 ]
{ "id": 4, "code_window": [ " - ${{ if eq(parameters.VSCODE_BUILD_LINUX_ARMHF, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: vscode_cli_linux_armhf_cli\n", "\n", " - ${{ if eq(parameters.VSCODE_BUILD_LINUX, true) }}:\n", " - template: ../cli/cli-publish.yml\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}\n" ], "file_path": "build/azure-pipelines/linux/cli-build-linux.yml", "type": "add", "edit_start_line_idx": 131 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { shuffle } from 'vs/base/common/arrays'; import { CharCode } from 'vs/base/common/charCode'; import { compare, compareIgnoreCase, compareSubstring, compareSubstringIgnoreCase } from 'vs/base/common/strings'; import { URI } from 'vs/base/common/uri'; export interface IKeyIterator<K> { reset(key: K): this; next(): this; hasNext(): boolean; cmp(a: string): number; value(): string; } export class StringIterator implements IKeyIterator<string> { private _value: string = ''; private _pos: number = 0; reset(key: string): this { this._value = key; this._pos = 0; return this; } next(): this { this._pos += 1; return this; } hasNext(): boolean { return this._pos < this._value.length - 1; } cmp(a: string): number { const aCode = a.charCodeAt(0); const thisCode = this._value.charCodeAt(this._pos); return aCode - thisCode; } value(): string { return this._value[this._pos]; } } export class ConfigKeysIterator implements IKeyIterator<string> { private _value!: string; private _from!: number; private _to!: number; constructor( private readonly _caseSensitive: boolean = true ) { } reset(key: string): this { this._value = key; this._from = 0; this._to = 0; return this.next(); } hasNext(): boolean { return this._to < this._value.length; } next(): this { // this._data = key.split(/[\\/]/).filter(s => !!s); this._from = this._to; let justSeps = true; for (; this._to < this._value.length; this._to++) { const ch = this._value.charCodeAt(this._to); if (ch === CharCode.Period) { if (justSeps) { this._from++; } else { break; } } else { justSeps = false; } } return this; } cmp(a: string): number { return this._caseSensitive ? compareSubstring(a, this._value, 0, a.length, this._from, this._to) : compareSubstringIgnoreCase(a, this._value, 0, a.length, this._from, this._to); } value(): string { return this._value.substring(this._from, this._to); } } export class PathIterator implements IKeyIterator<string> { private _value!: string; private _valueLen!: number; private _from!: number; private _to!: number; constructor( private readonly _splitOnBackslash: boolean = true, private readonly _caseSensitive: boolean = true ) { } reset(key: string): this { this._from = 0; this._to = 0; this._value = key; this._valueLen = key.length; for (let pos = key.length - 1; pos >= 0; pos--, this._valueLen--) { const ch = this._value.charCodeAt(pos); if (!(ch === CharCode.Slash || this._splitOnBackslash && ch === CharCode.Backslash)) { break; } } return this.next(); } hasNext(): boolean { return this._to < this._valueLen; } next(): this { // this._data = key.split(/[\\/]/).filter(s => !!s); this._from = this._to; let justSeps = true; for (; this._to < this._valueLen; this._to++) { const ch = this._value.charCodeAt(this._to); if (ch === CharCode.Slash || this._splitOnBackslash && ch === CharCode.Backslash) { if (justSeps) { this._from++; } else { break; } } else { justSeps = false; } } return this; } cmp(a: string): number { return this._caseSensitive ? compareSubstring(a, this._value, 0, a.length, this._from, this._to) : compareSubstringIgnoreCase(a, this._value, 0, a.length, this._from, this._to); } value(): string { return this._value.substring(this._from, this._to); } } const enum UriIteratorState { Scheme = 1, Authority = 2, Path = 3, Query = 4, Fragment = 5 } export class UriIterator implements IKeyIterator<URI> { private _pathIterator!: PathIterator; private _value!: URI; private _states: UriIteratorState[] = []; private _stateIdx: number = 0; constructor( private readonly _ignorePathCasing: (uri: URI) => boolean, private readonly _ignoreQueryAndFragment: (uri: URI) => boolean) { } reset(key: URI): this { this._value = key; this._states = []; if (this._value.scheme) { this._states.push(UriIteratorState.Scheme); } if (this._value.authority) { this._states.push(UriIteratorState.Authority); } if (this._value.path) { this._pathIterator = new PathIterator(false, !this._ignorePathCasing(key)); this._pathIterator.reset(key.path); if (this._pathIterator.value()) { this._states.push(UriIteratorState.Path); } } if (!this._ignoreQueryAndFragment(key)) { if (this._value.query) { this._states.push(UriIteratorState.Query); } if (this._value.fragment) { this._states.push(UriIteratorState.Fragment); } } this._stateIdx = 0; return this; } next(): this { if (this._states[this._stateIdx] === UriIteratorState.Path && this._pathIterator.hasNext()) { this._pathIterator.next(); } else { this._stateIdx += 1; } return this; } hasNext(): boolean { return (this._states[this._stateIdx] === UriIteratorState.Path && this._pathIterator.hasNext()) || this._stateIdx < this._states.length - 1; } cmp(a: string): number { if (this._states[this._stateIdx] === UriIteratorState.Scheme) { return compareIgnoreCase(a, this._value.scheme); } else if (this._states[this._stateIdx] === UriIteratorState.Authority) { return compareIgnoreCase(a, this._value.authority); } else if (this._states[this._stateIdx] === UriIteratorState.Path) { return this._pathIterator.cmp(a); } else if (this._states[this._stateIdx] === UriIteratorState.Query) { return compare(a, this._value.query); } else if (this._states[this._stateIdx] === UriIteratorState.Fragment) { return compare(a, this._value.fragment); } throw new Error(); } value(): string { if (this._states[this._stateIdx] === UriIteratorState.Scheme) { return this._value.scheme; } else if (this._states[this._stateIdx] === UriIteratorState.Authority) { return this._value.authority; } else if (this._states[this._stateIdx] === UriIteratorState.Path) { return this._pathIterator.value(); } else if (this._states[this._stateIdx] === UriIteratorState.Query) { return this._value.query; } else if (this._states[this._stateIdx] === UriIteratorState.Fragment) { return this._value.fragment; } throw new Error(); } } class TernarySearchTreeNode<K, V> { height: number = 1; segment!: string; value: V | undefined; key: K | undefined; left: TernarySearchTreeNode<K, V> | undefined; mid: TernarySearchTreeNode<K, V> | undefined; right: TernarySearchTreeNode<K, V> | undefined; isEmpty(): boolean { return !this.left && !this.mid && !this.right && !this.value; } rotateLeft() { const tmp = this.right!; this.right = tmp.left; tmp.left = this; this.updateHeight(); tmp.updateHeight(); return tmp; } rotateRight() { const tmp = this.left!; this.left = tmp.right; tmp.right = this; this.updateHeight(); tmp.updateHeight(); return tmp; } updateHeight() { this.height = 1 + Math.max(this.heightLeft, this.heightRight); } balanceFactor() { return this.heightRight - this.heightLeft; } get heightLeft() { return this.left?.height ?? 0; } get heightRight() { return this.right?.height ?? 0; } } const enum Dir { Left = -1, Mid = 0, Right = 1 } export class TernarySearchTree<K, V> { static forUris<E>(ignorePathCasing: (key: URI) => boolean = () => false, ignoreQueryAndFragment: (key: URI) => boolean = () => false): TernarySearchTree<URI, E> { return new TernarySearchTree<URI, E>(new UriIterator(ignorePathCasing, ignoreQueryAndFragment)); } static forPaths<E>(ignorePathCasing = false): TernarySearchTree<string, E> { return new TernarySearchTree<string, E>(new PathIterator(undefined, !ignorePathCasing)); } static forStrings<E>(): TernarySearchTree<string, E> { return new TernarySearchTree<string, E>(new StringIterator()); } static forConfigKeys<E>(): TernarySearchTree<string, E> { return new TernarySearchTree<string, E>(new ConfigKeysIterator()); } private _iter: IKeyIterator<K>; private _root: TernarySearchTreeNode<K, V> | undefined; constructor(segments: IKeyIterator<K>) { this._iter = segments; } clear(): void { this._root = undefined; } /** * Fill the tree with the same value of the given keys */ fill(element: V, keys: readonly K[]): void; /** * Fill the tree with given [key,value]-tuples */ fill(values: readonly [K, V][]): void; fill(values: readonly [K, V][] | V, keys?: readonly K[]): void { if (keys) { const arr = keys.slice(0); shuffle(arr); for (const k of arr) { this.set(k, (<V>values)); } } else { const arr = (<[K, V][]>values).slice(0); shuffle(arr); for (const entry of arr) { this.set(entry[0], entry[1]); } } } set(key: K, element: V): V | undefined { const iter = this._iter.reset(key); let node: TernarySearchTreeNode<K, V>; if (!this._root) { this._root = new TernarySearchTreeNode<K, V>(); this._root.segment = iter.value(); } const stack: [Dir, TernarySearchTreeNode<K, V>][] = []; // find insert_node node = this._root; while (true) { const val = iter.cmp(node.segment); if (val > 0) { // left if (!node.left) { node.left = new TernarySearchTreeNode<K, V>(); node.left.segment = iter.value(); } stack.push([Dir.Left, node]); node = node.left; } else if (val < 0) { // right if (!node.right) { node.right = new TernarySearchTreeNode<K, V>(); node.right.segment = iter.value(); } stack.push([Dir.Right, node]); node = node.right; } else if (iter.hasNext()) { // mid iter.next(); if (!node.mid) { node.mid = new TernarySearchTreeNode<K, V>(); node.mid.segment = iter.value(); } stack.push([Dir.Mid, node]); node = node.mid; } else { break; } } // set value const oldElement = node.value; node.value = element; node.key = key; // balance for (let i = stack.length - 1; i >= 0; i--) { const node = stack[i][1]; node.updateHeight(); const bf = node.balanceFactor(); if (bf < -1 || bf > 1) { // needs rotate const d1 = stack[i][0]; const d2 = stack[i + 1][0]; if (d1 === Dir.Right && d2 === Dir.Right) { //right, right -> rotate left stack[i][1] = node.rotateLeft(); } else if (d1 === Dir.Left && d2 === Dir.Left) { // left, left -> rotate right stack[i][1] = node.rotateRight(); } else if (d1 === Dir.Right && d2 === Dir.Left) { // right, left -> double rotate right, left node.right = stack[i + 1][1] = stack[i + 1][1].rotateRight(); stack[i][1] = node.rotateLeft(); } else if (d1 === Dir.Left && d2 === Dir.Right) { // left, right -> double rotate left, right node.left = stack[i + 1][1] = stack[i + 1][1].rotateLeft(); stack[i][1] = node.rotateRight(); } else { throw new Error(); } // patch path to parent if (i > 0) { switch (stack[i - 1][0]) { case Dir.Left: stack[i - 1][1].left = stack[i][1]; break; case Dir.Right: stack[i - 1][1].right = stack[i][1]; break; case Dir.Mid: stack[i - 1][1].mid = stack[i][1]; break; } } else { this._root = stack[0][1]; } } } return oldElement; } get(key: K): V | undefined { return this._getNode(key)?.value; } private _getNode(key: K) { const iter = this._iter.reset(key); let node = this._root; while (node) { const val = iter.cmp(node.segment); if (val > 0) { // left node = node.left; } else if (val < 0) { // right node = node.right; } else if (iter.hasNext()) { // mid iter.next(); node = node.mid; } else { break; } } return node; } has(key: K): boolean { const node = this._getNode(key); return !(node?.value === undefined && node?.mid === undefined); } delete(key: K): void { return this._delete(key, false); } deleteSuperstr(key: K): void { return this._delete(key, true); } private _delete(key: K, superStr: boolean): void { const iter = this._iter.reset(key); const stack: [Dir, TernarySearchTreeNode<K, V>][] = []; let node = this._root; // find node while (node) { const val = iter.cmp(node.segment); if (val > 0) { // left stack.push([Dir.Left, node]); node = node.left; } else if (val < 0) { // right stack.push([Dir.Right, node]); node = node.right; } else if (iter.hasNext()) { // mid iter.next(); stack.push([Dir.Mid, node]); node = node.mid; } else { break; } } if (!node) { // node not found return; } if (superStr) { // removing children, reset height node.left = undefined; node.mid = undefined; node.right = undefined; node.height = 1; } else { // removing element node.key = undefined; node.value = undefined; } // BST node removal if (!node.mid && !node.value) { if (node.left && node.right) { // full node // replace deleted-node with the min-node of the right branch. // If there is no true min-node leave things as they are const min = this._min(node.right); if (min.key) { const { key, value, segment } = min; this._delete(min.key, false); node.key = key; node.value = value; node.segment = segment; } } else { // empty or half empty const newChild = node.left ?? node.right; if (stack.length > 0) { const [dir, parent] = stack[stack.length - 1]; switch (dir) { case Dir.Left: parent.left = newChild; break; case Dir.Mid: parent.mid = newChild; break; case Dir.Right: parent.right = newChild; break; } } else { this._root = newChild; } } } // AVL balance for (let i = stack.length - 1; i >= 0; i--) { const node = stack[i][1]; node.updateHeight(); const bf = node.balanceFactor(); if (bf > 1) { // right heavy if (node.right!.balanceFactor() >= 0) { // right, right -> rotate left stack[i][1] = node.rotateLeft(); } else { // right, left -> double rotate node.right = node.right!.rotateRight(); stack[i][1] = node.rotateLeft(); } } else if (bf < -1) { // left heavy if (node.left!.balanceFactor() <= 0) { // left, left -> rotate right stack[i][1] = node.rotateRight(); } else { // left, right -> double rotate node.left = node.left!.rotateLeft(); stack[i][1] = node.rotateRight(); } } // patch path to parent if (i > 0) { switch (stack[i - 1][0]) { case Dir.Left: stack[i - 1][1].left = stack[i][1]; break; case Dir.Right: stack[i - 1][1].right = stack[i][1]; break; case Dir.Mid: stack[i - 1][1].mid = stack[i][1]; break; } } else { this._root = stack[0][1]; } } } private _min(node: TernarySearchTreeNode<K, V>): TernarySearchTreeNode<K, V> { while (node.left) { node = node.left; } return node; } findSubstr(key: K): V | undefined { const iter = this._iter.reset(key); let node = this._root; let candidate: V | undefined = undefined; while (node) { const val = iter.cmp(node.segment); if (val > 0) { // left node = node.left; } else if (val < 0) { // right node = node.right; } else if (iter.hasNext()) { // mid iter.next(); candidate = node.value || candidate; node = node.mid; } else { break; } } return node && node.value || candidate; } findSuperstr(key: K): IterableIterator<[K, V]> | undefined { return this._findSuperstrOrElement(key, false); } private _findSuperstrOrElement(key: K, allowValue: true): IterableIterator<[K, V]> | V | undefined; private _findSuperstrOrElement(key: K, allowValue: false): IterableIterator<[K, V]> | undefined; private _findSuperstrOrElement(key: K, allowValue: boolean): IterableIterator<[K, V]> | V | undefined { const iter = this._iter.reset(key); let node = this._root; while (node) { const val = iter.cmp(node.segment); if (val > 0) { // left node = node.left; } else if (val < 0) { // right node = node.right; } else if (iter.hasNext()) { // mid iter.next(); node = node.mid; } else { // collect if (!node.mid) { if (allowValue) { return node.value; } else { return undefined; } } else { return this._entries(node.mid); } } } return undefined; } hasElementOrSubtree(key: K): boolean { return this._findSuperstrOrElement(key, true) !== undefined; } forEach(callback: (value: V, index: K) => any): void { for (const [key, value] of this) { callback(value, key); } } *[Symbol.iterator](): IterableIterator<[K, V]> { yield* this._entries(this._root); } private _entries(node: TernarySearchTreeNode<K, V> | undefined): IterableIterator<[K, V]> { const result: [K, V][] = []; this._dfsEntries(node, result); return result[Symbol.iterator](); } private _dfsEntries(node: TernarySearchTreeNode<K, V> | undefined, bucket: [K, V][]) { // DFS if (!node) { return; } if (node.left) { this._dfsEntries(node.left, bucket); } if (node.value) { bucket.push([node.key!, node.value]); } if (node.mid) { this._dfsEntries(node.mid, bucket); } if (node.right) { this._dfsEntries(node.right, bucket); } } // for debug/testing _isBalanced(): boolean { const nodeIsBalanced = (node: TernarySearchTreeNode<any, any> | undefined): boolean => { if (!node) { return true; } const bf = node.balanceFactor(); if (bf < -1 || bf > 1) { return false; } return nodeIsBalanced(node.left) && nodeIsBalanced(node.right); }; return nodeIsBalanced(this._root); } }
src/vs/base/common/ternarySearchTree.ts
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.0001737148268148303, 0.00016965273243840784, 0.00016214055358432233, 0.00016961699293460697, 0.0000024739599666645518 ]
{ "id": 4, "code_window": [ " - ${{ if eq(parameters.VSCODE_BUILD_LINUX_ARMHF, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: vscode_cli_linux_armhf_cli\n", "\n", " - ${{ if eq(parameters.VSCODE_BUILD_LINUX, true) }}:\n", " - template: ../cli/cli-publish.yml\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}\n" ], "file_path": "build/azure-pipelines/linux/cli-build-linux.yml", "type": "add", "edit_start_line_idx": 131 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { NativeTitleService } from 'vs/workbench/electron-sandbox/parts/titlebar/titlebarPart'; import { ITitleService } from 'vs/workbench/services/title/browser/titleService'; registerSingleton(ITitleService, NativeTitleService, InstantiationType.Eager);
src/vs/workbench/services/title/electron-sandbox/titleService.ts
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.0004094734031241387, 0.00029164855368435383, 0.00017382368969265372, 0.00029164855368435383, 0.0001178248567157425 ]
{ "id": 4, "code_window": [ " - ${{ if eq(parameters.VSCODE_BUILD_LINUX_ARMHF, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: vscode_cli_linux_armhf_cli\n", "\n", " - ${{ if eq(parameters.VSCODE_BUILD_LINUX, true) }}:\n", " - template: ../cli/cli-publish.yml\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}\n" ], "file_path": "build/azure-pipelines/linux/cli-build-linux.yml", "type": "add", "edit_start_line_idx": 131 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import type { PerformanceMark } from 'vs/base/common/performance'; import type { UriComponents, URI } from 'vs/base/common/uri'; import type { IWebSocketFactory } from 'vs/platform/remote/browser/browserSocketFactory'; import type { IURLCallbackProvider } from 'vs/workbench/services/url/browser/urlService'; import type { LogLevel } from 'vs/platform/log/common/log'; import type { IUpdateProvider } from 'vs/workbench/services/update/browser/updateService'; import type { Event } from 'vs/base/common/event'; import type { IProductConfiguration } from 'vs/base/common/product'; import type { ISecretStorageProvider } from 'vs/platform/secrets/common/secrets'; import type { TunnelProviderFeatures } from 'vs/platform/tunnel/common/tunnel'; import type { IProgress, IProgressCompositeOptions, IProgressDialogOptions, IProgressNotificationOptions, IProgressOptions, IProgressStep, IProgressWindowOptions } from 'vs/platform/progress/common/progress'; import type { ITextEditorOptions } from 'vs/platform/editor/common/editor'; import type { IFolderToOpen, IWorkspaceToOpen } from 'vs/platform/window/common/window'; import type { EditorGroupLayout } from 'vs/workbench/services/editor/common/editorGroupsService'; import type { IEmbedderTerminalOptions } from 'vs/workbench/services/terminal/common/embedderTerminalService'; import type { IAuthenticationProvider } from 'vs/workbench/services/authentication/common/authentication'; /** * The `IWorkbench` interface is the API facade for web embedders * to call into the workbench. * * Note: Changes to this interface need to be announced and adopted. */ export interface IWorkbench { commands: { /** * Allows to execute any command if known with the provided arguments. * * @param command Identifier of the command to execute. * @param rest Parameters passed to the command function. * @return A promise that resolves to the returned value of the given command. */ executeCommand(command: string, ...args: any[]): Promise<unknown>; }; logger: { /** * Logging for embedder. * * @param level The log level of the message to be printed. * @param message Message to be printed. */ log(level: LogLevel, message: string): void; }; env: { /** * @returns the scheme to use for opening the associated desktop * experience via protocol handler. */ getUriScheme(): Promise<string>; /** * Retrieve performance marks that have been collected during startup. This function * returns tuples of source and marks. A source is a dedicated context, like * the renderer or an extension host. * * *Note* that marks can be collected on different machines and in different processes * and that therefore "different clocks" are used. So, comparing `startTime`-properties * across contexts should be taken with a grain of salt. * * @returns A promise that resolves to tuples of source and marks. */ retrievePerformanceMarks(): Promise<[string, readonly PerformanceMark[]][]>; /** * Allows to open a `URI` with the standard opener service of the * workbench. */ openUri(target: URI): Promise<boolean>; }; window: { /** * Show progress in the editor. Progress is shown while running the given callback * and while the promise it returned isn't resolved nor rejected. * * @param task A callback returning a promise. * @return A promise that resolves to the returned value of the given task result. */ withProgress<R>( options: IProgressOptions | IProgressDialogOptions | IProgressNotificationOptions | IProgressWindowOptions | IProgressCompositeOptions, task: (progress: IProgress<IProgressStep>) => Promise<R> ): Promise<R>; /** * Creates a terminal with limited capabilities that is intended for * writing output from the embedder before the workbench has finished * loading. When an embedder terminal is created it will automatically * show to the user. * * @param options The definition of the terminal, this is similar to * `ExtensionTerminalOptions` in the extension API. */ createTerminal(options: IEmbedderTerminalOptions): Promise<void>; }; workspace: { /** * Forwards a port. If the current embedder implements a tunnelFactory then that will be used to make the tunnel. * By default, openTunnel only support localhost; however, a tunnelFactory can be used to support other ips. * * @throws When run in an environment without a remote. * * @param tunnelOptions The `localPort` is a suggestion only. If that port is not available another will be chosen. */ openTunnel(tunnelOptions: ITunnelOptions): Promise<ITunnel>; }; /** * Triggers shutdown of the workbench programmatically. After this method is * called, the workbench is not usable anymore and the page needs to reload * or closed. * * This will also remove any `beforeUnload` handlers that would bring up a * confirmation dialog. * * The returned promise should be awaited on to ensure any data to persist * has been persisted. */ shutdown: () => Promise<void>; } export interface IWorkbenchConstructionOptions { //#region Connection related configuration /** * The remote authority is the IP:PORT from where the workbench is served * from. It is for example being used for the websocket connections as address. */ readonly remoteAuthority?: string; /** * The connection token to send to the server. */ readonly connectionToken?: string | Promise<string>; /** * An endpoint to serve iframe content ("webview") from. This is required * to provide full security isolation from the workbench host. */ readonly webviewEndpoint?: string; /** * A factory for web sockets. */ readonly webSocketFactory?: IWebSocketFactory; /** * A provider for resource URIs. * * *Note*: This will only be invoked after the `connectionToken` is resolved. */ readonly resourceUriProvider?: IResourceUriProvider; /** * Resolves an external uri before it is opened. */ readonly resolveExternalUri?: IExternalUriResolver; /** * A provider for supplying tunneling functionality, * such as creating tunnels and showing candidate ports to forward. */ readonly tunnelProvider?: ITunnelProvider; /** * Endpoints to be used for proxying authentication code exchange calls in the browser. */ readonly codeExchangeProxyEndpoints?: { [providerId: string]: string }; /** * The identifier of an edit session associated with the current workspace. */ readonly editSessionId?: string; /** * Resource delegation handler that allows for loading of resources when * using remote resolvers. * * This is exclusive with {@link resourceUriProvider}. `resourceUriProvider` * should be used if a {@link webSocketFactory} is used, and will be preferred. */ readonly remoteResourceProvider?: IRemoteResourceProvider; //#endregion //#region Workbench configuration /** * A handler for opening workspaces and providing the initial workspace. */ readonly workspaceProvider?: IWorkspaceProvider; /** * Settings sync options */ readonly settingsSyncOptions?: ISettingsSyncOptions; /** * The secret storage provider to store and retrieve secrets. */ readonly secretStorageProvider?: ISecretStorageProvider; /** * Additional builtin extensions those cannot be uninstalled but only be disabled. * It can be one of the following: * - an extension in the Marketplace * - location of the extension where it is hosted. */ readonly additionalBuiltinExtensions?: readonly (MarketplaceExtension | UriComponents)[]; /** * List of extensions to be enabled if they are installed. * Note: This will not install extensions if not installed. */ readonly enabledExtensions?: readonly ExtensionId[]; /** * Additional domains allowed to open from the workbench without the * link protection popup. */ readonly additionalTrustedDomains?: string[]; /** * Enable workspace trust feature for the current window */ readonly enableWorkspaceTrust?: boolean; /** * Urls that will be opened externally that are allowed access * to the opener window. This is primarily used to allow * `window.close()` to be called from the newly opened window. */ readonly openerAllowedExternalUrlPrefixes?: string[]; /** * Support for URL callbacks. */ readonly urlCallbackProvider?: IURLCallbackProvider; /** * Support adding additional properties to telemetry. */ readonly resolveCommonTelemetryProperties?: ICommonTelemetryPropertiesResolver; /** * A set of optional commands that should be registered with the commands * registry. * * Note: commands can be called from extensions if the identifier is known! */ readonly commands?: readonly ICommand[]; /** * Optional default layout to apply on first time the workspace is opened * (unless `force` is specified). This includes visibility of views and * editors including editor grid layout. */ readonly defaultLayout?: IDefaultLayout; /** * Optional configuration default overrides contributed to the workbench. */ readonly configurationDefaults?: Record<string, any>; //#endregion //#region Profile options /** * Profile to use for the workbench. */ readonly profile?: { readonly name: string; readonly contents?: string | UriComponents }; /** * URI of the profile to preview. */ readonly profileToPreview?: UriComponents; //#endregion //#region Update/Quality related /** * Support for update reporting */ readonly updateProvider?: IUpdateProvider; /** * Support for product quality switching */ readonly productQualityChangeHandler?: IProductQualityChangeHandler; //#endregion //#region Branding /** * Optional home indicator to appear above the hamburger menu in the activity bar. */ readonly homeIndicator?: IHomeIndicator; /** * Optional welcome banner to appear above the workbench. Can be dismissed by the * user. */ readonly welcomeBanner?: IWelcomeBanner; /** * Optional override for the product configuration properties. */ readonly productConfiguration?: Partial<IProductConfiguration>; /** * Optional override for properties of the window indicator in the status bar. */ readonly windowIndicator?: IWindowIndicator; /** * Specifies the default theme type (LIGHT, DARK..) and allows to provide initial colors that are shown * until the color theme that is specified in the settings (`editor.colorTheme`) is loaded and applied. * Once there are persisted colors from a last run these will be used. * * The idea is that the colors match the main colors from the theme defined in the `configurationDefaults`. */ readonly initialColorTheme?: IInitialColorTheme; /** * Welcome dialog. Can be dismissed by the user. */ readonly welcomeDialog?: IWelcomeDialog; //#endregion //#region IPC readonly messagePorts?: ReadonlyMap<ExtensionId, MessagePort>; //#endregion //#region Authentication Providers /** * Optional authentication provider contributions. These take precedence over * any authentication providers contributed via extensions. */ readonly authenticationProviders?: readonly IAuthenticationProvider[]; //#endregion //#region Development options readonly developmentOptions?: IDevelopmentOptions; //#endregion } /** * A workspace to open in the workbench can either be: * - a workspace file with 0-N folders (via `workspaceUri`) * - a single folder (via `folderUri`) * - empty (via `undefined`) */ export type IWorkspace = IWorkspaceToOpen | IFolderToOpen | undefined; export interface IWorkspaceProvider { /** * The initial workspace to open. */ readonly workspace: IWorkspace; /** * Arbitrary payload from the `IWorkspaceProvider.open` call. */ readonly payload?: object; /** * Return `true` if the provided [workspace](#IWorkspaceProvider.workspace) is trusted, `false` if not trusted, `undefined` if unknown. */ readonly trusted: boolean | undefined; /** * Asks to open a workspace in the current or a new window. * * @param workspace the workspace to open. * @param options optional options for the workspace to open. * - `reuse`: whether to open inside the current window or a new window * - `payload`: arbitrary payload that should be made available * to the opening window via the `IWorkspaceProvider.payload` property. * @param payload optional payload to send to the workspace to open. * * @returns true if successfully opened, false otherwise. */ open(workspace: IWorkspace, options?: { reuse?: boolean; payload?: object }): Promise<boolean>; } export interface IResourceUriProvider { (uri: URI): URI; } /** * The identifier of an extension in the format: `PUBLISHER.NAME`. For example: `vscode.csharp` */ export type ExtensionId = string; export type MarketplaceExtension = ExtensionId | { readonly id: ExtensionId; preRelease?: boolean; migrateStorageFrom?: ExtensionId }; export interface ICommonTelemetryPropertiesResolver { (): { [key: string]: any }; } export interface IExternalUriResolver { (uri: URI): Promise<URI>; } export interface IExternalURLOpener { /** * Overrides the behavior when an external URL is about to be opened. * Returning false means that the URL wasn't handled, and the default * handling behavior should be used: `window.open(href, '_blank', 'noopener');` * * @returns true if URL was handled, false otherwise. */ openExternal(href: string): boolean | Promise<boolean>; } export interface ITunnelProvider { /** * Support for creating tunnels. */ tunnelFactory?: ITunnelFactory; /** * Support for filtering candidate ports. */ showPortCandidate?: IShowPortCandidate; /** * The features that the tunnel provider supports. */ features?: TunnelProviderFeatures; } export interface ITunnelFactory { (tunnelOptions: ITunnelOptions, tunnelCreationOptions: TunnelCreationOptions): Promise<ITunnel> | undefined; } export interface ITunnelOptions { remoteAddress: { port: number; host: string }; /** * The desired local port. If this port can't be used, then another will be chosen. */ localAddressPort?: number; label?: string; privacy?: string; protocol?: string; } export interface TunnelCreationOptions { /** * True when the local operating system will require elevation to use the requested local port. */ elevationRequired?: boolean; } export interface ITunnel { remoteAddress: { port: number; host: string }; /** * The complete local address(ex. localhost:1234) */ localAddress: string; privacy?: string; /** * If protocol is not provided, it is assumed to be http, regardless of the localAddress */ protocol?: string; /** * Implementers of Tunnel should fire onDidDispose when dispose is called. */ onDidDispose: Event<void>; dispose(): Promise<void> | void; } export interface IShowPortCandidate { (host: string, port: number, detail: string): Promise<boolean>; } export enum Menu { CommandPalette, StatusBarWindowIndicatorMenu, } export interface ICommand { /** * An identifier for the command. Commands can be executed from extensions * using the `vscode.commands.executeCommand` API using that command ID. */ id: string; /** * The optional label of the command. If provided, the command will appear * in the command palette. */ label?: string; /** * The optional menus to append this command to. Only valid if `label` is * provided as well. * @default Menu.CommandPalette */ menu?: Menu | Menu[]; /** * A function that is being executed with any arguments passed over. The * return type will be send back to the caller. * * Note: arguments and return type should be serializable so that they can * be exchanged across processes boundaries. */ handler: (...args: any[]) => unknown; } export interface IHomeIndicator { /** * The link to open when clicking the home indicator. */ href: string; /** * The icon name for the home indicator. This needs to be one of the existing * icons from our Codicon icon set. For example `code`. */ icon: string; /** * A tooltip that will appear while hovering over the home indicator. */ title: string; } export interface IWelcomeBanner { /** * Welcome banner message to appear as text. */ message: string; /** * Optional icon for the banner. This is either the URL to an icon to use * or the name of one of the existing icons from our Codicon icon set. * * If not provided a default icon will be used. */ icon?: string | UriComponents; /** * Optional actions to appear as links after the welcome banner message. */ actions?: IWelcomeLinkAction[]; } export interface IWelcomeLinkAction { /** * The link to open when clicking. Supports command invocation when * using the `command:<commandId>` value. */ href: string; /** * The label to show for the action link. */ label: string; /** * A tooltip that will appear while hovering over the action link. */ title?: string; } export interface IWindowIndicator { /** * Triggering this event will cause the window indicator to update. */ readonly onDidChange?: Event<void>; /** * Label of the window indicator may include octicons * e.g. `$(remote) label` */ label: string; /** * Tooltip of the window indicator should not include * octicons and be descriptive. */ tooltip: string; /** * If provided, overrides the default command that * is executed when clicking on the window indicator. */ command?: string; } export enum ColorScheme { DARK = 'dark', LIGHT = 'light', HIGH_CONTRAST_LIGHT = 'hcLight', HIGH_CONTRAST_DARK = 'hcDark' } export interface IInitialColorTheme { /** * Initial color theme type. */ readonly themeType: ColorScheme; /** * A list of workbench colors to apply initially. */ readonly colors?: { [colorId: string]: string }; } export interface IWelcomeDialog { /** * Unique identifier of the welcome dialog. The identifier will be used to determine * if the dialog has been previously displayed. */ id: string; /** * Title of the welcome dialog. */ title: string; /** * Button text of the welcome dialog. */ buttonText: string; /** * Button command to execute from the welcome dialog. */ buttonCommand: string; /** * Message text for the welcome dialog. */ message: string; /** * Media to include in the welcome dialog. */ media: { altText: string; path: string }; } export interface IDefaultView { /** * The identifier of the view to show by default. */ readonly id: string; } export interface IDefaultEditor { /** * The location of the editor in the editor grid layout. * Editors are layed out in editor groups and the view * column is counted from top left to bottom right in * the order of appearance beginning with `1`. * * If not provided, the editor will open in the active * group. */ readonly viewColumn?: number; /** * The resource of the editor to open. */ readonly uri: UriComponents; /** * Optional extra options like which editor * to use or which text to select. */ readonly options?: ITextEditorOptions; /** * Will not open an untitled editor in case * the resource does not exist. */ readonly openOnlyIfExists?: boolean; } export interface IDefaultLayout { /** * A list of views to show by default. */ readonly views?: IDefaultView[]; /** * A list of editors to show by default. */ readonly editors?: IDefaultEditor[]; /** * The layout to use for the workbench. */ readonly layout?: { /** * The layout of the editor area. */ readonly editors?: EditorGroupLayout; }; /** * Forces this layout to be applied even if this isn't * the first time the workspace has been opened */ readonly force?: boolean; } export interface IProductQualityChangeHandler { /** * Handler is being called when the user wants to switch between * `insider` or `stable` product qualities. */ (newQuality: 'insider' | 'stable'): void; } /** * Settings sync options */ export interface ISettingsSyncOptions { /** * Is settings sync enabled */ readonly enabled: boolean; /** * Version of extensions sync state. * Extensions sync state will be reset if version is provided and different from previous version. */ readonly extensionsSyncStateVersion?: string; /** * Handler is being called when the user changes Settings Sync enablement. */ enablementHandler?(enablement: boolean, authenticationProvider: string): void; /** * Authentication provider */ readonly authenticationProvider?: { /** * Unique identifier of the authentication provider. */ readonly id: string; /** * Called when the user wants to signin to Settings Sync using the given authentication provider. * The returned promise should resolve to the authentication session id. */ signIn(): Promise<string>; }; } export interface IDevelopmentOptions { /** * Current logging level. Default is `LogLevel.Info`. */ readonly logLevel?: LogLevel; /** * Extension log level. */ readonly extensionLogLevel?: [string, LogLevel][]; /** * Location of a module containing extension tests to run once the workbench is open. */ readonly extensionTestsPath?: UriComponents; /** * Add extensions under development. */ readonly extensions?: readonly UriComponents[]; /** * Whether to enable the smoke test driver. */ readonly enableSmokeTestDriver?: boolean; } /** * Utility provided in the {@link WorkbenchOptions} which allows loading resources * when remote resolvers are used in the web. */ export interface IRemoteResourceProvider { /** * Path the workbench should delegate requests to. The embedder should * install a service worker on this path and emit {@link onDidReceiveRequest} * events when requests come in for that path. */ readonly path: string; /** * Event that should fire when requests are made on the {@link pathPrefix}. */ readonly onDidReceiveRequest: Event<IRemoteResourceRequest>; } /** * todo@connor4312: this may eventually gain more properties like method and * headers, but for now we only deal with GET requests. */ export interface IRemoteResourceRequest { /** * Request URI. Generally will begin with the current * origin and {@link IRemoteResourceProvider.pathPrefix}. */ uri: URI; /** * A method called by the editor to issue a response to the request. */ respondWith(statusCode: number, body: Uint8Array, headers: Record<string, string>): void; }
src/vs/workbench/browser/web.api.ts
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.0003672027087304741, 0.00017570478667039424, 0.00016073590086307377, 0.00016709370538592339, 0.00003260904850321822 ]
{ "id": 5, "code_window": [ "\n", " - ${{ if eq(parameters.VSCODE_BUILD_LINUX, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: vscode_cli_linux_x64_cli\n", "\n", " - ${{ if eq(parameters.VSCODE_BUILD_LINUX_ARM64, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}\n" ], "file_path": "build/azure-pipelines/linux/cli-build-linux.yml", "type": "add", "edit_start_line_idx": 136 }
parameters: - name: VSCODE_QUALITY type: string - name: VSCODE_BUILD_MACOS type: boolean default: false - name: VSCODE_BUILD_MACOS_ARM64 type: boolean default: false - name: VSCODE_CHECK_ONLY type: boolean default: false steps: - task: NodeTool@0 inputs: versionSource: fromFile versionFilePath: .nvmrc nodejsMirror: https://github.com/joaomoreno/node-mirror/releases/download - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - template: ../cli/cli-apply-patches.yml - task: Npm@1 displayName: Download openssl prebuilt inputs: command: custom customCommand: pack @vscode-internal/[email protected] customRegistry: useFeed customFeed: "Monaco/openssl-prebuilt" workingDir: $(Build.ArtifactStagingDirectory) - script: | set -e mkdir $(Build.ArtifactStagingDirectory)/openssl tar -xvzf $(Build.ArtifactStagingDirectory)/vscode-internal-openssl-prebuilt-0.0.11.tgz --strip-components=1 --directory=$(Build.ArtifactStagingDirectory)/openssl displayName: Extract openssl prebuilt - template: ../cli/install-rust-posix.yml parameters: targets: - ${{ if eq(parameters.VSCODE_BUILD_MACOS, true) }}: - x86_64-apple-darwin - ${{ if eq(parameters.VSCODE_BUILD_MACOS_ARM64, true) }}: - aarch64-apple-darwin - ${{ if eq(parameters.VSCODE_BUILD_MACOS, true) }}: - template: ../cli/cli-compile.yml parameters: VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_CLI_TARGET: x86_64-apple-darwin VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_darwin_x64_cli VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }} VSCODE_CLI_ENV: OPENSSL_LIB_DIR: $(Build.ArtifactStagingDirectory)/openssl/x64-osx/lib OPENSSL_INCLUDE_DIR: $(Build.ArtifactStagingDirectory)/openssl/x64-osx/include - ${{ if eq(parameters.VSCODE_BUILD_MACOS_ARM64, true) }}: - template: ../cli/cli-compile.yml parameters: VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_CLI_TARGET: aarch64-apple-darwin VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_darwin_arm64_cli VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }} VSCODE_CLI_ENV: OPENSSL_LIB_DIR: $(Build.ArtifactStagingDirectory)/openssl/arm64-osx/lib OPENSSL_INCLUDE_DIR: $(Build.ArtifactStagingDirectory)/openssl/arm64-osx/include - ${{ if eq(parameters.VSCODE_BUILD_MACOS, true) }}: - template: ../cli/cli-publish.yml parameters: VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_darwin_x64_cli - ${{ if eq(parameters.VSCODE_BUILD_MACOS_ARM64, true) }}: - template: ../cli/cli-publish.yml parameters: VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_darwin_arm64_cli
build/azure-pipelines/darwin/cli-build-darwin.yml
1
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.2520117461681366, 0.08599772304296494, 0.00016719360428396612, 0.029124092310667038, 0.0983228087425232 ]
{ "id": 5, "code_window": [ "\n", " - ${{ if eq(parameters.VSCODE_BUILD_LINUX, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: vscode_cli_linux_x64_cli\n", "\n", " - ${{ if eq(parameters.VSCODE_BUILD_LINUX_ARM64, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}\n" ], "file_path": "build/azure-pipelines/linux/cli-build-linux.yml", "type": "add", "edit_start_line_idx": 136 }
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M2 2L1 3V13L2 14H14L15 13V3L14 2H2ZM2 13V3H14V13H2ZM12 5H4V6H12V5ZM3 4V7H13V4H3ZM7 9H3V8H7V9ZM3 12H7V11H3V12ZM12 9H10V11H12V9ZM9 8V12H13V8H9Z" fill="#C5C5C5"/> </svg>
extensions/markdown-language-features/media/preview-dark.svg
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.00016868476814124733, 0.00016868476814124733, 0.00016868476814124733, 0.00016868476814124733, 0 ]
{ "id": 5, "code_window": [ "\n", " - ${{ if eq(parameters.VSCODE_BUILD_LINUX, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: vscode_cli_linux_x64_cli\n", "\n", " - ${{ if eq(parameters.VSCODE_BUILD_LINUX_ARM64, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}\n" ], "file_path": "build/azure-pipelines/linux/cli-build-linux.yml", "type": "add", "edit_start_line_idx": 136 }
/*--------------------------------------------------------------------------------------------- * 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 { generateUuid } from 'vs/base/common/uuid'; import { ensureNoDisposablesAreLeakedInTestSuite } from 'vs/base/test/common/utils'; import { Snippet, SnippetSource } from 'vs/workbench/contrib/snippets/browser/snippetsFile'; suite('SnippetRewrite', function () { ensureNoDisposablesAreLeakedInTestSuite(); function assertRewrite(input: string, expected: string | boolean): void { const actual = new Snippet(false, ['foo'], 'foo', 'foo', 'foo', input, 'foo', SnippetSource.User, generateUuid()); if (typeof expected === 'boolean') { assert.strictEqual(actual.codeSnippet, input); } else { assert.strictEqual(actual.codeSnippet, expected); } } test('bogous variable rewrite', function () { assertRewrite('foo', false); assertRewrite('hello $1 world$0', false); assertRewrite('$foo and $foo', '${1:foo} and ${1:foo}'); assertRewrite('$1 and $SELECTION and $foo', '$1 and ${SELECTION} and ${2:foo}'); assertRewrite( [ 'for (var ${index} = 0; ${index} < ${array}.length; ${index}++) {', '\tvar ${element} = ${array}[${index}];', '\t$0', '}' ].join('\n'), [ 'for (var ${1:index} = 0; ${1:index} < ${2:array}.length; ${1:index}++) {', '\tvar ${3:element} = ${2:array}[${1:index}];', '\t$0', '\\}' ].join('\n') ); }); test('Snippet choices: unable to escape comma and pipe, #31521', function () { assertRewrite('console.log(${1|not\\, not, five, 5, 1 23|});', false); }); test('lazy bogous variable rewrite', function () { const snippet = new Snippet(false, ['fooLang'], 'foo', 'prefix', 'desc', 'This is ${bogous} because it is a ${var}', 'source', SnippetSource.Extension, generateUuid()); assert.strictEqual(snippet.body, 'This is ${bogous} because it is a ${var}'); assert.strictEqual(snippet.codeSnippet, 'This is ${1:bogous} because it is a ${2:var}'); assert.strictEqual(snippet.isBogous, true); }); });
src/vs/workbench/contrib/snippets/test/browser/snippetsRewrite.test.ts
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.00019032330601476133, 0.0001722557208267972, 0.0001666087773628533, 0.00016885416698642075, 0.000008278119821625296 ]
{ "id": 5, "code_window": [ "\n", " - ${{ if eq(parameters.VSCODE_BUILD_LINUX, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: vscode_cli_linux_x64_cli\n", "\n", " - ${{ if eq(parameters.VSCODE_BUILD_LINUX_ARM64, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}\n" ], "file_path": "build/azure-pipelines/linux/cli-build-linux.yml", "type": "add", "edit_start_line_idx": 136 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { timeout } from 'vs/base/common/async'; import type { Terminal } from '@xterm/xterm'; export async function writeP(terminal: Terminal, data: string): Promise<void> { return new Promise<void>((resolve, reject) => { const failTimeout = timeout(2000); failTimeout.then(() => reject('Writing to xterm is taking longer than 2 seconds')); terminal.write(data, () => { failTimeout.cancel(); resolve(); }); }); }
src/vs/workbench/contrib/terminal/browser/terminalTestHelpers.ts
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.00018749843002296984, 0.00018073542742058635, 0.00017397242481820285, 0.00018073542742058635, 0.000006763002602383494 ]
{ "id": 6, "code_window": [ " - ${{ if eq(parameters.VSCODE_BUILD_LINUX_ARM64, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: vscode_cli_linux_arm64_cli\n" ], "labels": [ "keep", "keep", "keep", "add" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}" ], "file_path": "build/azure-pipelines/linux/cli-build-linux.yml", "type": "add", "edit_start_line_idx": 141 }
parameters: - name: VSCODE_BUILD_WIN32 type: boolean default: false - name: VSCODE_BUILD_WIN32_ARM64 type: boolean default: false - name: VSCODE_CHECK_ONLY type: boolean default: false - name: VSCODE_QUALITY type: string steps: - task: NodeTool@0 inputs: versionSource: fromFile versionFilePath: .nvmrc nodejsMirror: https://github.com/joaomoreno/node-mirror/releases/download - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - template: ../cli/cli-apply-patches.yml - task: Npm@1 displayName: Download openssl prebuilt inputs: command: custom customCommand: pack @vscode-internal/[email protected] customRegistry: useFeed customFeed: "Monaco/openssl-prebuilt" workingDir: $(Build.ArtifactStagingDirectory) - powershell: | mkdir $(Build.ArtifactStagingDirectory)/openssl tar -xvzf $(Build.ArtifactStagingDirectory)/vscode-internal-openssl-prebuilt-0.0.11.tgz --strip-components=1 --directory=$(Build.ArtifactStagingDirectory)/openssl displayName: Extract openssl prebuilt - template: ../cli/install-rust-win32.yml parameters: targets: - ${{ if eq(parameters.VSCODE_BUILD_WIN32, true) }}: - x86_64-pc-windows-msvc - ${{ if eq(parameters.VSCODE_BUILD_WIN32_ARM64, true) }}: - aarch64-pc-windows-msvc - ${{ if eq(parameters.VSCODE_BUILD_WIN32, true) }}: - template: ../cli/cli-compile.yml parameters: VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_CLI_TARGET: x86_64-pc-windows-msvc VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_win32_x64_cli VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }} VSCODE_CLI_ENV: OPENSSL_LIB_DIR: $(Build.ArtifactStagingDirectory)/openssl/x64-windows-static/lib OPENSSL_INCLUDE_DIR: $(Build.ArtifactStagingDirectory)/openssl/x64-windows-static/include RUSTFLAGS: "-C target-feature=+crt-static" - ${{ if eq(parameters.VSCODE_BUILD_WIN32_ARM64, true) }}: - template: ../cli/cli-compile.yml parameters: VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_CLI_TARGET: aarch64-pc-windows-msvc VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_win32_arm64_cli VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }} VSCODE_CLI_ENV: OPENSSL_LIB_DIR: $(Build.ArtifactStagingDirectory)/openssl/arm64-windows-static/lib OPENSSL_INCLUDE_DIR: $(Build.ArtifactStagingDirectory)/openssl/arm64-windows-static/include RUSTFLAGS: "-C target-feature=+crt-static" - ${{ if eq(parameters.VSCODE_BUILD_WIN32_ARM64, true) }}: - template: ../cli/cli-publish.yml parameters: VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_win32_arm64_cli - ${{ if eq(parameters.VSCODE_BUILD_WIN32, true) }}: - template: ../cli/cli-publish.yml parameters: VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_win32_x64_cli
build/azure-pipelines/win32/cli-build-win32.yml
1
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.530941367149353, 0.09761419892311096, 0.00016702279390301555, 0.019541501998901367, 0.17135347425937653 ]
{ "id": 6, "code_window": [ " - ${{ if eq(parameters.VSCODE_BUILD_LINUX_ARM64, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: vscode_cli_linux_arm64_cli\n" ], "labels": [ "keep", "keep", "keep", "add" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}" ], "file_path": "build/azure-pipelines/linux/cli-build-linux.yml", "type": "add", "edit_start_line_idx": 141 }
/*--------------------------------------------------------------------------------------------- * 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 'mocha'; import * as vscode from 'vscode'; import { asPromise, disposeAll } from '../utils'; import { Kernel, saveAllFilesAndCloseAll } from './notebook.api.test'; export type INativeInteractiveWindow = { notebookUri: vscode.Uri; inputUri: vscode.Uri; notebookEditor: vscode.NotebookEditor }; async function createInteractiveWindow(kernel: Kernel) { const { notebookEditor, inputUri } = (await vscode.commands.executeCommand( 'interactive.open', // Keep focus on the owning file if there is one { viewColumn: vscode.ViewColumn.Beside, preserveFocus: false }, undefined, `vscode.vscode-api-tests/${kernel.controller.id}`, undefined )) as unknown as INativeInteractiveWindow; assert.ok(notebookEditor, 'Interactive Window was not created successfully'); return { notebookEditor, inputUri }; } async function addCell(code: string, notebook: vscode.NotebookDocument) { const cell = new vscode.NotebookCellData(vscode.NotebookCellKind.Code, code, 'typescript'); const edit = vscode.NotebookEdit.insertCells(notebook.cellCount, [cell]); const workspaceEdit = new vscode.WorkspaceEdit(); workspaceEdit.set(notebook.uri, [edit]); const event = asPromise(vscode.workspace.onDidChangeNotebookDocument); await vscode.workspace.applyEdit(workspaceEdit); await event; return notebook.cellAt(notebook.cellCount - 1); } async function addCellAndRun(code: string, notebook: vscode.NotebookDocument) { const initialCellCount = notebook.cellCount; const cell = await addCell(code, notebook); const event = asPromise(vscode.workspace.onDidChangeNotebookDocument); await vscode.commands.executeCommand('notebook.cell.execute', { start: initialCellCount, end: initialCellCount + 1 }, notebook.uri); try { await event; } catch (e) { const result = notebook.cellAt(notebook.cellCount - 1); assert.fail(`Notebook change event was not triggered after executing newly added cell. Initial Cell count: ${initialCellCount}. Current cell count: ${notebook.cellCount}. execution summary: ${JSON.stringify(result.executionSummary)}`); } assert.strictEqual(cell.outputs.length, 1, `Executed cell has no output. Initial Cell count: ${initialCellCount}. Current cell count: ${notebook.cellCount}. execution summary: ${JSON.stringify(cell.executionSummary)}`); return cell; } (vscode.env.uiKind === vscode.UIKind.Web ? suite.skip : suite)('Interactive Window', function () { const testDisposables: vscode.Disposable[] = []; let defaultKernel: Kernel; let secondKernel: Kernel; setup(async function () { defaultKernel = new Kernel('mainKernel', 'Notebook Default Kernel', 'interactive'); secondKernel = new Kernel('secondKernel', 'Notebook Secondary Kernel', 'interactive'); testDisposables.push(defaultKernel.controller); testDisposables.push(secondKernel.controller); await saveAllFilesAndCloseAll(); }); teardown(async function () { disposeAll(testDisposables); testDisposables.length = 0; await saveAllFilesAndCloseAll(); }); test('Can open an interactive window and execute from input box', async () => { assert.ok(vscode.workspace.workspaceFolders); const { notebookEditor, inputUri } = await createInteractiveWindow(defaultKernel); const inputBox = vscode.window.visibleTextEditors.find( (e) => e.document.uri.path === inputUri.path ); await inputBox!.edit((editBuilder) => { editBuilder.insert(new vscode.Position(0, 0), 'print foo'); }); await vscode.commands.executeCommand('interactive.execute', notebookEditor.notebook.uri); assert.strictEqual(notebookEditor.notebook.cellCount, 1); assert.strictEqual(notebookEditor.notebook.cellAt(0).kind, vscode.NotebookCellKind.Code); }); test('Interactive window scrolls after execute', async () => { assert.ok(vscode.workspace.workspaceFolders); const { notebookEditor } = await createInteractiveWindow(defaultKernel); // Run and add a bunch of cells for (let i = 0; i < 10; i++) { await addCellAndRun(`print ${i}`, notebookEditor.notebook); } // Verify visible range has the last cell assert.strictEqual(notebookEditor.visibleRanges[notebookEditor.visibleRanges.length - 1].end, notebookEditor.notebook.cellCount, `Last cell is not visible`); }); test('Interactive window has the correct kernel', async () => { assert.ok(vscode.workspace.workspaceFolders); await createInteractiveWindow(defaultKernel); await vscode.commands.executeCommand('workbench.action.closeActiveEditor'); // Create a new interactive window with a different kernel const { notebookEditor } = await createInteractiveWindow(secondKernel); assert.ok(notebookEditor); // Verify the kernel is the secondary one await addCellAndRun(`print`, notebookEditor.notebook); assert.strictEqual(secondKernel.associatedNotebooks.has(notebookEditor.notebook.uri.toString()), true, `Secondary kernel was not set as the kernel for the interactive window`); }); });
extensions/vscode-api-tests/src/singlefolder-tests/interactiveWindow.test.ts
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.00017577757535036653, 0.00016866953228600323, 0.00016557681374251842, 0.00016725261230021715, 0.000003091999815296731 ]
{ "id": 6, "code_window": [ " - ${{ if eq(parameters.VSCODE_BUILD_LINUX_ARM64, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: vscode_cli_linux_arm64_cli\n" ], "labels": [ "keep", "keep", "keep", "add" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}" ], "file_path": "build/azure-pipelines/linux/cli-build-linux.yml", "type": "add", "edit_start_line_idx": 141 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; import { URI } from 'vs/base/common/uri'; import { assertIsDefined } from 'vs/base/common/types'; import { ITextEditorPane } from 'vs/workbench/common/editor'; import { applyTextEditorOptions } from 'vs/workbench/common/editor/editorOptions'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { ITextEditorOptions } from 'vs/platform/editor/common/editor'; import { isEqual } from 'vs/base/common/resources'; import { IEditorOptions as ICodeEditorOptions } from 'vs/editor/common/config/editorOptions'; import { CodeEditorWidget, ICodeEditorWidgetOptions } from 'vs/editor/browser/widget/codeEditorWidget'; import { IEditorViewState, ScrollType } from 'vs/editor/common/editorCommon'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { AbstractTextEditor } from 'vs/workbench/browser/parts/editor/textEditor'; import { Dimension } from 'vs/base/browser/dom'; import { IEditorGroup } from 'vs/workbench/services/editor/common/editorGroupsService'; /** * A text editor using the code editor widget. */ export abstract class AbstractTextCodeEditor<T extends IEditorViewState> extends AbstractTextEditor<T> implements ITextEditorPane { protected editorControl: ICodeEditor | undefined = undefined; override get scopedContextKeyService(): IContextKeyService | undefined { return this.editorControl?.invokeWithinContext(accessor => accessor.get(IContextKeyService)); } override getTitle(): string { if (this.input) { return this.input.getName(); } return localize('textEditor', "Text Editor"); } protected createEditorControl(parent: HTMLElement, initialOptions: ICodeEditorOptions): void { this.editorControl = this._register(this.instantiationService.createInstance(CodeEditorWidget, parent, initialOptions, this.getCodeEditorWidgetOptions())); } protected getCodeEditorWidgetOptions(): ICodeEditorWidgetOptions { return Object.create(null); } protected updateEditorControlOptions(options: ICodeEditorOptions): void { this.editorControl?.updateOptions(options); } protected getMainControl(): ICodeEditor | undefined { return this.editorControl; } override getControl(): ICodeEditor | undefined { return this.editorControl; } protected override computeEditorViewState(resource: URI): T | undefined { if (!this.editorControl) { return undefined; } const model = this.editorControl.getModel(); if (!model) { return undefined; // view state always needs a model } const modelUri = model.uri; if (!modelUri) { return undefined; // model URI is needed to make sure we save the view state correctly } if (!isEqual(modelUri, resource)) { return undefined; // prevent saving view state for a model that is not the expected one } return this.editorControl.saveViewState() as unknown as T ?? undefined; } override setOptions(options: ITextEditorOptions | undefined): void { super.setOptions(options); if (options) { applyTextEditorOptions(options, assertIsDefined(this.editorControl), ScrollType.Smooth); } } override focus(): void { super.focus(); this.editorControl?.focus(); } override hasFocus(): boolean { return this.editorControl?.hasTextFocus() || super.hasFocus(); } protected override setEditorVisible(visible: boolean, group: IEditorGroup | undefined): void { super.setEditorVisible(visible, group); if (visible) { this.editorControl?.onVisible(); } else { this.editorControl?.onHide(); } } override layout(dimension: Dimension): void { this.editorControl?.layout(dimension); } }
src/vs/workbench/browser/parts/editor/textCodeEditor.ts
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.00017279268649872392, 0.00017033315089065582, 0.00016723634325899184, 0.0001707613409962505, 0.0000016929781168073532 ]
{ "id": 6, "code_window": [ " - ${{ if eq(parameters.VSCODE_BUILD_LINUX_ARM64, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: vscode_cli_linux_arm64_cli\n" ], "labels": [ "keep", "keep", "keep", "add" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}" ], "file_path": "build/azure-pipelines/linux/cli-build-linux.yml", "type": "add", "edit_start_line_idx": 141 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /** Notification: Container */ .monaco-workbench .notifications-list-container { color: var(--vscode-notifications-foreground); background: var(--vscode-notifications-background); outline-color: var(--vscode-contrastBorder); border-radius: inherit; } .monaco-workbench .notifications-list-container .notification-list-item { display: flex; flex-direction: column; flex-direction: column-reverse; /* the details row appears first in order for better keyboard access to notification buttons */ padding: 10px 5px; height: 100%; box-sizing: border-box; border-radius: 4px; } .monaco-workbench .notifications-list-container .notification-offset-helper { opacity: 0; position: absolute; line-height: 22px; word-wrap: break-word; /* never overflow long words, but break to next line */ } .monaco-workbench .notifications-list-container .monaco-scrollable-element { border-radius: 4px; } /** Notification: Main Row */ .monaco-workbench .notifications-list-container .notification-list-item > .notification-list-item-main-row { display: flex; flex-grow: 1; } /** Notification: Icon */ .monaco-workbench .notifications-list-container .notification-list-item .notification-list-item-icon { display: flex; align-items: center; flex: 0 0 16px; height: 22px; margin-right: 4px; margin-left: 4px; font-size: 18px; background-position: center; background-repeat: no-repeat; } /** Notification: Message */ .monaco-workbench .notifications-list-container .notification-list-item .notification-list-item-message { line-height: 22px; overflow: hidden; text-overflow: ellipsis; flex: 1; /* let the message always grow */ user-select: text; -webkit-user-select: text; } .monaco-workbench .notifications-list-container .notification-list-item .notification-list-item-message a { color: var(--vscode-notificationLink-foreground); } .monaco-workbench .notifications-list-container .notification-list-item .notification-list-item-message a:focus { outline-width: 1px; outline-style: solid; outline-color: var(--vscode-focusBorder); } .monaco-workbench .notifications-list-container .notification-list-item.expanded .notification-list-item-message { white-space: normal; word-wrap: break-word; /* never overflow long words, but break to next line */ } /** Notification: Toolbar Container */ .monaco-workbench .notifications-list-container .notification-list-item .notification-list-item-toolbar-container { display: none; height: 22px; } .monaco-workbench .notifications-list-container .monaco-list:focus-within .notification-list-item .notification-list-item-toolbar-container, .monaco-workbench .notifications-list-container .notification-list-item:hover .notification-list-item-toolbar-container, .monaco-workbench .notifications-list-container .monaco-list-row.focused .notification-list-item .notification-list-item-toolbar-container, .monaco-workbench .notifications-list-container .notification-list-item.expanded .notification-list-item-toolbar-container { display: block; } /** Notification: Details Row */ .monaco-workbench .notifications-list-container .notification-list-item > .notification-list-item-details-row { display: none; align-items: center; padding-left: 5px; overflow: hidden; /* details row should never overflow */ } .monaco-workbench .notifications-list-container .notification-list-item.expanded > .notification-list-item-details-row { display: flex; } /** Notification: Source */ .monaco-workbench .notifications-list-container .notification-list-item .notification-list-item-source { flex: 1; font-size: 12px; overflow: hidden; /* always give away space to buttons container */ text-overflow: ellipsis; } /** Notification: Buttons */ .monaco-workbench .notifications-list-container .notification-list-item .notification-list-item-buttons-container { display: flex; overflow: hidden; } .monaco-workbench .notifications-list-container .notification-list-item .notification-list-item-buttons-container > .monaco-button-dropdown, .monaco-workbench .notifications-list-container .notification-list-item .notification-list-item-buttons-container > .monaco-button { margin: 4px 5px; /* allows button focus outline to be visible */ } .monaco-workbench .notifications-list-container .notification-list-item .notification-list-item-buttons-container .monaco-button { outline-offset: 2px !important; } .monaco-workbench .notifications-list-container .notification-list-item .notification-list-item-buttons-container .monaco-text-button { width: fit-content; padding: 4px 10px; display: inline-block; /* to enable ellipsis in text overflow */ font-size: 12px; overflow: hidden; text-overflow: ellipsis; } .monaco-workbench .notifications-list-container .notification-list-item .notification-list-item-buttons-container .monaco-dropdown-button { padding: 5px } /** Notification: Progress */ .monaco-workbench .notifications-list-container .progress-bit { bottom: 0; }
src/vs/workbench/browser/parts/notifications/media/notificationsList.css
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.0001730137737467885, 0.0001690155331743881, 0.00016559718642383814, 0.00016843956836964935, 0.000001844384428295598 ]
{ "id": 7, "code_window": [ "\n", " - ${{ if eq(parameters.VSCODE_BUILD_WIN32_ARM64, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_win32_arm64_cli\n", "\n", " - ${{ if eq(parameters.VSCODE_BUILD_WIN32, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}\n" ], "file_path": "build/azure-pipelines/win32/cli-build-win32.yml", "type": "add", "edit_start_line_idx": 73 }
parameters: - name: VSCODE_BUILD_LINUX type: boolean default: false - name: VSCODE_BUILD_LINUX_ARM64 type: boolean default: false - name: VSCODE_BUILD_LINUX_ARMHF type: boolean default: false - name: VSCODE_CHECK_ONLY type: boolean default: false - name: VSCODE_QUALITY type: string steps: - task: NodeTool@0 inputs: versionSource: fromFile versionFilePath: .nvmrc nodejsMirror: https://github.com/joaomoreno/node-mirror/releases/download - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - template: ../cli/cli-apply-patches.yml - task: Npm@1 displayName: Download openssl prebuilt inputs: command: custom customCommand: pack @vscode-internal/[email protected] customRegistry: useFeed customFeed: "Monaco/openssl-prebuilt" workingDir: $(Build.ArtifactStagingDirectory) - script: | set -e mkdir $(Build.ArtifactStagingDirectory)/openssl tar -xvzf $(Build.ArtifactStagingDirectory)/vscode-internal-openssl-prebuilt-0.0.11.tgz --strip-components=1 --directory=$(Build.ArtifactStagingDirectory)/openssl displayName: Extract openssl prebuilt - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - script: node build/setup-npm-registry.js $NPM_REGISTRY condition: and(succeeded(), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM Registry - script: | set -e npm config set registry "$NPM_REGISTRY" --location=project # npm >v7 deprecated the `always-auth` config option, refs npm/cli@72a7eeb # following is a workaround for yarn to send authorization header # for GET requests to the registry. echo "always-auth=true" >> .npmrc yarn config set registry "$NPM_REGISTRY" condition: and(succeeded(), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM & Yarn - task: npmAuthenticate@0 inputs: workingFile: .npmrc condition: and(succeeded(), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM Authentication - script: | set -e for i in {1..5}; do # try 5 times yarn --cwd build --frozen-lockfile --check-files && break if [ $i -eq 3 ]; then echo "Yarn failed too many times" >&2 exit 1 fi echo "Yarn failed $i, trying again..." done displayName: Install build dependencies - script: | set -e mkdir -p $(Build.SourcesDirectory)/.build displayName: Create .build folder for misc dependencies - template: ../cli/install-rust-posix.yml parameters: targets: - ${{ if eq(parameters.VSCODE_BUILD_LINUX_ARM64, true) }}: - aarch64-unknown-linux-gnu - ${{ if eq(parameters.VSCODE_BUILD_LINUX, true) }}: - x86_64-unknown-linux-gnu - ${{ if eq(parameters.VSCODE_BUILD_LINUX_ARMHF, true) }}: - armv7-unknown-linux-gnueabihf - ${{ if eq(parameters.VSCODE_BUILD_LINUX_ARM64, true) }}: - template: ../cli/cli-compile.yml parameters: VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_CLI_TARGET: aarch64-unknown-linux-gnu VSCODE_CLI_ARTIFACT: vscode_cli_linux_arm64_cli VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }} VSCODE_CLI_ENV: OPENSSL_LIB_DIR: $(Build.ArtifactStagingDirectory)/openssl/arm64-linux/lib OPENSSL_INCLUDE_DIR: $(Build.ArtifactStagingDirectory)/openssl/arm64-linux/include SYSROOT_ARCH: arm64 - ${{ if eq(parameters.VSCODE_BUILD_LINUX, true) }}: - template: ../cli/cli-compile.yml parameters: VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_CLI_TARGET: x86_64-unknown-linux-gnu VSCODE_CLI_ARTIFACT: vscode_cli_linux_x64_cli VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }} VSCODE_CLI_ENV: OPENSSL_LIB_DIR: $(Build.ArtifactStagingDirectory)/openssl/x64-linux/lib OPENSSL_INCLUDE_DIR: $(Build.ArtifactStagingDirectory)/openssl/x64-linux/include SYSROOT_ARCH: amd64 - ${{ if eq(parameters.VSCODE_BUILD_LINUX_ARMHF, true) }}: - template: ../cli/cli-compile.yml parameters: VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_CLI_TARGET: armv7-unknown-linux-gnueabihf VSCODE_CLI_ARTIFACT: vscode_cli_linux_armhf_cli VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }} VSCODE_CLI_ENV: OPENSSL_LIB_DIR: $(Build.ArtifactStagingDirectory)/openssl/arm-linux/lib OPENSSL_INCLUDE_DIR: $(Build.ArtifactStagingDirectory)/openssl/arm-linux/include SYSROOT_ARCH: armhf - ${{ if eq(parameters.VSCODE_BUILD_LINUX_ARMHF, true) }}: - template: ../cli/cli-publish.yml parameters: VSCODE_CLI_ARTIFACT: vscode_cli_linux_armhf_cli - ${{ if eq(parameters.VSCODE_BUILD_LINUX, true) }}: - template: ../cli/cli-publish.yml parameters: VSCODE_CLI_ARTIFACT: vscode_cli_linux_x64_cli - ${{ if eq(parameters.VSCODE_BUILD_LINUX_ARM64, true) }}: - template: ../cli/cli-publish.yml parameters: VSCODE_CLI_ARTIFACT: vscode_cli_linux_arm64_cli
build/azure-pipelines/linux/cli-build-linux.yml
1
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.11492257565259933, 0.02739821933209896, 0.00016722023428883404, 0.011739548295736313, 0.03416299447417259 ]
{ "id": 7, "code_window": [ "\n", " - ${{ if eq(parameters.VSCODE_BUILD_WIN32_ARM64, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_win32_arm64_cli\n", "\n", " - ${{ if eq(parameters.VSCODE_BUILD_WIN32, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}\n" ], "file_path": "build/azure-pipelines/win32/cli-build-win32.yml", "type": "add", "edit_start_line_idx": 73 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ export const flatTestItemDelimiter = ' \u203A ';
src/vs/workbench/contrib/testing/browser/explorerProjections/display.ts
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.00016917991160880774, 0.00016917991160880774, 0.00016917991160880774, 0.00016917991160880774, 0 ]
{ "id": 7, "code_window": [ "\n", " - ${{ if eq(parameters.VSCODE_BUILD_WIN32_ARM64, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_win32_arm64_cli\n", "\n", " - ${{ if eq(parameters.VSCODE_BUILD_WIN32, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}\n" ], "file_path": "build/azure-pipelines/win32/cli-build-win32.yml", "type": "add", "edit_start_line_idx": 73 }
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 "@microsoft/[email protected]", "@microsoft/1ds-core-js@^4.0.3": version "4.0.3" resolved "https://registry.yarnpkg.com/@microsoft/1ds-core-js/-/1ds-core-js-4.0.3.tgz#c8a92c623745a9595e06558a866658480c33bdf9" integrity sha512-FrxNLVAPsAvD7+l63TlNS/Kodvpct2WulpDSn1dI4Xuy0kF4E2H867kHdwL/iY1Bj3zA3FSy/jvE4+OcDws7ug== dependencies: "@microsoft/applicationinsights-core-js" "3.0.4" "@microsoft/applicationinsights-shims" "3.0.1" "@microsoft/dynamicproto-js" "^2.0.2" "@nevware21/ts-async" ">= 0.3.0 < 2.x" "@nevware21/ts-utils" ">= 0.10.1 < 2.x" "@microsoft/1ds-post-js@^4.0.3": version "4.0.3" resolved "https://registry.yarnpkg.com/@microsoft/1ds-post-js/-/1ds-post-js-4.0.3.tgz#cfcb20bb23fb6215d3f0732f60f5b7df3e624f86" integrity sha512-uewvmUtXKd7ttypiKQGdYI6i7UUpPkOznLayzIFrJ4r2xnG6jhPjpKRncHFXPQcM4XSWO3yf5PQ3xAbPq9t7ZQ== dependencies: "@microsoft/1ds-core-js" "4.0.3" "@microsoft/applicationinsights-shims" "3.0.1" "@microsoft/dynamicproto-js" "^2.0.2" "@nevware21/ts-async" ">= 0.3.0 < 2.x" "@nevware21/ts-utils" ">= 0.10.1 < 2.x" "@microsoft/[email protected]": version "3.0.4" resolved "https://registry.yarnpkg.com/@microsoft/applicationinsights-channel-js/-/applicationinsights-channel-js-3.0.4.tgz#247b6fe2158fad9826cbcdf7304f885766b36624" integrity sha512-6TlfExmErQ8Y+/ChbkyWl+jyt4wg3T6p7lwXDsUCB0LgZmlEWMaCUS0YlT73JCWmE8j7vxW8yUm0lgsgmHns3A== dependencies: "@microsoft/applicationinsights-common" "3.0.4" "@microsoft/applicationinsights-core-js" "3.0.4" "@microsoft/applicationinsights-shims" "3.0.1" "@microsoft/dynamicproto-js" "^2.0.2" "@nevware21/ts-async" ">= 0.3.0 < 2.x" "@nevware21/ts-utils" ">= 0.10.1 < 2.x" "@microsoft/[email protected]": version "3.0.4" resolved "https://registry.yarnpkg.com/@microsoft/applicationinsights-common/-/applicationinsights-common-3.0.4.tgz#c4aa53ba343f5b3c7fbf54cddd3c86a5bdcd95dc" integrity sha512-r5gWaw/K9+tKfuo2GtDiDiKASgOkPOCrKW+wZzFvuR06uuwvWjbVQ6yW/YbnfuhRF5M65ksUiMi0eCMwEOGq7Q== dependencies: "@microsoft/applicationinsights-core-js" "3.0.4" "@microsoft/applicationinsights-shims" "3.0.1" "@microsoft/dynamicproto-js" "^2.0.2" "@nevware21/ts-utils" ">= 0.10.1 < 2.x" "@microsoft/[email protected]": version "3.0.4" resolved "https://registry.yarnpkg.com/@microsoft/applicationinsights-core-js/-/applicationinsights-core-js-3.0.4.tgz#008308b786930d94a1de8a1fbb4af0351b74653e" integrity sha512-anxy5kEkqBmVoEqJiJzaaXXA0wzqZi9U4zGd05xFJ04lWckP8dG3zyT3+GGdg7rDelqLTNGxndeYoFmDv63u1g== dependencies: "@microsoft/applicationinsights-shims" "3.0.1" "@microsoft/dynamicproto-js" "^2.0.2" "@nevware21/ts-async" ">= 0.3.0 < 2.x" "@nevware21/ts-utils" ">= 0.10.1 < 2.x" "@microsoft/[email protected]": version "3.0.1" resolved "https://registry.yarnpkg.com/@microsoft/applicationinsights-shims/-/applicationinsights-shims-3.0.1.tgz#3865b73ace8405b9c4618cc5c571f2fe3876f06f" integrity sha512-DKwboF47H1nb33rSUfjqI6ryX29v+2QWcTrRvcQDA32AZr5Ilkr7whOOSsD1aBzwqX0RJEIP1Z81jfE3NBm/Lg== dependencies: "@nevware21/ts-utils" ">= 0.9.4 < 2.x" "@microsoft/applicationinsights-web-basic@^3.0.4": version "3.0.4" resolved "https://registry.yarnpkg.com/@microsoft/applicationinsights-web-basic/-/applicationinsights-web-basic-3.0.4.tgz#9a23323276b4a5a0dc6a352e2de5d75e3c16b534" integrity sha512-KfoxPlLlf0JT12ADb23C5iGye/yFouoMgHEKULxkSQcYY9SsW/8rVrqqvoYKAL+u215CZU2A8Kc8sR3ehEaPCQ== dependencies: "@microsoft/applicationinsights-channel-js" "3.0.4" "@microsoft/applicationinsights-common" "3.0.4" "@microsoft/applicationinsights-core-js" "3.0.4" "@microsoft/applicationinsights-shims" "3.0.1" "@microsoft/dynamicproto-js" "^2.0.2" "@nevware21/ts-async" ">= 0.3.0 < 2.x" "@nevware21/ts-utils" ">= 0.10.1 < 2.x" "@microsoft/dynamicproto-js@^2.0.2": version "2.0.2" resolved "https://registry.yarnpkg.com/@microsoft/dynamicproto-js/-/dynamicproto-js-2.0.2.tgz#e57fbec2e7067d48b7e8e1e1c1d354028ef718a6" integrity sha512-MB8trWaFREpmb037k/d0bB7T2BP7Ai24w1e1tbz3ASLB0/lwphsq3Nq8S9I5AsI5vs4zAQT+SB5nC5/dLYTiOg== dependencies: "@nevware21/ts-utils" ">= 0.9.4 < 2.x" "@nevware21/ts-async@>= 0.3.0 < 2.x": version "0.3.0" resolved "https://registry.yarnpkg.com/@nevware21/ts-async/-/ts-async-0.3.0.tgz#a8b97ba01065fc930de9a3f4dd4a05e862becc6c" integrity sha512-ZUcgUH12LN/F6nzN0cYd0F/rJaMLmXr0EHVTyYfaYmK55bdwE4338uue4UiVoRqHVqNW4KDUrJc49iGogHKeWA== dependencies: "@nevware21/ts-utils" ">= 0.10.0 < 2.x" "@nevware21/ts-utils@>= 0.10.0 < 2.x", "@nevware21/ts-utils@>= 0.10.1 < 2.x", "@nevware21/ts-utils@>= 0.9.4 < 2.x": version "0.10.1" resolved "https://registry.yarnpkg.com/@nevware21/ts-utils/-/ts-utils-0.10.1.tgz#aa65abc71eba06749a396598f22263d26f796ac7" integrity sha512-pMny25NnF2/MJwdqC3Iyjm2pGIXNxni4AROpcqDeWa+td9JMUY4bUS9uU9XW+BoBRqTLUL+WURF9SOd/6OQzRg== "@types/[email protected]": version "18.15.13" resolved "https://registry.yarnpkg.com/@types/node/-/node-18.15.13.tgz#f64277c341150c979e42b00e4ac289290c9df469" integrity sha512-N+0kuo9KgrUQ1Sn/ifDXsvg0TTleP7rIy4zOBGECxAljqvqfqpTfzx0Q1NUedOixRMBfe2Whhb056a42cWs26Q== "@vscode/extension-telemetry@^0.9.0": version "0.9.0" resolved "https://registry.yarnpkg.com/@vscode/extension-telemetry/-/extension-telemetry-0.9.0.tgz#8c6c61e253ff304f46045f04edd60059b144417a" integrity sha512-37RxGHXrs3GoXPgCUKQhghEu0gxs8j27RLjQwwtSf4WhPdJKz8UrqMYzpsXlliQ05zURYmtdGZst9C6+hfWXaQ== dependencies: "@microsoft/1ds-core-js" "^4.0.3" "@microsoft/1ds-post-js" "^4.0.3" "@microsoft/applicationinsights-web-basic" "^3.0.4" balanced-match@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767" integrity sha1-ibTRmasr7kneFk6gK4nORi1xt2c= brace-expansion@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-2.0.1.tgz#1edc459e0f0c548486ecf9fc99f2221364b9a0ae" integrity sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA== dependencies: balanced-match "^1.0.0" lru-cache@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-6.0.0.tgz#6d6fe6570ebd96aaf90fcad1dafa3b2566db3a94" integrity sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA== dependencies: yallist "^4.0.0" minimatch@^5.1.0: version "5.1.6" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-5.1.6.tgz#1cfcb8cf5522ea69952cd2af95ae09477f122a96" integrity sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g== dependencies: brace-expansion "^2.0.1" request-light@^0.7.0: version "0.7.0" resolved "https://registry.yarnpkg.com/request-light/-/request-light-0.7.0.tgz#885628bb2f8040c26401ebf258ec51c4ae98ac2a" integrity sha512-lMbBMrDoxgsyO+yB3sDcrDuX85yYt7sS8BfQd11jtbW/z5ZWgLZRcEGLsLoYw7I0WSUGQBs8CC8ScIxkTX1+6Q== semver@^7.3.7: version "7.5.4" resolved "https://registry.yarnpkg.com/semver/-/semver-7.5.4.tgz#483986ec4ed38e1c6c48c34894a9182dbff68a6e" integrity sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA== dependencies: lru-cache "^6.0.0" [email protected]: version "8.2.0" resolved "https://registry.yarnpkg.com/vscode-jsonrpc/-/vscode-jsonrpc-8.2.0.tgz#f43dfa35fb51e763d17cd94dcca0c9458f35abf9" integrity sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA== [email protected]: version "9.0.1" resolved "https://registry.yarnpkg.com/vscode-languageclient/-/vscode-languageclient-9.0.1.tgz#cdfe20267726c8d4db839dc1e9d1816e1296e854" integrity sha512-JZiimVdvimEuHh5olxhxkht09m3JzUGwggb5eRUkzzJhZ2KjCN0nh55VfiED9oez9DyF8/fz1g1iBV3h+0Z2EA== dependencies: minimatch "^5.1.0" semver "^7.3.7" vscode-languageserver-protocol "3.17.5" [email protected]: version "3.17.5" resolved "https://registry.yarnpkg.com/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.5.tgz#864a8b8f390835572f4e13bd9f8313d0e3ac4bea" integrity sha512-mb1bvRJN8SVznADSGWM9u/b07H7Ecg0I3OgXDuLdn307rl/J3A9YD6/eYOssqhecL27hK1IPZAsaqh00i/Jljg== dependencies: vscode-jsonrpc "8.2.0" vscode-languageserver-types "3.17.5" [email protected]: version "3.17.5" resolved "https://registry.yarnpkg.com/vscode-languageserver-types/-/vscode-languageserver-types-3.17.5.tgz#3273676f0cf2eab40b3f44d085acbb7f08a39d8a" integrity sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg== yallist@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72" integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==
extensions/json-language-features/yarn.lock
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.0010118656791746616, 0.0002200357848778367, 0.0001622036361368373, 0.0001663121220190078, 0.0001889609411591664 ]
{ "id": 7, "code_window": [ "\n", " - ${{ if eq(parameters.VSCODE_BUILD_WIN32_ARM64, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_win32_arm64_cli\n", "\n", " - ${{ if eq(parameters.VSCODE_BUILD_WIN32, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}\n" ], "file_path": "build/azure-pipelines/win32/cli-build-win32.yml", "type": "add", "edit_start_line_idx": 73 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CancellationToken } from 'vs/base/common/cancellation'; type SparseEmbedding = Record</* word */ string, /* weight */number>; type TermFrequencies = Map</* word */ string, /*occurrences*/ number>; type DocumentOccurrences = Map</* word */ string, /*documentOccurrences*/ number>; function countMapFrom<K>(values: Iterable<K>): Map<K, number> { const map = new Map<K, number>(); for (const value of values) { map.set(value, (map.get(value) ?? 0) + 1); } return map; } interface DocumentChunkEntry { readonly text: string; readonly tf: TermFrequencies; } export interface TfIdfDocument { readonly key: string; readonly textChunks: readonly string[]; } export interface TfIdfScore { readonly key: string; /** * An unbounded number. */ readonly score: number; } export interface NormalizedTfIdfScore { readonly key: string; /** * A number between 0 and 1. */ readonly score: number; } /** * Implementation of tf-idf (term frequency-inverse document frequency) for a set of * documents where each document contains one or more chunks of text. * Each document is identified by a key, and the score for each document is computed * by taking the max score over all the chunks in the document. */ export class TfIdfCalculator { calculateScores(query: string, token: CancellationToken): TfIdfScore[] { const embedding = this.computeEmbedding(query); const idfCache = new Map<string, number>(); const scores: TfIdfScore[] = []; // For each document, generate one score for (const [key, doc] of this.documents) { if (token.isCancellationRequested) { return []; } for (const chunk of doc.chunks) { const score = this.computeSimilarityScore(chunk, embedding, idfCache); if (score > 0) { scores.push({ key, score }); } } } return scores; } /** * Count how many times each term (word) appears in a string. */ private static termFrequencies(input: string): TermFrequencies { return countMapFrom(TfIdfCalculator.splitTerms(input)); } /** * Break a string into terms (words). */ private static *splitTerms(input: string): Iterable<string> { const normalize = (word: string) => word.toLowerCase(); // Only match on words that are at least 3 characters long and start with a letter for (const [word] of input.matchAll(/\b\p{Letter}[\p{Letter}\d]{2,}\b/gu)) { yield normalize(word); const camelParts = word.replace(/([a-z])([A-Z])/g, '$1 $2').split(/\s+/g); if (camelParts.length > 1) { for (const part of camelParts) { // Require at least 3 letters in the parts of a camel case word if (part.length > 2 && /\p{Letter}{3,}/gu.test(part)) { yield normalize(part); } } } } } /** * Total number of chunks */ private chunkCount = 0; private readonly chunkOccurrences: DocumentOccurrences = new Map</* word */ string, /*documentOccurrences*/ number>(); private readonly documents = new Map</* key */ string, { readonly chunks: ReadonlyArray<DocumentChunkEntry>; }>(); updateDocuments(documents: ReadonlyArray<TfIdfDocument>): this { for (const { key } of documents) { this.deleteDocument(key); } for (const doc of documents) { const chunks: Array<{ text: string; tf: TermFrequencies }> = []; for (const text of doc.textChunks) { // TODO: See if we can compute the tf lazily // The challenge is that we need to also update the `chunkOccurrences` // and all of those updates need to get flushed before the real TF-IDF of // anything is computed. const tf = TfIdfCalculator.termFrequencies(text); // Update occurrences list for (const term of tf.keys()) { this.chunkOccurrences.set(term, (this.chunkOccurrences.get(term) ?? 0) + 1); } chunks.push({ text, tf }); } this.chunkCount += chunks.length; this.documents.set(doc.key, { chunks }); } return this; } deleteDocument(key: string) { const doc = this.documents.get(key); if (!doc) { return; } this.documents.delete(key); this.chunkCount -= doc.chunks.length; // Update term occurrences for the document for (const chunk of doc.chunks) { for (const term of chunk.tf.keys()) { const currentOccurrences = this.chunkOccurrences.get(term); if (typeof currentOccurrences === 'number') { const newOccurrences = currentOccurrences - 1; if (newOccurrences <= 0) { this.chunkOccurrences.delete(term); } else { this.chunkOccurrences.set(term, newOccurrences); } } } } } private computeSimilarityScore(chunk: DocumentChunkEntry, queryEmbedding: SparseEmbedding, idfCache: Map<string, number>): number { // Compute the dot product between the chunk's embedding and the query embedding // Note that the chunk embedding is computed lazily on a per-term basis. // This lets us skip a large number of calculations because the majority // of chunks do not share any terms with the query. let sum = 0; for (const [term, termTfidf] of Object.entries(queryEmbedding)) { const chunkTf = chunk.tf.get(term); if (!chunkTf) { // Term does not appear in chunk so it has no contribution continue; } let chunkIdf = idfCache.get(term); if (typeof chunkIdf !== 'number') { chunkIdf = this.computeIdf(term); idfCache.set(term, chunkIdf); } const chunkTfidf = chunkTf * chunkIdf; sum += chunkTfidf * termTfidf; } return sum; } private computeEmbedding(input: string): SparseEmbedding { const tf = TfIdfCalculator.termFrequencies(input); return this.computeTfidf(tf); } private computeIdf(term: string): number { const chunkOccurrences = this.chunkOccurrences.get(term) ?? 0; return chunkOccurrences > 0 ? Math.log((this.chunkCount + 1) / chunkOccurrences) : 0; } private computeTfidf(termFrequencies: TermFrequencies): SparseEmbedding { const embedding = Object.create(null); for (const [word, occurrences] of termFrequencies) { const idf = this.computeIdf(word); if (idf > 0) { embedding[word] = occurrences * idf; } } return embedding; } } /** * Normalize the scores to be between 0 and 1 and sort them decending. * @param scores array of scores from {@link TfIdfCalculator.calculateScores} * @returns normalized scores */ export function normalizeTfIdfScores(scores: TfIdfScore[]): NormalizedTfIdfScore[] { // copy of scores const result = scores.slice(0) as { score: number }[]; // sort descending result.sort((a, b) => b.score - a.score); // normalize const max = result[0]?.score ?? 0; if (max > 0) { for (const score of result) { score.score /= max; } } return result as TfIdfScore[]; }
src/vs/base/common/tfIdf.ts
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.0010118675418198109, 0.000203582807444036, 0.00016600015806034207, 0.00016921653877943754, 0.00016501217032782733 ]
{ "id": 8, "code_window": [ " - ${{ if eq(parameters.VSCODE_BUILD_WIN32, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_win32_x64_cli\n" ], "labels": [ "keep", "keep", "keep", "add" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}" ], "file_path": "build/azure-pipelines/win32/cli-build-win32.yml", "type": "add", "edit_start_line_idx": 78 }
parameters: - name: VSCODE_QUALITY type: string - name: VSCODE_BUILD_MACOS type: boolean default: false - name: VSCODE_BUILD_MACOS_ARM64 type: boolean default: false - name: VSCODE_CHECK_ONLY type: boolean default: false steps: - task: NodeTool@0 inputs: versionSource: fromFile versionFilePath: .nvmrc nodejsMirror: https://github.com/joaomoreno/node-mirror/releases/download - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - template: ../cli/cli-apply-patches.yml - task: Npm@1 displayName: Download openssl prebuilt inputs: command: custom customCommand: pack @vscode-internal/[email protected] customRegistry: useFeed customFeed: "Monaco/openssl-prebuilt" workingDir: $(Build.ArtifactStagingDirectory) - script: | set -e mkdir $(Build.ArtifactStagingDirectory)/openssl tar -xvzf $(Build.ArtifactStagingDirectory)/vscode-internal-openssl-prebuilt-0.0.11.tgz --strip-components=1 --directory=$(Build.ArtifactStagingDirectory)/openssl displayName: Extract openssl prebuilt - template: ../cli/install-rust-posix.yml parameters: targets: - ${{ if eq(parameters.VSCODE_BUILD_MACOS, true) }}: - x86_64-apple-darwin - ${{ if eq(parameters.VSCODE_BUILD_MACOS_ARM64, true) }}: - aarch64-apple-darwin - ${{ if eq(parameters.VSCODE_BUILD_MACOS, true) }}: - template: ../cli/cli-compile.yml parameters: VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_CLI_TARGET: x86_64-apple-darwin VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_darwin_x64_cli VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }} VSCODE_CLI_ENV: OPENSSL_LIB_DIR: $(Build.ArtifactStagingDirectory)/openssl/x64-osx/lib OPENSSL_INCLUDE_DIR: $(Build.ArtifactStagingDirectory)/openssl/x64-osx/include - ${{ if eq(parameters.VSCODE_BUILD_MACOS_ARM64, true) }}: - template: ../cli/cli-compile.yml parameters: VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_CLI_TARGET: aarch64-apple-darwin VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_darwin_arm64_cli VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }} VSCODE_CLI_ENV: OPENSSL_LIB_DIR: $(Build.ArtifactStagingDirectory)/openssl/arm64-osx/lib OPENSSL_INCLUDE_DIR: $(Build.ArtifactStagingDirectory)/openssl/arm64-osx/include - ${{ if eq(parameters.VSCODE_BUILD_MACOS, true) }}: - template: ../cli/cli-publish.yml parameters: VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_darwin_x64_cli - ${{ if eq(parameters.VSCODE_BUILD_MACOS_ARM64, true) }}: - template: ../cli/cli-publish.yml parameters: VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_darwin_arm64_cli
build/azure-pipelines/darwin/cli-build-darwin.yml
1
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.5795077085494995, 0.1316620111465454, 0.0001674297236604616, 0.005025199614465237, 0.19985686242580414 ]
{ "id": 8, "code_window": [ " - ${{ if eq(parameters.VSCODE_BUILD_WIN32, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_win32_x64_cli\n" ], "labels": [ "keep", "keep", "keep", "add" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}" ], "file_path": "build/azure-pipelines/win32/cli-build-win32.yml", "type": "add", "edit_start_line_idx": 78 }
parameters: - name: VSCODE_CLI_ARTIFACTS type: object default: [] steps: - task: AzureKeyVault@1 displayName: "Azure Key Vault: Get Secrets" inputs: azureSubscription: "vscode-builds-subscription" KeyVaultName: vscode-build-secrets SecretsFilter: "ESRP-PKI,esrp-aad-username,esrp-aad-password" - task: UseDotNet@2 inputs: version: 6.x - task: EsrpClientTool@1 continueOnError: true displayName: Download ESRPClient - ${{ each target in parameters.VSCODE_CLI_ARTIFACTS }}: - task: DownloadPipelineArtifact@2 displayName: Download ${{ target }} inputs: artifact: ${{ target }} path: $(Build.ArtifactStagingDirectory)/pkg/${{ target }} - script: node build/azure-pipelines/common/sign $(Agent.ToolsDirectory)/esrpclient/*/*/net6.0/esrpcli.dll sign-darwin $(ESRP-PKI) $(esrp-aad-username) $(esrp-aad-password) $(Build.ArtifactStagingDirectory)/pkg "*.zip" displayName: Codesign - script: node build/azure-pipelines/common/sign $(Agent.ToolsDirectory)/esrpclient/*/*/net6.0/esrpcli.dll notarize-darwin $(ESRP-PKI) $(esrp-aad-username) $(esrp-aad-password) $(Build.ArtifactStagingDirectory)/pkg "*.zip" displayName: Notarize - ${{ each target in parameters.VSCODE_CLI_ARTIFACTS }}: - script: | set -e ASSET_ID=$(echo "${{ target }}" | sed "s/unsigned_//") mv $(Build.ArtifactStagingDirectory)/pkg/${{ target }}/${{ target }}.zip $(Build.ArtifactStagingDirectory)/pkg/${{ target }}/$ASSET_ID.zip echo "##vso[task.setvariable variable=ASSET_ID]$ASSET_ID" displayName: Set asset id variable - publish: $(Build.ArtifactStagingDirectory)/pkg/${{ target }}/$(ASSET_ID).zip displayName: Publish signed artifact with ID $(ASSET_ID) artifact: $(ASSET_ID)
build/azure-pipelines/cli/cli-darwin-sign.yml
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.012887042947113514, 0.003886160906404257, 0.00016787172353360802, 0.001031234860420227, 0.004864608868956566 ]
{ "id": 8, "code_window": [ " - ${{ if eq(parameters.VSCODE_BUILD_WIN32, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_win32_x64_cli\n" ], "labels": [ "keep", "keep", "keep", "add" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}" ], "file_path": "build/azure-pipelines/win32/cli-build-win32.yml", "type": "add", "edit_start_line_idx": 78 }
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Security-Policy" content=" default-src 'none'; child-src 'self' data: blob:; script-src 'self' 'unsafe-eval' 'sha256-75NYUUvf+5++1WbfCZOV3PSWxBhONpaxwx+mkOFRv/Y=' https:; connect-src 'self' https: wss: http://localhost:* http://127.0.0.1:* ws://localhost:* ws://127.0.0.1:*;"/> </head> <body> <script> (function () { const searchParams = new URL(document.location.href).searchParams; const vscodeWebWorkerExtHostId = searchParams.get('vscodeWebWorkerExtHostId') || ''; const name = searchParams.get('debugged') ? 'DebugWorkerExtensionHost' : 'WorkerExtensionHost'; const parentOrigin = searchParams.get('parentOrigin') || window.origin; const salt = searchParams.get('salt'); (async function () { const hostnameValidationMarker = 'v--'; const hostname = location.hostname; if (!hostname.startsWith(hostnameValidationMarker)) { // validation not requested return start(); } if (!crypto.subtle) { // cannot validate, not running in a secure context return sendError(new Error(`Cannot validate in current context!`)); } // Here the `parentOriginHash()` function from `src/vs/base/browser/iframe.ts` is inlined // compute a sha-256 composed of `parentOrigin` and `salt` converted to base 32 /** @type {string} */ let parentOriginHash; try { const strData = JSON.stringify({ parentOrigin, salt }); const encoder = new TextEncoder(); const arrData = encoder.encode(strData); const hash = await crypto.subtle.digest('sha-256', arrData); const hashArray = Array.from(new Uint8Array(hash)); const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); // sha256 has 256 bits, so we need at most ceil(lg(2^256-1)/lg(32)) = 52 chars to represent it in base 32 parentOriginHash = BigInt(`0x${hashHex}`).toString(32).padStart(52, '0'); } catch (err) { return sendError(err instanceof Error ? err : new Error(String(err))); } const requiredSubdomain = `${hostnameValidationMarker}${parentOriginHash}.`; if (hostname.substring(0, requiredSubdomain.length) === requiredSubdomain) { // validation succeeded! return start(); } return sendError(new Error(`Expected '${requiredSubdomain}' as subdomain!`)); })(); function sendError(error) { window.parent.postMessage({ vscodeWebWorkerExtHostId, error: { name: error ? error.name : '', message: error ? error.message : '', stack: error ? error.stack : [] } }, '*'); } function start() { try { let workerUrl = '../../../../base/worker/workerMain.js'; if (globalThis.crossOriginIsolated) { workerUrl += '?vscode-coi=2'; // COEP } const worker = new Worker(workerUrl, { name }); worker.postMessage('vs/workbench/api/worker/extensionHostWorker'); const nestedWorkers = new Map(); worker.onmessage = (event) => { const { data } = event; if (data?.type === '_newWorker') { const { id, port, url, options } = data; const newWorker = new Worker(url, options); newWorker.postMessage(port, [port]); newWorker.onerror = console.error.bind(console); nestedWorkers.set(id, newWorker); } else if (data?.type === '_terminateWorker') { const { id } = data; if (nestedWorkers.has(id)) { nestedWorkers.get(id).terminate(); nestedWorkers.delete(id); } } else { worker.onerror = console.error.bind(console); window.parent.postMessage({ vscodeWebWorkerExtHostId, data }, parentOrigin, [data]); } }; worker.onerror = (event) => { console.error(event.message, event.error); sendError(event.error); }; self.onmessage = (event) => { if (event.origin !== parentOrigin) { return; } worker.postMessage(event.data, event.ports); }; } catch (err) { console.error(err); sendError(err); } } })(); </script> </body> </html>
src/vs/workbench/services/extensions/worker/webWorkerExtensionHostIframe.html
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.00024501996813341975, 0.000173406268004328, 0.00016448443057015538, 0.00016779618454165757, 0.000020732082703034393 ]
{ "id": 8, "code_window": [ " - ${{ if eq(parameters.VSCODE_BUILD_WIN32, true) }}:\n", " - template: ../cli/cli-publish.yml\n", " parameters:\n", " VSCODE_CLI_ARTIFACT: unsigned_vscode_cli_win32_x64_cli\n" ], "labels": [ "keep", "keep", "keep", "add" ], "after_edit": [ " VSCODE_CHECK_ONLY: ${{ parameters.VSCODE_CHECK_ONLY }}" ], "file_path": "build/azure-pipelines/win32/cli-build-win32.yml", "type": "add", "edit_start_line_idx": 78 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { RequestType, Connection } from 'vscode-languageserver'; import { RuntimeEnvironment } from './htmlServer'; export namespace FsStatRequest { export const type: RequestType<string, FileStat, any> = new RequestType('fs/stat'); } export namespace FsReadDirRequest { export const type: RequestType<string, [string, FileType][], any> = new RequestType('fs/readDir'); } export enum FileType { /** * The file type is unknown. */ Unknown = 0, /** * A regular file. */ File = 1, /** * A directory. */ Directory = 2, /** * A symbolic link to a file. */ SymbolicLink = 64 } export interface FileStat { /** * The type of the file, e.g. is a regular file, a directory, or symbolic link * to a file. */ type: FileType; /** * The creation timestamp in milliseconds elapsed since January 1, 1970 00:00:00 UTC. */ ctime: number; /** * The modification timestamp in milliseconds elapsed since January 1, 1970 00:00:00 UTC. */ mtime: number; /** * The size in bytes. */ size: number; } export interface FileSystemProvider { stat(uri: string): Promise<FileStat>; readDirectory(uri: string): Promise<[string, FileType][]>; } export function getFileSystemProvider(handledSchemas: string[], connection: Connection, runtime: RuntimeEnvironment): FileSystemProvider { const fileFs = runtime.fileFs && handledSchemas.indexOf('file') !== -1 ? runtime.fileFs : undefined; return { async stat(uri: string): Promise<FileStat> { if (fileFs && uri.startsWith('file:')) { return fileFs.stat(uri); } const res = await connection.sendRequest(FsStatRequest.type, uri.toString()); return res; }, readDirectory(uri: string): Promise<[string, FileType][]> { if (fileFs && uri.startsWith('file:')) { return fileFs.readDirectory(uri); } return connection.sendRequest(FsReadDirRequest.type, uri.toString()); } }; }
extensions/html-language-features/server/src/requests.ts
0
https://github.com/microsoft/vscode/commit/7e2981e8a6729f33a950a6b18dac03a14d1ad24a
[ 0.00019115606846753508, 0.00017203798051923513, 0.00016483863873872906, 0.00016930402489379048, 0.000007635409929207526 ]
{ "id": 0, "code_window": [ " displayName: Generate SBOM (client)\n", " inputs:\n", " BuildDropPath: $(agent.builddirectory)/VSCode-darwin-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code\n", "\n", " - publish: $(agent.builddirectory)/VSCode-darwin-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (client)\n", " artifact: $(ARTIFACT_PREFIX)sbom_client_darwin_$(VSCODE_ARCH)_sbom\n", "\n", " - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0\n", " displayName: Generate SBOM (server)\n", " inputs:\n", " BuildDropPath: $(agent.builddirectory)/vscode-server-darwin-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code Server\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "build/azure-pipelines/darwin/product-build-darwin.yml", "type": "replace", "edit_start_line_idx": 214 }
parameters: - name: VSCODE_QUALITY type: string - name: VSCODE_CIBUILD type: boolean - name: VSCODE_RUN_UNIT_TESTS type: boolean - name: VSCODE_RUN_INTEGRATION_TESTS type: boolean - name: VSCODE_RUN_SMOKE_TESTS type: boolean - name: VSCODE_ARCH type: string steps: - ${{ if eq(parameters.VSCODE_QUALITY, 'oss') }}: - checkout: self fetchDepth: 1 retryCountOnTaskFailure: 3 - task: NodeTool@0 inputs: versionSpec: "16.x" - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - template: ../distro/download-distro.yml - task: AzureKeyVault@1 displayName: "Azure Key Vault: Get Secrets" inputs: azureSubscription: "vscode-builds-subscription" KeyVaultName: vscode-build-secrets SecretsFilter: "github-distro-mixin-password,ESRP-PKI,esrp-aad-username,esrp-aad-password" - task: DownloadPipelineArtifact@2 inputs: artifact: Compilation path: $(Build.ArtifactStagingDirectory) displayName: Download compilation output - script: tar -xzf $(Build.ArtifactStagingDirectory)/compilation.tar.gz displayName: Extract compilation output - script: | set -e # Start X server /etc/init.d/xvfb start # Start dbus session DBUS_LAUNCH_RESULT=$(sudo dbus-daemon --config-file=/usr/share/dbus-1/system.conf --print-address) echo "##vso[task.setvariable variable=DBUS_SESSION_BUS_ADDRESS]$DBUS_LAUNCH_RESULT" displayName: Setup system services condition: and(succeeded(), eq(variables['VSCODE_ARCH'], 'x64')) - script: node build/setup-npm-registry.js $NPM_REGISTRY condition: and(succeeded(), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM Registry - script: mkdir -p .build && node build/azure-pipelines/common/computeNodeModulesCacheKey.js linux $VSCODE_ARCH > .build/yarnlockhash displayName: Prepare node_modules cache key - task: Cache@2 inputs: key: '"node_modules" | .build/yarnlockhash' path: .build/node_modules_cache cacheHitVar: NODE_MODULES_RESTORED displayName: Restore node_modules cache - script: tar -xzf .build/node_modules_cache/cache.tgz condition: and(succeeded(), eq(variables.NODE_MODULES_RESTORED, 'true')) displayName: Extract node_modules cache - script: | set -e npm config set registry "$NPM_REGISTRY" --location=project npm config set always-auth=true --location=project yarn config set registry "$NPM_REGISTRY" condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM & Yarn - task: npmAuthenticate@0 inputs: workingFile: .npmrc condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), ne(variables['NPM_REGISTRY'], 'none')) displayName: Setup NPM Authentication # TODO@joaomoreno TODO@deepak1556 this should be part of the base image - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - script: | sudo apt-get update && sudo apt-get install -y ca-certificates curl gnupg sudo mkdir -m 0755 -p /etc/apt/keyrings curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg echo "deb [arch="$(dpkg --print-architecture)" signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu "$(. /etc/os-release && echo "$VERSION_CODENAME")" stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null sudo apt update && sudo apt install -y docker-ce-cli displayName: Install Docker client condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - ${{ if and(ne(parameters.VSCODE_QUALITY, 'oss'), or(eq(parameters.VSCODE_ARCH, 'x64'), eq(parameters.VSCODE_ARCH, 'arm64'))) }}: - task: Docker@1 displayName: "Pull Docker image" inputs: azureSubscriptionEndpoint: "vscode-builds-subscription" azureContainerRegistry: vscodehub.azurecr.io command: "Run an image" imageName: vscode-linux-build-agent:centos7-devtoolset8-$(VSCODE_ARCH) containerCommand: uname condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - ${{ if and(ne(parameters.VSCODE_QUALITY, 'oss'), eq(parameters.VSCODE_ARCH, 'arm64')) }}: - script: docker run --rm --privileged multiarch/qemu-user-static --reset -p yes displayName: Register Docker QEMU condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), eq(variables['VSCODE_ARCH'], 'arm64')) - script: | set -e for i in {1..5}; do # try 5 times yarn --cwd build --frozen-lockfile --check-files && break if [ $i -eq 3 ]; then echo "Yarn failed too many times" >&2 exit 1 fi echo "Yarn failed $i, trying again..." done if [ -z "$CC" ] || [ -z "$CXX" ]; then # Download clang based on chromium revision used by vscode curl -s https://raw.githubusercontent.com/chromium/chromium/108.0.5359.215/tools/clang/scripts/update.py | python - --output-dir=$PWD/.build/CR_Clang --host-os=linux # Download libcxx headers and objects from upstream electron releases DEBUG=libcxx-fetcher \ VSCODE_LIBCXX_OBJECTS_DIR=$PWD/.build/libcxx-objects \ VSCODE_LIBCXX_HEADERS_DIR=$PWD/.build/libcxx_headers \ VSCODE_LIBCXXABI_HEADERS_DIR=$PWD/.build/libcxxabi_headers \ VSCODE_ARCH="$(NPM_ARCH)" \ node build/linux/libcxx-fetcher.js # Set compiler toolchain # Flags for the client build are based on # https://source.chromium.org/chromium/chromium/src/+/refs/tags/108.0.5359.215:build/config/arm.gni # https://source.chromium.org/chromium/chromium/src/+/refs/tags/108.0.5359.215:build/config/compiler/BUILD.gn # https://source.chromium.org/chromium/chromium/src/+/refs/tags/108.0.5359.215:build/config/c++/BUILD.gn export CC=$PWD/.build/CR_Clang/bin/clang export CXX=$PWD/.build/CR_Clang/bin/clang++ export CXXFLAGS="-nostdinc++ -D__NO_INLINE__ -I$PWD/.build/libcxx_headers -isystem$PWD/.build/libcxx_headers/include -isystem$PWD/.build/libcxxabi_headers/include -fPIC -flto=thin -fsplit-lto-unit -D_LIBCPP_ABI_NAMESPACE=Cr" export LDFLAGS="-stdlib=libc++ -fuse-ld=lld -flto=thin -L$PWD/.build/libcxx-objects -lc++abi -Wl,--lto-O0" export VSCODE_REMOTE_CC=$(which gcc) export VSCODE_REMOTE_CXX=$(which g++) fi for i in {1..5}; do # try 5 times yarn --frozen-lockfile --check-files && break if [ $i -eq 3 ]; then echo "Yarn failed too many times" >&2 exit 1 fi echo "Yarn failed $i, trying again..." done env: npm_config_arch: $(NPM_ARCH) ELECTRON_SKIP_BINARY_DOWNLOAD: 1 PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1 GITHUB_TOKEN: "$(github-distro-mixin-password)" ${{ if and(ne(parameters.VSCODE_QUALITY, 'oss'), or(eq(parameters.VSCODE_ARCH, 'x64'), eq(parameters.VSCODE_ARCH, 'arm64'))) }}: VSCODE_REMOTE_DEPENDENCIES_CONTAINER_NAME: vscodehub.azurecr.io/vscode-linux-build-agent:centos7-devtoolset8-$(VSCODE_ARCH) displayName: Install dependencies condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - script: node build/azure-pipelines/distro/mixin-npm condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) displayName: Mixin distro node modules - script: | set -e node build/azure-pipelines/common/listNodeModules.js .build/node_modules_list.txt mkdir -p .build/node_modules_cache tar -czf .build/node_modules_cache/cache.tgz --files-from .build/node_modules_list.txt condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) displayName: Create node_modules archive - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - script: node build/azure-pipelines/distro/mixin-quality displayName: Mixin distro quality - template: ../common/install-builtin-extensions.yml - ${{ if ne(parameters.VSCODE_QUALITY, 'oss') }}: - script: | set -e yarn gulp vscode-linux-$(VSCODE_ARCH)-min-ci ARCHIVE_PATH=".build/linux/client/code-${{ parameters.VSCODE_QUALITY }}-$(VSCODE_ARCH)-$(date +%s).tar.gz" mkdir -p $(dirname $ARCHIVE_PATH) tar -czf $ARCHIVE_PATH -C .. VSCode-linux-$(VSCODE_ARCH) echo "##vso[task.setvariable variable=CLIENT_PATH]$ARCHIVE_PATH" env: GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Build client - script: | set -e yarn gulp vscode-reh-linux-$(VSCODE_ARCH)-min-ci mv ../vscode-reh-linux-$(VSCODE_ARCH) ../vscode-server-linux-$(VSCODE_ARCH) # TODO@joaomoreno ARCHIVE_PATH=".build/linux/server/vscode-server-linux-$(VSCODE_ARCH).tar.gz" mkdir -p $(dirname $ARCHIVE_PATH) tar --owner=0 --group=0 -czf $ARCHIVE_PATH -C .. vscode-server-linux-$(VSCODE_ARCH) echo "##vso[task.setvariable variable=SERVER_PATH]$ARCHIVE_PATH" env: GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Build server - script: | set -e yarn gulp vscode-reh-web-linux-$(VSCODE_ARCH)-min-ci mv ../vscode-reh-web-linux-$(VSCODE_ARCH) ../vscode-server-linux-$(VSCODE_ARCH)-web # TODO@joaomoreno ARCHIVE_PATH=".build/linux/web/vscode-server-linux-$(VSCODE_ARCH)-web.tar.gz" mkdir -p $(dirname $ARCHIVE_PATH) tar --owner=0 --group=0 -czf $ARCHIVE_PATH -C .. vscode-server-linux-$(VSCODE_ARCH)-web echo "##vso[task.setvariable variable=WEB_PATH]$ARCHIVE_PATH" env: GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Build server (web) - ${{ else }}: - script: yarn gulp "transpile-client-swc" "transpile-extensions" env: GITHUB_TOKEN: "$(github-distro-mixin-password)" displayName: Transpile - ${{ if or(eq(parameters.VSCODE_RUN_UNIT_TESTS, true), eq(parameters.VSCODE_RUN_INTEGRATION_TESTS, true), eq(parameters.VSCODE_RUN_SMOKE_TESTS, true)) }}: - template: product-build-linux-test.yml parameters: VSCODE_QUALITY: ${{ parameters.VSCODE_QUALITY }} VSCODE_RUN_UNIT_TESTS: ${{ parameters.VSCODE_RUN_UNIT_TESTS }} VSCODE_RUN_INTEGRATION_TESTS: ${{ parameters.VSCODE_RUN_INTEGRATION_TESTS }} VSCODE_RUN_SMOKE_TESTS: ${{ parameters.VSCODE_RUN_SMOKE_TESTS }} - ${{ if and(ne(parameters.VSCODE_CIBUILD, true), ne(parameters.VSCODE_QUALITY, 'oss')) }}: - task: DownloadPipelineArtifact@2 inputs: artifact: $(ARTIFACT_PREFIX)vscode_cli_linux_$(VSCODE_ARCH)_cli patterns: "**" path: $(Build.ArtifactStagingDirectory)/cli displayName: Download VS Code CLI - script: | set -e tar -xzvf $(Build.ArtifactStagingDirectory)/cli/*.tar.gz -C $(Build.ArtifactStagingDirectory)/cli CLI_APP_NAME=$(node -p "require(\"$(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)/resources/app/product.json\").tunnelApplicationName") APP_NAME=$(node -p "require(\"$(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)/resources/app/product.json\").applicationName") mv $(Build.ArtifactStagingDirectory)/cli/$APP_NAME $(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)/bin/$CLI_APP_NAME displayName: Make CLI executable - script: | set -e yarn gulp "vscode-linux-$(VSCODE_ARCH)-build-deb" echo "##vso[task.setvariable variable=DEB_PATH]$(ls .build/linux/deb/*/deb/*.deb)" displayName: Build deb package - script: | set -e yarn gulp "vscode-linux-$(VSCODE_ARCH)-build-rpm" echo "##vso[task.setvariable variable=RPM_PATH]$(ls .build/linux/rpm/*/*.rpm)" displayName: Build rpm package - script: | set -e yarn gulp "vscode-linux-$(VSCODE_ARCH)-prepare-snap" ARCHIVE_PATH=".build/linux/snap-tarball/snap-$(VSCODE_ARCH).tar.gz" mkdir -p $(dirname $ARCHIVE_PATH) tar -czf $ARCHIVE_PATH -C .build/linux snap echo "##vso[task.setvariable variable=SNAP_PATH]$ARCHIVE_PATH" displayName: Prepare snap package - task: UseDotNet@2 inputs: version: 6.x - task: EsrpClientTool@1 continueOnError: true displayName: Download ESRPClient - script: node build/azure-pipelines/common/sign $(Agent.ToolsDirectory)/esrpclient/*/*/net6.0/esrpcli.dll rpm $(ESRP-PKI) $(esrp-aad-username) $(esrp-aad-password) .build/linux/rpm '*.rpm' displayName: Codesign rpm - script: echo "##vso[task.setvariable variable=ARTIFACT_PREFIX]attempt$(System.JobAttempt)_" condition: and(succeededOrFailed(), notIn(variables['Agent.JobStatus'], 'Succeeded', 'SucceededWithIssues')) displayName: Generate artifact prefix - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0 displayName: Generate SBOM (client) inputs: BuildDropPath: $(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH) PackageName: Visual Studio Code - publish: $(agent.builddirectory)/VSCode-linux-$(VSCODE_ARCH)/_manifest displayName: Publish SBOM (client) artifact: $(ARTIFACT_PREFIX)sbom_vscode_client_linux_$(VSCODE_ARCH) - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0 displayName: Generate SBOM (server) inputs: BuildDropPath: $(agent.builddirectory)/vscode-server-linux-$(VSCODE_ARCH) PackageName: Visual Studio Code Server - publish: $(agent.builddirectory)/vscode-server-linux-$(VSCODE_ARCH)/_manifest displayName: Publish SBOM (server) artifact: $(ARTIFACT_PREFIX)sbom_vscode_server_linux_$(VSCODE_ARCH) - publish: $(CLIENT_PATH) artifact: $(ARTIFACT_PREFIX)vscode_client_linux_$(VSCODE_ARCH)_archive-unsigned condition: and(succeededOrFailed(), ne(variables['CLIENT_PATH'], '')) displayName: Publish client archive - publish: $(SERVER_PATH) artifact: $(ARTIFACT_PREFIX)vscode_server_linux_$(VSCODE_ARCH)_archive-unsigned condition: and(succeededOrFailed(), ne(variables['SERVER_PATH'], '')) displayName: Publish server archive - publish: $(WEB_PATH) artifact: $(ARTIFACT_PREFIX)vscode_web_linux_$(VSCODE_ARCH)_archive-unsigned condition: and(succeededOrFailed(), ne(variables['WEB_PATH'], '')) displayName: Publish web server archive - publish: $(DEB_PATH) artifact: $(ARTIFACT_PREFIX)vscode_client_linux_$(VSCODE_ARCH)_deb-package condition: and(succeededOrFailed(), ne(variables['DEB_PATH'], '')) displayName: Publish deb package - publish: $(RPM_PATH) artifact: $(ARTIFACT_PREFIX)vscode_client_linux_$(VSCODE_ARCH)_rpm-package condition: and(succeededOrFailed(), ne(variables['RPM_PATH'], '')) displayName: Publish rpm package - publish: $(SNAP_PATH) artifact: $(ARTIFACT_PREFIX)snap-$(VSCODE_ARCH) condition: and(succeededOrFailed(), ne(variables['SNAP_PATH'], '')) displayName: Publish snap pre-package
build/azure-pipelines/linux/product-build-linux.yml
1
https://github.com/microsoft/vscode/commit/6bad769697ec3e4ad65287d9345624328377fdd5
[ 0.38121429085731506, 0.013309497386217117, 0.00016262626741081476, 0.0001795307034626603, 0.06448478251695633 ]
{ "id": 0, "code_window": [ " displayName: Generate SBOM (client)\n", " inputs:\n", " BuildDropPath: $(agent.builddirectory)/VSCode-darwin-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code\n", "\n", " - publish: $(agent.builddirectory)/VSCode-darwin-$(VSCODE_ARCH)/_manifest\n", " displayName: Publish SBOM (client)\n", " artifact: $(ARTIFACT_PREFIX)sbom_client_darwin_$(VSCODE_ARCH)_sbom\n", "\n", " - task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0\n", " displayName: Generate SBOM (server)\n", " inputs:\n", " BuildDropPath: $(agent.builddirectory)/vscode-server-darwin-$(VSCODE_ARCH)\n", " PackageName: Visual Studio Code Server\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "build/azure-pipelines/darwin/product-build-darwin.yml", "type": "replace", "edit_start_line_idx": 214 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { isNonEmptyArray } from 'vs/base/common/arrays'; import { ExtensionIdentifier, IExtensionDescription } from 'vs/platform/extensions/common/extensions'; import { ILogService } from 'vs/platform/log/common/log'; import { IProductService } from 'vs/platform/product/common/productService'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { ApiProposalName, allApiProposals } from 'vs/workbench/services/extensions/common/extensionsApiProposals'; export class ExtensionsProposedApi { private readonly _envEnablesProposedApiForAll: boolean; private readonly _envEnabledExtensions: Set<string>; private readonly _productEnabledExtensions: Map<string, string[]>; constructor( @ILogService private readonly _logService: ILogService, @IWorkbenchEnvironmentService private readonly _environmentService: IWorkbenchEnvironmentService, @IProductService productService: IProductService ) { this._envEnabledExtensions = new Set((_environmentService.extensionEnabledProposedApi ?? []).map(id => ExtensionIdentifier.toKey(id))); this._envEnablesProposedApiForAll = !_environmentService.isBuilt || // always allow proposed API when running out of sources (_environmentService.isExtensionDevelopment && productService.quality !== 'stable') || // do not allow proposed API against stable builds when developing an extension (this._envEnabledExtensions.size === 0 && Array.isArray(_environmentService.extensionEnabledProposedApi)); // always allow proposed API if --enable-proposed-api is provided without extension ID this._productEnabledExtensions = new Map<string, ApiProposalName[]>(); // NEW world - product.json spells out what proposals each extension can use if (productService.extensionEnabledApiProposals) { for (const [k, value] of Object.entries(productService.extensionEnabledApiProposals)) { const key = ExtensionIdentifier.toKey(k); const proposalNames = value.filter(name => { if (!allApiProposals[<ApiProposalName>name]) { _logService.warn(`Via 'product.json#extensionEnabledApiProposals' extension '${key}' wants API proposal '${name}' but that proposal DOES NOT EXIST. Likely, the proposal has been finalized (check 'vscode.d.ts') or was abandoned.`); return false; } return true; }); this._productEnabledExtensions.set(key, proposalNames); } } } updateEnabledApiProposals(extensions: IExtensionDescription[]): void { for (const extension of extensions) { this.doUpdateEnabledApiProposals(extension); } } private doUpdateEnabledApiProposals(_extension: IExtensionDescription): void { // this is a trick to make the extension description writeable... type Writeable<T> = { -readonly [P in keyof T]: Writeable<T[P]> }; const extension = <Writeable<IExtensionDescription>>_extension; const key = ExtensionIdentifier.toKey(_extension.identifier); // warn about invalid proposal and remove them from the list if (isNonEmptyArray(extension.enabledApiProposals)) { extension.enabledApiProposals = extension.enabledApiProposals.filter(name => { const result = Boolean(allApiProposals[<ApiProposalName>name]); if (!result) { this._logService.error(`Extension '${key}' wants API proposal '${name}' but that proposal DOES NOT EXIST. Likely, the proposal has been finalized (check 'vscode.d.ts') or was abandoned.`); } return result; }); } if (this._productEnabledExtensions.has(key)) { // NOTE that proposals that are listed in product.json override whatever is declared in the extension // itself. This is needed for us to know what proposals are used "in the wild". Merging product.json-proposals // and extension-proposals would break that. const productEnabledProposals = this._productEnabledExtensions.get(key)!; // check for difference between product.json-declaration and package.json-declaration const productSet = new Set(productEnabledProposals); const extensionSet = new Set(extension.enabledApiProposals); const diff = new Set([...extensionSet].filter(a => !productSet.has(a))); if (diff.size > 0) { this._logService.error(`Extension '${key}' appears in product.json but enables LESS API proposals than the extension wants.\npackage.json (LOSES): ${[...extensionSet].join(', ')}\nproduct.json (WINS): ${[...productSet].join(', ')}`); if (this._environmentService.isExtensionDevelopment) { this._logService.error(`Proceeding with EXTRA proposals (${[...diff].join(', ')}) because extension is in development mode. Still, this EXTENSION WILL BE BROKEN unless product.json is updated.`); productEnabledProposals.push(...diff); } } extension.enabledApiProposals = productEnabledProposals; return; } if (this._envEnablesProposedApiForAll || this._envEnabledExtensions.has(key)) { // proposed API usage is not restricted and allowed just like the extension // has declared it return; } if (!extension.isBuiltin && isNonEmptyArray(extension.enabledApiProposals)) { // restrictive: extension cannot use proposed API in this context and its declaration is nulled this._logService.error(`Extension '${extension.identifier.value} CANNOT USE these API proposals '${extension.enabledApiProposals?.join(', ') || '*'}'. You MUST start in extension development mode or use the --enable-proposed-api command line flag`); extension.enabledApiProposals = []; } } }
src/vs/workbench/services/extensions/common/extensionsProposedApi.ts
0
https://github.com/microsoft/vscode/commit/6bad769697ec3e4ad65287d9345624328377fdd5
[ 0.0001731391967041418, 0.00016917705943342298, 0.0001630318001843989, 0.0001698776613920927, 0.000003257282287449925 ]