hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
sequencelengths 5
5
|
---|---|---|---|---|---|
{
"id": 0,
"code_window": [
" @keydown.enter.exact=\"onNavigate(NavigateDir.NEXT, $event)\"\n",
" @keydown.shift.enter.exact=\"onNavigate(NavigateDir.PREV, $event)\"\n",
" >\n",
" <template v-if=\"intersected\">\n",
" <LazyVirtualCellLinks v-if=\"isLink(column)\" :readonly=\"isUnderLookup\" />\n",
" <LazyVirtualCellHasMany v-else-if=\"isHm(column)\" />\n",
" <LazyVirtualCellManyToMany v-else-if=\"isMm(column)\" />\n",
" <LazyVirtualCellBelongsTo v-else-if=\"isBt(column)\" />\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" <LazyVirtualCellLinks v-if=\"isLink(column)\" />\n"
],
"file_path": "packages/nc-gui/components/smartsheet/VirtualCell.vue",
"type": "replace",
"edit_start_line_idx": 103
} | import { Test } from '@nestjs/testing';
import { PublicDatasExportService } from './public-datas-export.service';
import type { TestingModule } from '@nestjs/testing';
describe('PublicDatasExportService', () => {
let service: PublicDatasExportService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [PublicDatasExportService],
}).compile();
service = module.get<PublicDatasExportService>(PublicDatasExportService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
| packages/nocodb/src/services/public-datas-export.service.spec.ts | 0 | https://github.com/nocodb/nocodb/commit/cfe6c234eee6067a01e9ccf6501d60f8a26513fd | [
0.00017777970060706139,
0.00017765088705345988,
0.00017752205894794315,
0.00017765088705345988,
1.2882082955911756e-7
] |
{
"id": 0,
"code_window": [
" @keydown.enter.exact=\"onNavigate(NavigateDir.NEXT, $event)\"\n",
" @keydown.shift.enter.exact=\"onNavigate(NavigateDir.PREV, $event)\"\n",
" >\n",
" <template v-if=\"intersected\">\n",
" <LazyVirtualCellLinks v-if=\"isLink(column)\" :readonly=\"isUnderLookup\" />\n",
" <LazyVirtualCellHasMany v-else-if=\"isHm(column)\" />\n",
" <LazyVirtualCellManyToMany v-else-if=\"isMm(column)\" />\n",
" <LazyVirtualCellBelongsTo v-else-if=\"isBt(column)\" />\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" <LazyVirtualCellLinks v-if=\"isLink(column)\" />\n"
],
"file_path": "packages/nc-gui/components/smartsheet/VirtualCell.vue",
"type": "replace",
"edit_start_line_idx": 103
} | ---
title: 'Data Sources'
description: 'NocoDB Data-Source sync, access control & re-config'
---
## Overview
`Data Sources` tab includes following functionalities
- Connect/manage external data source
- UI Access Control
- Relations
Note that, currently only one external data source can be added per project.
## Accessing Data Sources
Click `Data Sources` tab in `Project dashboard`

## Sync Metadata
Go to `Data Sources`, click ``Sync Metadata``, you can see your metadata sync status. If it is out of sync, you can sync the schema. See [Sync Schema](/setup-and-usages/sync-schema) for more.

## UI Access Control
Go to `Data Sources`, click ``UI ACL``, you can control the access to each table by roles.

## Relations
Go to `Data Sources`, click ``Relations``, you can see the ERD of your database.

### Junction table names within Relations
- Enable `Show M2M Tables` within `Project Settings` menu
- Double click on `Show Columns` to see additional checkboxes get enabled.
- Enabling which you should be able to see junction tables and their table names.

## Edit external database configuration parameters
Go to `Data Sources`, click ``Edit`` icon, you can re-configure database credentials.
Please make sure database configuration parameters are valid. Any incorrect parameters could lead to schema loss!

## Unlink data source
Go to `Data Sources`, click ``Delete`` against the data source that you wish to un-link.

## Data source visibility
Go to `Data Sources`, toggle ``Radio-button`` against the data source that you wish to hide/un-hide.
 | packages/noco-docs/docs/030.setup-and-usages/240.meta-management.md | 0 | https://github.com/nocodb/nocodb/commit/cfe6c234eee6067a01e9ccf6501d60f8a26513fd | [
0.00017473949992563576,
0.00017080779070965946,
0.00016698904801160097,
0.00017152182408608496,
0.0000026017519303422887
] |
{
"id": 1,
"code_window": [
"import type { ColumnType } from 'nocodb-sdk'\n",
"import { ref } from 'vue'\n",
"import type { Ref } from 'vue'\n",
"import { ActiveCellInj, CellValueInj, ColumnInj, IsUnderLookupInj, inject, useSelectedCellKeyupListener } from '#imports'\n",
"\n",
"const props = defineProps<{\n",
" readonly: boolean\n",
"}>()\n",
"\n",
"const value = inject(CellValueInj, ref(0))\n",
"\n",
"const column = inject(ColumnInj)!\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/nc-gui/components/virtual-cell/Links.vue",
"type": "replace",
"edit_start_line_idx": 7
} | <script setup lang="ts">
import { computed } from '@vue/reactivity'
import type { ColumnType } from 'nocodb-sdk'
import { ref } from 'vue'
import type { Ref } from 'vue'
import { ActiveCellInj, CellValueInj, ColumnInj, IsUnderLookupInj, inject, useSelectedCellKeyupListener } from '#imports'
const props = defineProps<{
readonly: boolean
}>()
const value = inject(CellValueInj, ref(0))
const column = inject(ColumnInj)!
const row = inject(RowInj)!
const reloadRowTrigger = inject(ReloadRowDataHookInj, createEventHook())
const isForm = inject(IsFormInj)
const _readOnly = inject(ReadonlyInj, ref(false))
const readOnly = computed(() => props.readonly || _readOnly.value)
const isLocked = inject(IsLockedInj, ref(false))
const isUnderLookup = inject(IsUnderLookupInj, ref(false))
const colTitle = computed(() => column.value?.title || '')
const listItemsDlg = ref(false)
const childListDlg = ref(false)
const { isUIAllowed } = useRoles()
const { t } = useI18n()
const { state, isNew } = useSmartsheetRowStoreOrThrow()
const { relatedTableMeta, loadRelatedTableMeta, relatedTableDisplayValueProp } = useProvideLTARStore(
column as Ref<Required<ColumnType>>,
row,
isNew,
reloadRowTrigger.trigger,
)
const relatedTableDisplayColumn = computed(
() =>
relatedTableMeta.value?.columns?.find((c: any) => c.title === relatedTableDisplayValueProp.value) as ColumnType | undefined,
)
loadRelatedTableMeta()
const textVal = computed(() => {
if (isForm?.value) {
return state.value?.[colTitle.value]?.length
? `${+state.value?.[colTitle.value]?.length} ${t('msg.recordsLinked')}`
: t('msg.noRecordsLinked')
}
const parsedValue = +value?.value || 0
if (!parsedValue) {
return t('msg.noRecordsLinked')
} else if (parsedValue === 1) {
return `1 ${column.value?.meta?.singular || t('general.link')}`
} else {
return `${parsedValue} ${column.value?.meta?.plural || t('general.links')}`
}
})
const toatlRecordsLinked = computed(() => {
if (isForm?.value) {
return state.value?.[colTitle.value]?.length
}
return +value?.value || 0
})
const onAttachRecord = () => {
childListDlg.value = false
listItemsDlg.value = true
}
const openChildList = () => {
if (readOnly.value) return
if (!isLocked.value) {
childListDlg.value = true
}
}
useSelectedCellKeyupListener(inject(ActiveCellInj, ref(false)), (e: KeyboardEvent) => {
switch (e.key) {
case 'Enter':
if (isLocked.value || listItemsDlg.value) return
childListDlg.value = true
e.stopPropagation()
break
}
})
const localCellValue = computed<any[]>(() => {
if (isNew.value) {
return state?.value?.[column?.value.title as string] ?? []
}
return []
})
const openListDlg = () => {
if (readOnly.value) return
listItemsDlg.value = true
}
</script>
<template>
<div class="flex w-full group items-center nc-links-wrapper" @dblclick.stop="openChildList">
<div class="block flex-shrink truncate">
<component
:is="isLocked || isUnderLookup ? 'span' : 'a'"
v-e="['c:cell:links:modal:open']"
:title="textVal"
class="text-center nc-datatype-link underline-transparent"
:class="{ '!text-gray-300': !textVal }"
@click.stop.prevent="openChildList"
>
{{ textVal }}
</component>
</div>
<div class="flex-grow" />
<div v-if="!isLocked && !isUnderLookup" class="!xs:hidden flex justify-end hidden group-hover:flex items-center">
<MdiPlus
v-if="(!readOnly && isUIAllowed('dataEdit')) || isForm"
class="select-none !text-md text-gray-700 nc-action-icon nc-plus"
@click.stop="openListDlg"
/>
</div>
<LazyVirtualCellComponentsListItems
v-if="listItemsDlg || childListDlg"
v-model="listItemsDlg"
:column="relatedTableDisplayColumn"
/>
<LazyVirtualCellComponentsListChildItems
v-if="listItemsDlg || childListDlg"
v-model="childListDlg"
:items="toatlRecordsLinked"
:column="relatedTableDisplayColumn"
:cell-value="localCellValue"
@attach-record="onAttachRecord"
/>
</div>
</template>
| packages/nc-gui/components/virtual-cell/Links.vue | 1 | https://github.com/nocodb/nocodb/commit/cfe6c234eee6067a01e9ccf6501d60f8a26513fd | [
0.9982858300209045,
0.21818269789218903,
0.00016547848645132035,
0.00018202996579930186,
0.3912326395511627
] |
{
"id": 1,
"code_window": [
"import type { ColumnType } from 'nocodb-sdk'\n",
"import { ref } from 'vue'\n",
"import type { Ref } from 'vue'\n",
"import { ActiveCellInj, CellValueInj, ColumnInj, IsUnderLookupInj, inject, useSelectedCellKeyupListener } from '#imports'\n",
"\n",
"const props = defineProps<{\n",
" readonly: boolean\n",
"}>()\n",
"\n",
"const value = inject(CellValueInj, ref(0))\n",
"\n",
"const column = inject(ColumnInj)!\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/nc-gui/components/virtual-cell/Links.vue",
"type": "replace",
"edit_start_line_idx": 7
} | <script lang="ts" setup>
import { onKeyStroke } from '#imports'
const props = defineProps<{
visible: boolean
entityName: string
onDelete: () => Promise<void>
}>()
const emits = defineEmits(['update:visible'])
const visible = useVModel(props, 'visible', emits)
const isLoading = ref(false)
const onDelete = async () => {
isLoading.value = true
try {
await props.onDelete()
visible.value = false
} catch (e: any) {
console.error(e)
message.error(await extractSdkResponseErrorMsg(e))
} finally {
isLoading.value = false
}
}
onKeyStroke('Escape', () => {
if (visible.value) visible.value = false
})
onKeyStroke('Enter', () => {
if (isLoading.value) return
if (!visible.value) return
onDelete()
})
</script>
<template>
<GeneralModal v-model:visible="visible" size="small" centered>
<div class="flex flex-col p-6">
<div class="flex flex-row pb-2 mb-4 font-medium text-lg border-b-1 border-gray-50 text-gray-800">
{{ $t('general.delete') }} {{ props.entityName }}
</div>
<div class="mb-3 text-gray-800">
{{ $t('msg.areYouSureUWantTo') }}<span class="ml-1">{{ props.entityName.toLowerCase() }}?</span>
</div>
<slot name="entity-preview"></slot>
<div class="flex flex-row gap-x-2 mt-2.5 pt-2.5 justify-end">
<NcButton type="secondary" @click="visible = false">
{{ $t('general.cancel') }}
</NcButton>
<NcButton
key="submit"
type="danger"
html-type="submit"
:loading="isLoading"
data-testid="nc-delete-modal-delete-btn"
@click="onDelete"
>
{{ `${$t('general.delete')} ${props.entityName}` }}
<template #loading>
{{ $t('general.deleting') }}
</template>
</NcButton>
</div>
</div>
</GeneralModal>
</template>
<style lang="scss">
.nc-modal-wrapper {
.ant-modal-content {
@apply !p-0;
}
}
</style>
| packages/nc-gui/components/general/DeleteModal.vue | 0 | https://github.com/nocodb/nocodb/commit/cfe6c234eee6067a01e9ccf6501d60f8a26513fd | [
0.9846996665000916,
0.32061731815338135,
0.00016883602074813098,
0.00017389198183082044,
0.44488993287086487
] |
{
"id": 1,
"code_window": [
"import type { ColumnType } from 'nocodb-sdk'\n",
"import { ref } from 'vue'\n",
"import type { Ref } from 'vue'\n",
"import { ActiveCellInj, CellValueInj, ColumnInj, IsUnderLookupInj, inject, useSelectedCellKeyupListener } from '#imports'\n",
"\n",
"const props = defineProps<{\n",
" readonly: boolean\n",
"}>()\n",
"\n",
"const value = inject(CellValueInj, ref(0))\n",
"\n",
"const column = inject(ColumnInj)!\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/nc-gui/components/virtual-cell/Links.vue",
"type": "replace",
"edit_start_line_idx": 7
} | import axios from 'axios';
import type { IWebhookNotificationAdapter } from 'nc-plugin';
export default class Slack implements IWebhookNotificationAdapter {
public init(): Promise<any> {
return Promise.resolve(undefined);
}
public async sendMessage(text: string, payload: any): Promise<any> {
for (const { webhook_url } of payload?.channels || []) {
try {
return await axios.post(webhook_url, {
text,
});
} catch (e) {
console.log(e);
throw e;
}
}
}
}
| packages/nocodb/src/plugins/slack/Slack.ts | 0 | https://github.com/nocodb/nocodb/commit/cfe6c234eee6067a01e9ccf6501d60f8a26513fd | [
0.00017132288485299796,
0.00016873690765351057,
0.00016728483024053276,
0.00016760302241891623,
0.000001833166948017606
] |
{
"id": 1,
"code_window": [
"import type { ColumnType } from 'nocodb-sdk'\n",
"import { ref } from 'vue'\n",
"import type { Ref } from 'vue'\n",
"import { ActiveCellInj, CellValueInj, ColumnInj, IsUnderLookupInj, inject, useSelectedCellKeyupListener } from '#imports'\n",
"\n",
"const props = defineProps<{\n",
" readonly: boolean\n",
"}>()\n",
"\n",
"const value = inject(CellValueInj, ref(0))\n",
"\n",
"const column = inject(ColumnInj)!\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/nc-gui/components/virtual-cell/Links.vue",
"type": "replace",
"edit_start_line_idx": 7
} | import { test } from '@playwright/test';
import { DashboardPage } from '../../../pages/Dashboard';
import setup, { unsetup } from '../../../setup';
test.describe.skip('Map View', () => {
let dashboard: DashboardPage;
let context: any;
const latitudeInFullDecimalLength = '50.4501000';
const longitudeInFullDecimalLength = '30.5234000';
const latitudeInShortDecimalLength = '50.4501';
const longitudeInShortDecimalLength = '30.5234';
test.beforeEach(async ({ page }) => {
context = await setup({ page, isEmptyProject: false });
dashboard = new DashboardPage(page, context.base);
await dashboard.viewSidebar.changeBetaFeatureToggleValue();
// close 'Team & Auth' tab
await dashboard.closeTab({ title: 'Team & Auth' });
await dashboard.treeView.openTable({ title: 'Actor' });
const grid = dashboard.grid;
await grid.column.create({
title: 'Actors Birthplace',
type: 'GeoData',
});
await grid.column.verify({ title: 'Actors Birthplace', isVisible: true });
await grid.cell.geoData.openSetLocation({
index: 0,
columnHeader: 'Actors Birthplace',
});
await grid.cell.geoData.enterLatLong({
lat: latitudeInShortDecimalLength,
long: longitudeInShortDecimalLength,
});
await grid.cell.geoData.clickSave();
await grid.cell.verifyGeoDataCell({
index: 0,
columnHeader: 'Actors Birthplace',
lat: latitudeInFullDecimalLength,
long: longitudeInFullDecimalLength,
});
});
test.afterEach(async () => {
await unsetup(context);
});
test('shows the marker and opens the expanded form view when clicking on it', async () => {
await dashboard.viewSidebar.createMapView({
title: 'Map 1',
});
// Zoom out
await dashboard.map.zoomOut(8);
await dashboard.map.verifyMarkerCount(1);
await dashboard.map.clickAddRowButton();
await dashboard.expandedForm.fillField({
columnTitle: 'FirstName',
value: 'Mario',
type: 'text',
});
await dashboard.expandedForm.fillField({
columnTitle: 'LastName',
value: 'Ali',
type: 'text',
});
await dashboard.expandedForm.fillField({
columnTitle: 'Actors Birthplace',
value: '12, 34',
type: 'geodata',
});
await dashboard.expandedForm.save();
await dashboard.map.verifyMarkerCount(2);
await dashboard.map.clickMarker('12', '34');
await dashboard.expandedForm.clickDeleteRow();
await dashboard.map.verifyMarkerCount(1);
});
});
| tests/playwright/tests/db/views/viewMap.spec.ts | 0 | https://github.com/nocodb/nocodb/commit/cfe6c234eee6067a01e9ccf6501d60f8a26513fd | [
0.00017340602062176913,
0.00017032581672538072,
0.0001669984485488385,
0.000170236497069709,
0.000002182087655455689
] |
{
"id": 2,
"code_window": [
"const reloadRowTrigger = inject(ReloadRowDataHookInj, createEventHook())\n",
"\n",
"const isForm = inject(IsFormInj)\n",
"\n",
"const _readOnly = inject(ReadonlyInj, ref(false))\n",
"\n",
"const readOnly = computed(() => props.readonly || _readOnly.value)\n",
"\n",
"const isLocked = inject(IsLockedInj, ref(false))\n",
"\n",
"const isUnderLookup = inject(IsUnderLookupInj, ref(false))\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const readOnly = inject(ReadonlyInj, ref(false))\n"
],
"file_path": "packages/nc-gui/components/virtual-cell/Links.vue",
"type": "replace",
"edit_start_line_idx": 21
} | <script setup lang="ts">
import { computed } from '@vue/reactivity'
import type { ColumnType } from 'nocodb-sdk'
import { ref } from 'vue'
import type { Ref } from 'vue'
import { ActiveCellInj, CellValueInj, ColumnInj, IsUnderLookupInj, inject, useSelectedCellKeyupListener } from '#imports'
const props = defineProps<{
readonly: boolean
}>()
const value = inject(CellValueInj, ref(0))
const column = inject(ColumnInj)!
const row = inject(RowInj)!
const reloadRowTrigger = inject(ReloadRowDataHookInj, createEventHook())
const isForm = inject(IsFormInj)
const _readOnly = inject(ReadonlyInj, ref(false))
const readOnly = computed(() => props.readonly || _readOnly.value)
const isLocked = inject(IsLockedInj, ref(false))
const isUnderLookup = inject(IsUnderLookupInj, ref(false))
const colTitle = computed(() => column.value?.title || '')
const listItemsDlg = ref(false)
const childListDlg = ref(false)
const { isUIAllowed } = useRoles()
const { t } = useI18n()
const { state, isNew } = useSmartsheetRowStoreOrThrow()
const { relatedTableMeta, loadRelatedTableMeta, relatedTableDisplayValueProp } = useProvideLTARStore(
column as Ref<Required<ColumnType>>,
row,
isNew,
reloadRowTrigger.trigger,
)
const relatedTableDisplayColumn = computed(
() =>
relatedTableMeta.value?.columns?.find((c: any) => c.title === relatedTableDisplayValueProp.value) as ColumnType | undefined,
)
loadRelatedTableMeta()
const textVal = computed(() => {
if (isForm?.value) {
return state.value?.[colTitle.value]?.length
? `${+state.value?.[colTitle.value]?.length} ${t('msg.recordsLinked')}`
: t('msg.noRecordsLinked')
}
const parsedValue = +value?.value || 0
if (!parsedValue) {
return t('msg.noRecordsLinked')
} else if (parsedValue === 1) {
return `1 ${column.value?.meta?.singular || t('general.link')}`
} else {
return `${parsedValue} ${column.value?.meta?.plural || t('general.links')}`
}
})
const toatlRecordsLinked = computed(() => {
if (isForm?.value) {
return state.value?.[colTitle.value]?.length
}
return +value?.value || 0
})
const onAttachRecord = () => {
childListDlg.value = false
listItemsDlg.value = true
}
const openChildList = () => {
if (readOnly.value) return
if (!isLocked.value) {
childListDlg.value = true
}
}
useSelectedCellKeyupListener(inject(ActiveCellInj, ref(false)), (e: KeyboardEvent) => {
switch (e.key) {
case 'Enter':
if (isLocked.value || listItemsDlg.value) return
childListDlg.value = true
e.stopPropagation()
break
}
})
const localCellValue = computed<any[]>(() => {
if (isNew.value) {
return state?.value?.[column?.value.title as string] ?? []
}
return []
})
const openListDlg = () => {
if (readOnly.value) return
listItemsDlg.value = true
}
</script>
<template>
<div class="flex w-full group items-center nc-links-wrapper" @dblclick.stop="openChildList">
<div class="block flex-shrink truncate">
<component
:is="isLocked || isUnderLookup ? 'span' : 'a'"
v-e="['c:cell:links:modal:open']"
:title="textVal"
class="text-center nc-datatype-link underline-transparent"
:class="{ '!text-gray-300': !textVal }"
@click.stop.prevent="openChildList"
>
{{ textVal }}
</component>
</div>
<div class="flex-grow" />
<div v-if="!isLocked && !isUnderLookup" class="!xs:hidden flex justify-end hidden group-hover:flex items-center">
<MdiPlus
v-if="(!readOnly && isUIAllowed('dataEdit')) || isForm"
class="select-none !text-md text-gray-700 nc-action-icon nc-plus"
@click.stop="openListDlg"
/>
</div>
<LazyVirtualCellComponentsListItems
v-if="listItemsDlg || childListDlg"
v-model="listItemsDlg"
:column="relatedTableDisplayColumn"
/>
<LazyVirtualCellComponentsListChildItems
v-if="listItemsDlg || childListDlg"
v-model="childListDlg"
:items="toatlRecordsLinked"
:column="relatedTableDisplayColumn"
:cell-value="localCellValue"
@attach-record="onAttachRecord"
/>
</div>
</template>
| packages/nc-gui/components/virtual-cell/Links.vue | 1 | https://github.com/nocodb/nocodb/commit/cfe6c234eee6067a01e9ccf6501d60f8a26513fd | [
0.9990189075469971,
0.5616408586502075,
0.00017303621280007064,
0.9969327449798584,
0.49485909938812256
] |
{
"id": 2,
"code_window": [
"const reloadRowTrigger = inject(ReloadRowDataHookInj, createEventHook())\n",
"\n",
"const isForm = inject(IsFormInj)\n",
"\n",
"const _readOnly = inject(ReadonlyInj, ref(false))\n",
"\n",
"const readOnly = computed(() => props.readonly || _readOnly.value)\n",
"\n",
"const isLocked = inject(IsLockedInj, ref(false))\n",
"\n",
"const isUnderLookup = inject(IsUnderLookupInj, ref(false))\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const readOnly = inject(ReadonlyInj, ref(false))\n"
],
"file_path": "packages/nc-gui/components/virtual-cell/Links.vue",
"type": "replace",
"edit_start_line_idx": 21
} | ---
title: "Table Operations"
description: "Table Operations: Row, Column, Quick Import, Export & Import"
---
Once you have created a new NocoDB project you can open it, In the browser, the URL would be like `example.com/#/default/<project_id>`.
## Table
### Table Create
On project dashboard, click on `Add new table` button

Provide a name for the table & click `Create Table` button.

After the successful submission, the table will be created and open on a new grid.

New table can also be created by using `+` button on project tile in left sidebar

### Table Rename
Right click on Table name on left sidebar, (OR)
Click on `...` to open `Table context menu`, select `Rename`.
Feed in the changes to the table name & press `Enter`

### Table Duplicate
Right click on Table name on left sidebar, (OR)
Click on `...` to open `Table context menu`, select `Duplicate`

Additionally, you can configure to duplicate
- `Include Data` : toggle this to include/exclude table records
- `Include Views` : toggle this to include/exclude table views

### Table Delete
Right click on Table name on left sidebar, (OR)
Click on `...` to open `Table context menu`, select `Delete`

Click on `Delete Table` to confirm

## Column
### Column Add
Click on `+` button to the right of Columns header, type `Column name`

Select a `type` for the column from the dropdown. Depending on the column type, you might find additional options to configure.
Click on `Save column` to finish creating column.

#### Column create before OR after a specific column
You can also use context menu of an existing column to either insert before or after a specific column.

### Column Edit
Double click on Column name in column header to open `Column edit` modal
You can rename column & optionally change column-type.

Note:
- Changing column type might not be allowed in some scenarios & in some other, might lead to either loss or truncated data.
- Column name is also possible using Column context menu as described below
### Column Duplicate
Open `Column context menu` (click `v` on column header), select `Duplicate`

Note: Column duplicate only creates another column of same type & inserts it to the immediate right. Currently data in the column is not duplicated.
### Column Delete
Open `Column context menu` (click `v` on column header), select `Delete`

Click on `Delete Column` to confirm

## Row
For adding new values to the table we need new rows, new rows can be added in two methods.
### Row Add (Using Form)
Click on `New Record` at the bottom of the grid (footbar), select `New Record - Form`

Populate columns in the Expnaded form popup; click `Save`

### Row Add (Using Table Row at bottom of page)

Click on any of the following options to insert a new record on the grid directly.
- `+`
- `New Record` : `New Record- Grid`
- Right click on any cell, click `Insert new row` from the cell context menu
Note that, any record inserted in the grid will always be appended to the end of the table by default.
### Row Add (Pressing Enter Key from Previous Row)
When you finish editing a cell and press Enter, the cell in the next row with the same column will be highlighted.

### Row Edit
You can start editing by any of the following methods
- Double-click on cell to edit
- Click on cell and start typing (this way it will clear the previous content)
- Click on cell and press enter to start editing
- And it will automatically save on blur event or if inactive.
### Row Delete
Right-click on the row and then from the context menu select `Delete Row` option.

Bulk delete is also possible by selecting multiple rows by using the checkbox in first column and then `Delete Selected Rows` options from the right click context menu.

## Quick Import
You can use Quick Import when you have data from external sources such as Airtable, CSV file or Microsoft Excel to an existing project by either
- Hover on `Project title` in tree-view, click `...` > `Quick Import From` > `Airtable` or `CSV file` or `Microsoft Excel` or `JSON file`
- Drag and drop CSV, JSON or Excel file to import

### Import Airtable into an Existing Project
- See [here](/setup-and-usages/import-airtable-to-sql-database-within-a-minute-for-free)
### Import CSV data into an Existing Project
- Hover on `Project title` in tree-view, click `...` > `Quick Import From` > `CSV file`
- Drag & drop or select files (at most 5 files) to upload or specify CSV file URL, and Click Import
- **Auto-Select Field Types**: If it is checked, column types will be detected. Otherwise, it will default to `SingleLineText`.
- **Use First Row as Headers**: If it is checked, the first row will be treated as header row.
- **Import Data**: If it is checked, all data will be imported. Otherwise, only table will be created.

- You can revise the table name by double-clicking it, column name and column type. By default, the first column will be chosen as `Display Value` and cannot be deleted.

- Click `Import` to start importing process. The table will be created and the data will be imported.

### Import Excel data into an Existing Project
- Hover on `Project title` in tree-view, click `...` > `Quick Import From` > `Excel file`
- Drag & drop or select files (at most 5 files) to upload or specify CSV file URL, and Click Import
- **Auto-Select Field Types**: If it is checked, column types will be detected. Otherwise, it will default to `SingleLineText`.
- **Use First Row as Headers**: If it is checked, the first row will be treated as header row.
- **Import Data**: If it is checked, all data will be imported. Otherwise, only table will be created.

- You can revise the table name by double-clicking it, column name and column type. By default, the first column will be chosen as `Display Value` and cannot be deleted.

- Click `Import` to start importing process. The table will be created and the data will be imported.

## Export Data
You can export your data from a table as a CSV file by clicking the `...` menu in toolbar, and hover on `Download`. Currently only CSV and XLSX formats are supported for export.

## Import Data
You can export your data from a table as a CSV file by clicking the `...` menu in toolbar, and hover on `Upload`. Currently only CSV and XLSX formats are supported for import.

| packages/noco-docs/docs/030.setup-and-usages/020.table-operations.md | 0 | https://github.com/nocodb/nocodb/commit/cfe6c234eee6067a01e9ccf6501d60f8a26513fd | [
0.00029538373928517103,
0.00017561743152327836,
0.0001622042473172769,
0.00016769222565926611,
0.000028423011826816946
] |
{
"id": 2,
"code_window": [
"const reloadRowTrigger = inject(ReloadRowDataHookInj, createEventHook())\n",
"\n",
"const isForm = inject(IsFormInj)\n",
"\n",
"const _readOnly = inject(ReadonlyInj, ref(false))\n",
"\n",
"const readOnly = computed(() => props.readonly || _readOnly.value)\n",
"\n",
"const isLocked = inject(IsLockedInj, ref(false))\n",
"\n",
"const isUnderLookup = inject(IsUnderLookupInj, ref(false))\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const readOnly = inject(ReadonlyInj, ref(false))\n"
],
"file_path": "packages/nc-gui/components/virtual-cell/Links.vue",
"type": "replace",
"edit_start_line_idx": 21
} | import { Test } from '@nestjs/testing';
import { LocalStrategy } from './local.strategy';
import type { TestingModule } from '@nestjs/testing';
describe('LocalStrategy', () => {
let provider: LocalStrategy;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [LocalStrategy],
}).compile();
provider = module.get<LocalStrategy>(LocalStrategy);
});
it('should be defined', () => {
expect(provider).toBeDefined();
});
});
| packages/nocodb/src/strategies/local.strategy.spec.ts | 0 | https://github.com/nocodb/nocodb/commit/cfe6c234eee6067a01e9ccf6501d60f8a26513fd | [
0.00017615794786252081,
0.00017441471572965384,
0.00017267146904487163,
0.00017441471572965384,
0.0000017432394088245928
] |
{
"id": 2,
"code_window": [
"const reloadRowTrigger = inject(ReloadRowDataHookInj, createEventHook())\n",
"\n",
"const isForm = inject(IsFormInj)\n",
"\n",
"const _readOnly = inject(ReadonlyInj, ref(false))\n",
"\n",
"const readOnly = computed(() => props.readonly || _readOnly.value)\n",
"\n",
"const isLocked = inject(IsLockedInj, ref(false))\n",
"\n",
"const isUnderLookup = inject(IsUnderLookupInj, ref(false))\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const readOnly = inject(ReadonlyInj, ref(false))\n"
],
"file_path": "packages/nc-gui/components/virtual-cell/Links.vue",
"type": "replace",
"edit_start_line_idx": 21
} | import { XcActionType, XcType } from 'nocodb-sdk';
import SMTPPlugin from './SMTPPlugin';
import type { XcPluginConfig } from 'nc-plugin';
// @author <[email protected]>
const config: XcPluginConfig = {
builder: SMTPPlugin,
title: 'SMTP',
version: '0.0.2',
// icon: 'mdi-email-outline',
description: 'SMTP email client',
price: 'Free',
tags: 'Email',
category: 'Email',
inputs: {
title: 'Configure Email SMTP',
items: [
{
key: 'from',
label: 'From',
placeholder: 'eg: [email protected]',
type: XcType.SingleLineText,
required: true,
},
{
key: 'host',
label: 'Host',
placeholder: 'eg: smtp.run.com',
type: XcType.SingleLineText,
required: true,
},
{
key: 'port',
label: 'Port',
placeholder: 'Port',
type: XcType.SingleLineText,
required: true,
},
{
key: 'secure',
label: 'Secure',
placeholder: 'Secure',
type: XcType.Checkbox,
required: false,
},
{
key: 'ignoreTLS',
label: 'Ignore TLS',
placeholder: 'Ignore TLS',
type: XcType.Checkbox,
required: false,
},
{
key: 'rejectUnauthorized',
label: 'Reject Unauthorized',
placeholder: 'Reject Unauthorized',
type: XcType.Checkbox,
required: false,
},
{
key: 'username',
label: 'Username',
placeholder: 'Username',
type: XcType.SingleLineText,
required: false,
},
{
key: 'password',
label: 'Password',
placeholder: 'Password',
type: XcType.Password,
required: false,
},
],
actions: [
{
label: 'Test',
key: 'test',
actionType: XcActionType.TEST,
type: XcType.Button,
},
{
label: 'Save',
key: 'save',
actionType: XcActionType.SUBMIT,
type: XcType.Button,
},
],
msgOnInstall:
'Successfully installed and email notification will use SMTP configuration',
msgOnUninstall: '',
},
};
export default config;
| packages/nocodb/src/plugins/smtp/index.ts | 0 | https://github.com/nocodb/nocodb/commit/cfe6c234eee6067a01e9ccf6501d60f8a26513fd | [
0.00017648041830398142,
0.00017526203009765595,
0.00017289238166995347,
0.00017547598690725863,
0.0000010011345921157044
] |
{
"id": 3,
"code_window": [
"}\n",
"\n",
"const openChildList = () => {\n",
" if (readOnly.value) return\n",
"\n",
" if (!isLocked.value) {\n",
" childListDlg.value = true\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isUnderLookup.value) return\n"
],
"file_path": "packages/nc-gui/components/virtual-cell/Links.vue",
"type": "replace",
"edit_start_line_idx": 85
} | <script setup lang="ts">
import { computed } from '@vue/reactivity'
import type { ColumnType } from 'nocodb-sdk'
import { ref } from 'vue'
import type { Ref } from 'vue'
import { ActiveCellInj, CellValueInj, ColumnInj, IsUnderLookupInj, inject, useSelectedCellKeyupListener } from '#imports'
const props = defineProps<{
readonly: boolean
}>()
const value = inject(CellValueInj, ref(0))
const column = inject(ColumnInj)!
const row = inject(RowInj)!
const reloadRowTrigger = inject(ReloadRowDataHookInj, createEventHook())
const isForm = inject(IsFormInj)
const _readOnly = inject(ReadonlyInj, ref(false))
const readOnly = computed(() => props.readonly || _readOnly.value)
const isLocked = inject(IsLockedInj, ref(false))
const isUnderLookup = inject(IsUnderLookupInj, ref(false))
const colTitle = computed(() => column.value?.title || '')
const listItemsDlg = ref(false)
const childListDlg = ref(false)
const { isUIAllowed } = useRoles()
const { t } = useI18n()
const { state, isNew } = useSmartsheetRowStoreOrThrow()
const { relatedTableMeta, loadRelatedTableMeta, relatedTableDisplayValueProp } = useProvideLTARStore(
column as Ref<Required<ColumnType>>,
row,
isNew,
reloadRowTrigger.trigger,
)
const relatedTableDisplayColumn = computed(
() =>
relatedTableMeta.value?.columns?.find((c: any) => c.title === relatedTableDisplayValueProp.value) as ColumnType | undefined,
)
loadRelatedTableMeta()
const textVal = computed(() => {
if (isForm?.value) {
return state.value?.[colTitle.value]?.length
? `${+state.value?.[colTitle.value]?.length} ${t('msg.recordsLinked')}`
: t('msg.noRecordsLinked')
}
const parsedValue = +value?.value || 0
if (!parsedValue) {
return t('msg.noRecordsLinked')
} else if (parsedValue === 1) {
return `1 ${column.value?.meta?.singular || t('general.link')}`
} else {
return `${parsedValue} ${column.value?.meta?.plural || t('general.links')}`
}
})
const toatlRecordsLinked = computed(() => {
if (isForm?.value) {
return state.value?.[colTitle.value]?.length
}
return +value?.value || 0
})
const onAttachRecord = () => {
childListDlg.value = false
listItemsDlg.value = true
}
const openChildList = () => {
if (readOnly.value) return
if (!isLocked.value) {
childListDlg.value = true
}
}
useSelectedCellKeyupListener(inject(ActiveCellInj, ref(false)), (e: KeyboardEvent) => {
switch (e.key) {
case 'Enter':
if (isLocked.value || listItemsDlg.value) return
childListDlg.value = true
e.stopPropagation()
break
}
})
const localCellValue = computed<any[]>(() => {
if (isNew.value) {
return state?.value?.[column?.value.title as string] ?? []
}
return []
})
const openListDlg = () => {
if (readOnly.value) return
listItemsDlg.value = true
}
</script>
<template>
<div class="flex w-full group items-center nc-links-wrapper" @dblclick.stop="openChildList">
<div class="block flex-shrink truncate">
<component
:is="isLocked || isUnderLookup ? 'span' : 'a'"
v-e="['c:cell:links:modal:open']"
:title="textVal"
class="text-center nc-datatype-link underline-transparent"
:class="{ '!text-gray-300': !textVal }"
@click.stop.prevent="openChildList"
>
{{ textVal }}
</component>
</div>
<div class="flex-grow" />
<div v-if="!isLocked && !isUnderLookup" class="!xs:hidden flex justify-end hidden group-hover:flex items-center">
<MdiPlus
v-if="(!readOnly && isUIAllowed('dataEdit')) || isForm"
class="select-none !text-md text-gray-700 nc-action-icon nc-plus"
@click.stop="openListDlg"
/>
</div>
<LazyVirtualCellComponentsListItems
v-if="listItemsDlg || childListDlg"
v-model="listItemsDlg"
:column="relatedTableDisplayColumn"
/>
<LazyVirtualCellComponentsListChildItems
v-if="listItemsDlg || childListDlg"
v-model="childListDlg"
:items="toatlRecordsLinked"
:column="relatedTableDisplayColumn"
:cell-value="localCellValue"
@attach-record="onAttachRecord"
/>
</div>
</template>
| packages/nc-gui/components/virtual-cell/Links.vue | 1 | https://github.com/nocodb/nocodb/commit/cfe6c234eee6067a01e9ccf6501d60f8a26513fd | [
0.9982854723930359,
0.21808376908302307,
0.0001669338089413941,
0.0017722109332680702,
0.38416779041290283
] |
{
"id": 3,
"code_window": [
"}\n",
"\n",
"const openChildList = () => {\n",
" if (readOnly.value) return\n",
"\n",
" if (!isLocked.value) {\n",
" childListDlg.value = true\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isUnderLookup.value) return\n"
],
"file_path": "packages/nc-gui/components/virtual-cell/Links.vue",
"type": "replace",
"edit_start_line_idx": 85
} | <script lang="ts" setup>
import { CellClickHookInj, CurrentCellInj, createEventHook, ref } from '#imports'
const el = ref<HTMLTableDataCellElement>()
const cellClickHook = createEventHook()
provide(CellClickHookInj, cellClickHook)
provide(CurrentCellInj, el)
defineExpose({ el })
</script>
<template>
<td ref="el" class="select-none" @click="cellClickHook.trigger($event)">
<slot />
</td>
</template>
| packages/nc-gui/components/smartsheet/TableDataCell.vue | 0 | https://github.com/nocodb/nocodb/commit/cfe6c234eee6067a01e9ccf6501d60f8a26513fd | [
0.0001737817656248808,
0.00017369573470205069,
0.00017360968922730535,
0.00017369573470205069,
8.603819878771901e-8
] |
{
"id": 3,
"code_window": [
"}\n",
"\n",
"const openChildList = () => {\n",
" if (readOnly.value) return\n",
"\n",
" if (!isLocked.value) {\n",
" childListDlg.value = true\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isUnderLookup.value) return\n"
],
"file_path": "packages/nc-gui/components/virtual-cell/Links.vue",
"type": "replace",
"edit_start_line_idx": 85
} | import { XcWebhookNotificationPlugin } from 'nc-plugin';
import Teams from './Teams';
import type { IWebhookNotificationAdapter } from 'nc-plugin';
class TeamsPlugin extends XcWebhookNotificationPlugin {
private static notificationAdapter: Teams;
public getAdapter(): IWebhookNotificationAdapter {
return TeamsPlugin.notificationAdapter;
}
public async init(_config: any): Promise<any> {
TeamsPlugin.notificationAdapter = new Teams();
await TeamsPlugin.notificationAdapter.init();
}
}
export default TeamsPlugin;
| packages/nocodb/src/plugins/teams/TeamsPlugin.ts | 0 | https://github.com/nocodb/nocodb/commit/cfe6c234eee6067a01e9ccf6501d60f8a26513fd | [
0.00017683953046798706,
0.0001716826081974432,
0.00016652568592689931,
0.0001716826081974432,
0.000005156922270543873
] |
{
"id": 3,
"code_window": [
"}\n",
"\n",
"const openChildList = () => {\n",
" if (readOnly.value) return\n",
"\n",
" if (!isLocked.value) {\n",
" childListDlg.value = true\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isUnderLookup.value) return\n"
],
"file_path": "packages/nc-gui/components/virtual-cell/Links.vue",
"type": "replace",
"edit_start_line_idx": 85
} | <script setup lang="ts">
import type { ProjectEventType } from 'nocodb-sdk'
import { AppEvents } from 'nocodb-sdk'
const props = defineProps<{
item: ProjectEventType
}>()
const item = toRef(props, 'item')
const { navigateToProject } = useGlobal()
const action = computed(() => {
switch (item.value.type) {
case AppEvents.VIEW_CREATE:
return 'created'
case AppEvents.VIEW_UPDATE:
return 'updated'
case AppEvents.VIEW_DELETE:
return 'deleted'
}
})
const onClick = () => {
if (item.value.type === AppEvents.VIEW_DELETE) return
navigateToProject({ baseId: item.value.body.id })
}
</script>
<template>
<NotificationItemWrapper :item="item" @click="onClick">
<div class="text-xs gap-2">
View
<strong>{{ item.body.title }}</strong>
{{ action }} successfully
</div>
</NotificationItemWrapper>
</template>
| packages/nc-gui/components/notification/Item/ViewEvent.vue | 0 | https://github.com/nocodb/nocodb/commit/cfe6c234eee6067a01e9ccf6501d60f8a26513fd | [
0.00017589644994586706,
0.00017213844694197178,
0.00016798639262560755,
0.00017233547987416387,
0.0000031793401831237134
] |
{
"id": 4,
"code_window": [
" }\n",
" return []\n",
"})\n",
"\n",
"const openListDlg = () => {\n",
" if (readOnly.value) return\n",
" listItemsDlg.value = true\n",
"}\n",
"</script>\n",
"\n",
"<template>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isUnderLookup.value) return\n",
"\n"
],
"file_path": "packages/nc-gui/components/virtual-cell/Links.vue",
"type": "replace",
"edit_start_line_idx": 110
} | <script setup lang="ts">
import { computed } from '@vue/reactivity'
import type { ColumnType } from 'nocodb-sdk'
import { ref } from 'vue'
import type { Ref } from 'vue'
import { ActiveCellInj, CellValueInj, ColumnInj, IsUnderLookupInj, inject, useSelectedCellKeyupListener } from '#imports'
const props = defineProps<{
readonly: boolean
}>()
const value = inject(CellValueInj, ref(0))
const column = inject(ColumnInj)!
const row = inject(RowInj)!
const reloadRowTrigger = inject(ReloadRowDataHookInj, createEventHook())
const isForm = inject(IsFormInj)
const _readOnly = inject(ReadonlyInj, ref(false))
const readOnly = computed(() => props.readonly || _readOnly.value)
const isLocked = inject(IsLockedInj, ref(false))
const isUnderLookup = inject(IsUnderLookupInj, ref(false))
const colTitle = computed(() => column.value?.title || '')
const listItemsDlg = ref(false)
const childListDlg = ref(false)
const { isUIAllowed } = useRoles()
const { t } = useI18n()
const { state, isNew } = useSmartsheetRowStoreOrThrow()
const { relatedTableMeta, loadRelatedTableMeta, relatedTableDisplayValueProp } = useProvideLTARStore(
column as Ref<Required<ColumnType>>,
row,
isNew,
reloadRowTrigger.trigger,
)
const relatedTableDisplayColumn = computed(
() =>
relatedTableMeta.value?.columns?.find((c: any) => c.title === relatedTableDisplayValueProp.value) as ColumnType | undefined,
)
loadRelatedTableMeta()
const textVal = computed(() => {
if (isForm?.value) {
return state.value?.[colTitle.value]?.length
? `${+state.value?.[colTitle.value]?.length} ${t('msg.recordsLinked')}`
: t('msg.noRecordsLinked')
}
const parsedValue = +value?.value || 0
if (!parsedValue) {
return t('msg.noRecordsLinked')
} else if (parsedValue === 1) {
return `1 ${column.value?.meta?.singular || t('general.link')}`
} else {
return `${parsedValue} ${column.value?.meta?.plural || t('general.links')}`
}
})
const toatlRecordsLinked = computed(() => {
if (isForm?.value) {
return state.value?.[colTitle.value]?.length
}
return +value?.value || 0
})
const onAttachRecord = () => {
childListDlg.value = false
listItemsDlg.value = true
}
const openChildList = () => {
if (readOnly.value) return
if (!isLocked.value) {
childListDlg.value = true
}
}
useSelectedCellKeyupListener(inject(ActiveCellInj, ref(false)), (e: KeyboardEvent) => {
switch (e.key) {
case 'Enter':
if (isLocked.value || listItemsDlg.value) return
childListDlg.value = true
e.stopPropagation()
break
}
})
const localCellValue = computed<any[]>(() => {
if (isNew.value) {
return state?.value?.[column?.value.title as string] ?? []
}
return []
})
const openListDlg = () => {
if (readOnly.value) return
listItemsDlg.value = true
}
</script>
<template>
<div class="flex w-full group items-center nc-links-wrapper" @dblclick.stop="openChildList">
<div class="block flex-shrink truncate">
<component
:is="isLocked || isUnderLookup ? 'span' : 'a'"
v-e="['c:cell:links:modal:open']"
:title="textVal"
class="text-center nc-datatype-link underline-transparent"
:class="{ '!text-gray-300': !textVal }"
@click.stop.prevent="openChildList"
>
{{ textVal }}
</component>
</div>
<div class="flex-grow" />
<div v-if="!isLocked && !isUnderLookup" class="!xs:hidden flex justify-end hidden group-hover:flex items-center">
<MdiPlus
v-if="(!readOnly && isUIAllowed('dataEdit')) || isForm"
class="select-none !text-md text-gray-700 nc-action-icon nc-plus"
@click.stop="openListDlg"
/>
</div>
<LazyVirtualCellComponentsListItems
v-if="listItemsDlg || childListDlg"
v-model="listItemsDlg"
:column="relatedTableDisplayColumn"
/>
<LazyVirtualCellComponentsListChildItems
v-if="listItemsDlg || childListDlg"
v-model="childListDlg"
:items="toatlRecordsLinked"
:column="relatedTableDisplayColumn"
:cell-value="localCellValue"
@attach-record="onAttachRecord"
/>
</div>
</template>
| packages/nc-gui/components/virtual-cell/Links.vue | 1 | https://github.com/nocodb/nocodb/commit/cfe6c234eee6067a01e9ccf6501d60f8a26513fd | [
0.9990659356117249,
0.3299599885940552,
0.0001659219851717353,
0.001337738591246307,
0.43828579783439636
] |
{
"id": 4,
"code_window": [
" }\n",
" return []\n",
"})\n",
"\n",
"const openListDlg = () => {\n",
" if (readOnly.value) return\n",
" listItemsDlg.value = true\n",
"}\n",
"</script>\n",
"\n",
"<template>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isUnderLookup.value) return\n",
"\n"
],
"file_path": "packages/nc-gui/components/virtual-cell/Links.vue",
"type": "replace",
"edit_start_line_idx": 110
} | <script lang="ts" setup>
import type { ColumnType, LinkToAnotherRecordType } from 'nocodb-sdk'
import { RelationTypes, UITypes, isVirtualCol } from 'nocodb-sdk'
import { breakpointsTailwind } from '@vueuse/core'
import {
DropZoneRef,
IsSurveyFormInj,
computed,
iconMap,
isValidURL,
onKeyStroke,
onMounted,
provide,
ref,
useBreakpoints,
useI18n,
usePointerSwipe,
useSharedFormStoreOrThrow,
useStepper,
validateEmail,
} from '#imports'
enum TransitionDirection {
Left = 'left',
Right = 'right',
}
enum AnimationTarget {
ArrowLeft = 'arrow-left',
ArrowRight = 'arrow-right',
OkButton = 'ok-button',
SubmitButton = 'submit-button',
}
const { md } = useBreakpoints(breakpointsTailwind)
const { v$, formState, formColumns, submitForm, submitted, secondsRemain, sharedFormView, sharedViewMeta, onReset } =
useSharedFormStoreOrThrow()
const { t } = useI18n()
const isTransitioning = ref(false)
const transitionName = ref<TransitionDirection>(TransitionDirection.Left)
const animationTarget = ref<AnimationTarget>(AnimationTarget.ArrowRight)
const isAnimating = ref(false)
const editEnabled = ref<boolean[]>([])
const el = ref<HTMLDivElement>()
provide(DropZoneRef, el)
provide(IsSurveyFormInj, ref(true))
const transitionDuration = computed(() => sharedViewMeta.value.transitionDuration || 50)
const steps = computed(() => {
if (!formColumns.value) return []
return formColumns.value.reduce<string[]>((acc, column) => {
const title = column.label || column.title
if (!title) return acc
acc.push(title)
return acc
}, [])
})
const { index, goToPrevious, goToNext, isFirst, isLast, goTo } = useStepper(steps)
const field = computed(() => formColumns.value?.[index.value])
const columnValidationError = ref(false)
function isRequired(column: ColumnType, required = false) {
let columnObj = column
if (
columnObj.uidt === UITypes.LinkToAnotherRecord &&
columnObj.colOptions &&
(columnObj.colOptions as { type: RelationTypes }).type === RelationTypes.BELONGS_TO
) {
columnObj = formColumns.value?.find(
(c) => c.id === (columnObj.colOptions as LinkToAnotherRecordType).fk_child_column_id,
) as ColumnType
}
return required || (columnObj && columnObj.rqd && !columnObj.cdf)
}
function transition(direction: TransitionDirection) {
isTransitioning.value = true
transitionName.value = direction
setTimeout(() => {
transitionName.value =
transitionName.value === TransitionDirection.Left ? TransitionDirection.Right : TransitionDirection.Left
}, transitionDuration.value / 2)
setTimeout(() => {
isTransitioning.value = false
setTimeout(focusInput, 100)
}, transitionDuration.value)
}
function animate(target: AnimationTarget) {
animationTarget.value = target
isAnimating.value = true
setTimeout(() => {
isAnimating.value = false
}, transitionDuration.value / 2)
}
async function validateColumn() {
const f = field.value!
if (parseProp(f.meta)?.validate && formState.value[f.title!]) {
if (f.uidt === UITypes.Email) {
if (!validateEmail(formState.value[f.title!])) {
columnValidationError.value = true
message.error(t('msg.error.invalidEmail'))
return false
}
} else if (f.uidt === UITypes.URL) {
if (!isValidURL(formState.value[f.title!])) {
columnValidationError.value = true
message.error(t('msg.error.invalidURL'))
return false
}
}
}
return true
}
async function goNext(animationTarget?: AnimationTarget) {
columnValidationError.value = false
if (isLast.value || submitted.value) return
if (!field.value || !field.value.title) return
const validationField = v$.value.localState[field.value.title]
if (validationField) {
const isValid = await validationField.$validate()
if (!isValid) return
}
if (!(await validateColumn())) return
animate(animationTarget || AnimationTarget.ArrowRight)
setTimeout(
() => {
transition(TransitionDirection.Left)
goToNext()
},
animationTarget === AnimationTarget.OkButton ? 300 : 0,
)
}
async function goPrevious(animationTarget?: AnimationTarget) {
if (isFirst.value || submitted.value) return
animate(animationTarget || AnimationTarget.ArrowLeft)
transition(TransitionDirection.Right)
goToPrevious()
}
function focusInput() {
if (document && typeof document !== 'undefined') {
const inputEl =
(document.querySelector('.nc-cell input') as HTMLInputElement) ||
(document.querySelector('.nc-cell textarea') as HTMLTextAreaElement)
if (inputEl) {
inputEl.select()
inputEl.focus()
}
}
}
function resetForm() {
v$.value.$reset()
submitted.value = false
transition(TransitionDirection.Right)
goTo(steps.value[0])
}
async function submit() {
if (submitted.value || !(await validateColumn())) return
submitForm()
}
onReset(resetForm)
onKeyStroke(['ArrowLeft', 'ArrowDown'], () => {
goPrevious(AnimationTarget.ArrowLeft)
})
onKeyStroke(['ArrowRight', 'ArrowUp'], () => {
goNext(AnimationTarget.ArrowRight)
})
onKeyStroke(['Enter', 'Space'], () => {
if (isLast.value) {
submit()
} else {
goNext(AnimationTarget.OkButton, true)
}
})
onMounted(() => {
focusInput()
if (!md.value) {
const { direction } = usePointerSwipe(el, {
onSwipe: () => {
if (isTransitioning.value) return
if (direction.value === 'left') {
goNext()
} else if (direction.value === 'right') {
goPrevious()
}
},
})
}
})
</script>
<template>
<div ref="el" class="survey pt-8 md:p-0 w-full h-full flex flex-col">
<div
v-if="sharedFormView"
style="height: max(40vh, 225px); min-height: 225px"
class="max-w-[max(33%,600px)] mx-auto flex flex-col justify-end"
>
<div class="px-4 md:px-0 flex flex-col justify-end">
<h1 class="prose-2xl font-bold self-center my-4" data-testid="nc-survey-form__heading">
{{ sharedFormView.heading }}
</h1>
<h2
v-if="sharedFormView.subheading && sharedFormView.subheading !== ''"
class="prose-lg text-slate-500 dark:text-slate-300 self-center mb-4 leading-6"
data-testid="nc-survey-form__sub-heading"
>
{{ sharedFormView?.subheading }}
</h2>
</div>
</div>
<div class="h-full w-full flex items-center px-4 md:px-0">
<Transition :name="`slide-${transitionName}`" :duration="transitionDuration" mode="out-in">
<div
ref="el"
:key="field?.title"
class="color-transition h-full flex flex-col mt-6 gap-4 w-full max-w-[max(33%,600px)] m-auto"
>
<div v-if="field && !submitted" class="flex flex-col gap-2">
<div class="flex nc-form-column-label" data-testid="nc-form-column-label">
<LazySmartsheetHeaderVirtualCell
v-if="isVirtualCol(field)"
:column="{ ...field, title: field.label || field.title }"
:required="isRequired(field, field.required)"
:hide-menu="true"
/>
<LazySmartsheetHeaderCell
v-else
:class="field.uidt === UITypes.Checkbox ? 'nc-form-column-label__checkbox' : ''"
:column="{ meta: {}, ...field, title: field.label || field.title }"
:required="isRequired(field, field.required)"
:hide-menu="true"
/>
</div>
<LazySmartsheetDivDataCell v-if="field.title" class="relative">
<LazySmartsheetVirtualCell
v-if="isVirtualCol(field)"
v-model="formState[field.title]"
class="mt-0 nc-input h-auto"
:row="{ row: {}, oldRow: {}, rowMeta: {} }"
:data-testid="`nc-survey-form__input-${field.title.replaceAll(' ', '')}`"
:column="field"
/>
<LazySmartsheetCell
v-else
v-model="formState[field.title]"
class="nc-input h-auto"
:data-testid="`nc-survey-form__input-${field.title.replaceAll(' ', '')}`"
:column="field"
:edit-enabled="editEnabled[index]"
@click="editEnabled[index] = true"
@cancel="editEnabled[index] = false"
@update:edit-enabled="editEnabled[index] = $event"
/>
<div class="flex flex-col gap-2 text-slate-500 dark:text-slate-300 text-[0.75rem] my-2 px-1">
<div v-for="error of v$.localState[field.title]?.$errors" :key="error" class="text-red-500">
{{ error.$message }}
</div>
<div
class="block text-[14px]"
:class="field.uidt === UITypes.Checkbox ? 'text-center' : ''"
data-testid="nc-survey-form__field-description"
>
{{ field.description }}
</div>
<div v-if="field.uidt === UITypes.LongText" class="text-sm text-gray-500 flex flex-wrap items-center">
Shift <MdiAppleKeyboardShift class="mx-1 text-primary" /> + Enter
<MaterialSymbolsKeyboardReturn class="mx-1 text-primary" /> to make a line break
</div>
</div>
</LazySmartsheetDivDataCell>
</div>
<div class="ml-1 mt-4 flex w-full text-lg">
<div class="flex-1 flex justify-center">
<div v-if="isLast && !submitted && !v$.$invalid" class="text-center my-4">
<button
:class="
animationTarget === AnimationTarget.SubmitButton && isAnimating
? 'transform translate-y-[1px] translate-x-[1px] ring ring-accent ring-opacity-100'
: ''
"
type="submit"
class="uppercase scaling-btn prose-sm"
data-testid="nc-survey-form__btn-submit"
@click="submit"
>
{{ $t('general.submit') }}
</button>
</div>
<div v-else-if="!submitted" class="flex items-center gap-3 flex-col">
<a-tooltip
:title="v$.localState[field.title]?.$error ? v$.localState[field.title].$errors[0].$message : 'Go to next'"
:mouse-enter-delay="0.25"
:mouse-leave-delay="0"
>
<!-- Ok button for question -->
<NcButton
data-testid="nc-survey-form__btn-next"
:class="[
v$.localState[field.title]?.$error || columnValidationError ? 'after:!bg-gray-100 after:!ring-red-500' : '',
animationTarget === AnimationTarget.OkButton && isAnimating
? 'transform translate-y-[2px] translate-x-[2px] after:(!ring !ring-accent !ring-opacity-100)'
: '',
]"
@click="goNext()"
>
<Transition name="fade">
<span v-if="!v$.localState[field.title]?.$error" class="uppercase text-white">Ok</span>
</Transition>
<Transition name="slide-right" mode="out-in">
<component
:is="iconMap.closeCircle"
v-if="v$.localState[field.title]?.$error || columnValidationError"
class="text-red-500 md:text-md"
/>
<component :is="iconMap.check" v-else class="text-white md:text-md" />
</Transition>
</NcButton>
</a-tooltip>
<!-- todo: i18n -->
<div class="hidden md:flex text-sm text-gray-500 items-center gap-1">
Press Enter <MaterialSymbolsKeyboardReturn class="text-primary" />
</div>
</div>
</div>
</div>
<Transition name="slide-left">
<div v-if="submitted" class="flex flex-col justify-center items-center text-center">
<div class="text-lg px-6 py-3 bg-green-300 text-gray-700 rounded" data-testid="nc-survey-form__success-msg">
<template v-if="sharedFormView?.success_msg">
{{ sharedFormView?.success_msg }}
</template>
<template v-else>
<div class="flex flex-col gap-1">
<div>Thank you!</div>
<div>You have successfully submitted the form data.</div>
</div>
</template>
</div>
<div v-if="sharedFormView" class="mt-3">
<p v-if="sharedFormView?.show_blank_form" class="text-xs text-slate-500 dark:text-slate-300 text-center my-4">
New form will be loaded after {{ secondsRemain }} seconds
</p>
<div v-if="sharedFormView?.submit_another_form" class="text-center">
<NcButton type="primary" data-testid="nc-survey-form__btn-submit-another-form" @click="resetForm">
Submit Another Form
</NcButton>
</div>
</div>
</div>
</Transition>
</div>
</Transition>
</div>
<template v-if="!submitted">
<div class="mb-24 md:my-4 select-none text-center text-gray-500 dark:text-slate-200" data-testid="nc-survey-form__footer">
{{ index + 1 }} / {{ formColumns?.length }}
</div>
</template>
<div class="relative flex w-full items-end">
<Transition name="fade">
<div
v-if="!submitted"
class="color-transition shadow-sm absolute bottom-18 right-1/2 transform translate-x-[50%] md:bottom-4 md:(right-12 transform-none) flex items-center bg-white border dark:bg-slate-500 rounded divide-x-1"
>
<a-tooltip :title="isFirst ? '' : 'Go to previous'" :mouse-enter-delay="0.25" :mouse-leave-delay="0">
<button
:class="
animationTarget === AnimationTarget.ArrowLeft && isAnimating
? 'transform translate-y-[1px] translate-x-[1px] text-primary'
: ''
"
class="p-0.5 flex items-center group color-transition"
data-testid="nc-survey-form__icon-prev"
@click="goPrevious()"
>
<component
:is="iconMap.chevronLeft"
:class="isFirst ? 'text-gray-300' : 'group-hover:text-accent'"
class="text-2xl md:text-md"
/>
</button>
</a-tooltip>
<a-tooltip
:title="v$.localState[field.title]?.$error ? '' : 'Go to next'"
:mouse-enter-delay="0.25"
:mouse-leave-delay="0"
>
<button
:class="
animationTarget === AnimationTarget.ArrowRight && isAnimating
? 'transform translate-y-[1px] translate-x-[-1px] text-primary'
: ''
"
class="p-0.5 flex items-center group color-transition"
data-testid="nc-survey-form__icon-next"
@click="goNext()"
>
<component
:is="iconMap.chevronRight"
:class="[isLast || v$.localState[field.title]?.$error ? 'text-gray-300' : 'group-hover:text-accent']"
class="text-2xl md:text-md"
/>
</button>
</a-tooltip>
</div>
</Transition>
<GeneralPoweredBy />
</div>
</div>
</template>
<style lang="scss">
:global(html, body) {
@apply overscroll-x-none;
}
.survey {
.nc-form-column-label {
> * {
@apply !prose-lg;
}
.nc-icon {
@apply mr-2;
}
}
.nc-form-column-label__checkbox {
@apply flex items-center justify-center gap-2 text-left;
}
.nc-input {
@apply appearance-none w-full rounded px-2 py-2 my-2 border-solid border-1 border-primary border-opacity-50;
&.nc-cell-checkbox {
> * {
@apply justify-center flex items-center;
}
}
input {
@apply !py-1 !px-1;
}
}
}
</style>
| packages/nc-gui/pages/index/[typeOrId]/form/[viewId]/index/survey.vue | 0 | https://github.com/nocodb/nocodb/commit/cfe6c234eee6067a01e9ccf6501d60f8a26513fd | [
0.0002781577059067786,
0.00017290719551965594,
0.0001651769271120429,
0.00017102647689171135,
0.000014990938325354364
] |
{
"id": 4,
"code_window": [
" }\n",
" return []\n",
"})\n",
"\n",
"const openListDlg = () => {\n",
" if (readOnly.value) return\n",
" listItemsDlg.value = true\n",
"}\n",
"</script>\n",
"\n",
"<template>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isUnderLookup.value) return\n",
"\n"
],
"file_path": "packages/nc-gui/components/virtual-cell/Links.vue",
"type": "replace",
"edit_start_line_idx": 110
} | import { NormalColumnRequestType } from '../Api'
import UITypes from '../UITypes';
import { IDType } from './index';
export class OracleUi {
static getNewTableColumns(): any[] {
return [
{
column_name: 'id',
title: 'Id',
dt: 'integer',
dtx: 'integer',
ct: 'int(11)',
nrqd: false,
rqd: true,
ck: false,
pk: true,
un: false,
ai: false,
cdf: null,
clen: null,
np: null,
ns: null,
dtxp: '',
dtxs: '',
altered: 1,
uidt: 'ID',
uip: '',
uicn: '',
},
{
column_name: 'title',
title: 'Title',
dt: 'varchar',
dtx: 'specificType',
ct: 'varchar(45)',
nrqd: true,
rqd: false,
ck: false,
pk: false,
un: false,
ai: false,
cdf: null,
clen: 45,
np: null,
ns: null,
dtxp: '45',
dtxs: '',
altered: 1,
uidt: 'SingleLineText',
uip: '',
uicn: '',
},
// {
// column_name: "created_at",
// dt: "timestamp",
// dtx: "specificType",
// ct: "varchar(45)",
// nrqd: true,
// rqd: false,
// ck: false,
// pk: false,
// un: false,
// ai: false,
// cdf: 'CURRENT_TIMESTAMP',
// clen: 45,
// np: null,
// ns: null,
// dtxp: '',
// dtxs: ''
// },
// {
// column_name: "updated_at",
// dt: "timestamp",
// dtx: "specificType",
// ct: "varchar(45)",
// nrqd: true,
// rqd: false,
// ck: false,
// pk: false,
// un: false,
// ai: false,
// cdf: 'CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP',
// clen: 45,
// np: null,
// ns: null,
// dtxp: '',
// dtxs: ''
// }
];
}
static getNewColumn(suffix) {
return {
column_name: 'title' + suffix,
dt: 'varchar',
dtx: 'specificType',
ct: 'varchar(45)',
nrqd: true,
rqd: false,
ck: false,
pk: false,
un: false,
ai: false,
cdf: null,
clen: 45,
np: null,
ns: null,
dtxp: '45',
dtxs: '',
altered: 1,
uidt: 'SingleLineText',
uip: '',
uicn: '',
};
}
// static getDefaultLengthForDatatype(type) {
// switch (type) {
// case "int":
// return 11;
// break;
// case "tinyint":
// return 1;
// break;
// case "smallint":
// return 5;
// break;
//
// case "mediumint":
// return 9;
// break;
// case "bigint":
// return 20;
// break;
// case "bit":
// return 64;
// break;
// case "boolean":
// return '';
// break;
// case "float":
// return 12;
// break;
// case "decimal":
// return 10;
// break;
// case "double":
// return 22;
// break;
// case "serial":
// return 20;
// break;
// case "date":
// return '';
// break;
// case "datetime":
// case "timestamp":
// return 6;
// break;
// case "time":
// return '';
// break;
// case "year":
// return '';
// break;
// case "char":
// return 255;
// break;
// case "varchar":
// return 45;
// break;
// case "nchar":
// return 255;
// break;
// case "text":
// return '';
// break;
// case "tinytext":
// return '';
// break;
// case "mediumtext":
// return '';
// break;
// case "longtext":
// return ''
// break;
// case "binary":
// return 255;
// break;
// case "varbinary":
// return 65500;
// break;
// case "blob":
// return '';
// break;
// case "tinyblob":
// return '';
// break;
// case "mediumblob":
// return '';
// break;
// case "longblob":
// return '';
// break;
// case "enum":
// return '\'a\',\'b\'';
// break;
// case "set":
// return '\'a\',\'b\'';
// break;
// case "geometry":
// return '';
// case "point":
// return '';
// case "linestring":
// return '';
// case "polygon":
// return '';
// case "multipoint":
// return '';
// case "multilinestring":
// return '';
// case "multipolygon":
// return '';
// case "json":
// return ''
// break;
//
// }
//
// }
static getDefaultLengthForDatatype(type) {
switch (type) {
default:
return '';
}
}
static getDefaultLengthIsDisabled(type): any {
switch (type) {
case 'integer':
return true;
case 'bfile':
case 'binary rowid':
case 'binary double':
case 'binary_float':
case 'blob':
case 'canoical':
case 'cfile':
case 'char':
case 'clob':
case 'content pointer':
case 'contigous array':
case 'date':
case 'decimal':
case 'double precision':
case 'float':
case 'interval day to second':
case 'interval year to month':
case 'lob pointer':
case 'long':
case 'long raw':
case 'named collection':
case 'named object':
case 'nchar':
case 'nclob':
case 'number':
case 'nvarchar2':
case 'octet':
case 'oid':
case 'pointer':
case 'raw':
case 'real':
case 'ref':
case 'ref cursor':
case 'rowid':
case 'signed binary integer':
case 'smallint':
case 'table':
case 'time':
case 'time with tz':
case 'timestamp':
case 'timestamp with local time zone':
case 'timestamp with local tz':
case 'timestamp with timezone':
case 'timestamp with tz':
case 'unsigned binary integer':
case 'urowid':
case 'varchar':
case 'varchar2':
case 'varray':
case 'varying array':
return false;
}
}
static getDefaultValueForDatatype(type) {
switch (type) {
default:
return '';
}
}
static getDefaultScaleForDatatype(type): any {
switch (type) {
case 'integer':
case 'bfile':
case 'binary rowid':
case 'binary double':
case 'binary_float':
case 'blob':
case 'canoical':
case 'cfile':
case 'char':
case 'clob':
case 'content pointer':
case 'contigous array':
case 'date':
case 'decimal':
case 'double precision':
case 'float':
case 'interval day to second':
case 'interval year to month':
case 'lob pointer':
case 'long':
case 'long raw':
case 'named collection':
case 'named object':
case 'nchar':
case 'nclob':
case 'number':
case 'nvarchar2':
case 'octet':
case 'oid':
case 'pointer':
case 'raw':
case 'real':
case 'ref':
case 'ref cursor':
case 'rowid':
case 'signed binary integer':
case 'smallint':
case 'table':
case 'time':
case 'time with tz':
case 'timestamp':
case 'timestamp with local time zone':
case 'timestamp with local tz':
case 'timestamp with timezone':
case 'timestamp with tz':
case 'unsigned binary integer':
case 'urowid':
case 'varchar':
case 'varchar2':
case 'varray':
case 'varying array':
return ' ';
}
}
static colPropAIDisabled(col, columns) {
// console.log(col);
if (
col.dt === 'int4' ||
col.dt === 'integer' ||
col.dt === 'bigint' ||
col.dt === 'smallint'
) {
for (let i = 0; i < columns.length; ++i) {
if (columns[i].cn !== col.cn && columns[i].ai) {
return true;
}
}
return false;
} else {
return true;
}
}
static colPropUNDisabled(_col) {
// console.log(col);
return true;
// if (col.dt === 'int' ||
// col.dt === 'tinyint' ||
// col.dt === 'smallint' ||
// col.dt === 'mediumint' ||
// col.dt === 'bigint') {
// return false;
// } else {
// return true;
// }
}
static onCheckboxChangeAI(col) {
console.log(col);
if (
col.dt === 'int' ||
col.dt === 'bigint' ||
col.dt === 'smallint' ||
col.dt === 'tinyint'
) {
col.altered = col.altered || 2;
}
// if (!col.ai) {
// col.dtx = 'specificType'
// } else {
// col.dtx = ''
// }
}
static showScale(_columnObj) {
return false;
}
static removeUnsigned(columns) {
for (let i = 0; i < columns.length; ++i) {
if (
columns[i].altered === 1 &&
!(
columns[i].dt === 'int' ||
columns[i].dt === 'bigint' ||
columns[i].dt === 'tinyint' ||
columns[i].dt === 'smallint' ||
columns[i].dt === 'mediumint'
)
) {
columns[i].un = false;
console.log('>> resetting unsigned value', columns[i].cn);
}
console.log(columns[i].cn);
}
}
static columnEditable(colObj) {
return colObj.tn !== '_evolutions' || colObj.tn !== 'nc_evolutions';
}
static extractFunctionName(query) {
const reg =
/^\s*CREATE\s+(?:OR\s+REPLACE\s*)?\s*FUNCTION\s+(?:[\w\d_]+\.)?([\w_\d]+)/i;
const match = query.match(reg);
return match && match[1];
}
static extractProcedureName(query) {
const reg =
/^\s*CREATE\s+(?:OR\s+REPLACE\s*)?\s*PROCEDURE\s+(?:[\w\d_]+\.)?([\w_\d]+)/i;
const match = query.match(reg);
return match && match[1];
}
static splitQueries(query) {
/***
* we are splitting based on semicolon
* there are mechanism to escape semicolon within single/double quotes(string)
*/
return query.match(/\b("[^"]*;[^"]*"|'[^']*;[^']*'|[^;])*;/g);
}
static onCheckboxChangeAU(col) {
console.log(col);
// if (1) {
col.altered = col.altered || 2;
// }
// if (!col.ai) {
// col.dtx = 'specificType'
// } else {
// col.dtx = ''
// }
}
/**
* if sql statement is SELECT - it limits to a number
* @param args
* @returns {string|*}
*/
sanitiseQuery(args) {
let q = args.query.trim().split(';');
if (q[0].startsWith('Select')) {
q = q[0] + ` LIMIT 0,${args.limit ? args.limit : 100};`;
} else if (q[0].startsWith('select')) {
q = q[0] + ` LIMIT 0,${args.limit ? args.limit : 100};`;
} else if (q[0].startsWith('SELECT')) {
q = q[0] + ` LIMIT 0,${args.limit ? args.limit : 100};`;
} else {
return args.query;
}
return q;
}
getColumnsFromJson(json, tn) {
const columns = [];
try {
if (typeof json === 'object' && !Array.isArray(json)) {
const keys = Object.keys(json);
for (let i = 0; i < keys.length; ++i) {
switch (typeof json[keys[i]]) {
case 'number':
if (Number.isInteger(json[keys[i]])) {
columns.push({
dp: null,
tn,
column_name: keys[i],
cno: keys[i],
dt: 'int',
np: 10,
ns: 0,
clen: null,
cop: 1,
pk: false,
nrqd: false,
rqd: false,
un: false,
ct: 'int(11) unsigned',
ai: false,
unique: false,
cdf: null,
cc: '',
csn: null,
dtx: 'specificType',
dtxp: '11',
dtxs: 0,
altered: 1,
});
} else {
columns.push({
dp: null,
tn,
column_name: keys[i],
cno: keys[i],
dt: 'float',
np: 10,
ns: 2,
clen: null,
cop: 1,
pk: false,
nrqd: false,
rqd: false,
un: false,
ct: 'int(11) unsigned',
ai: false,
unique: false,
cdf: null,
cc: '',
csn: null,
dtx: 'specificType',
dtxp: '11',
dtxs: 2,
altered: 1,
});
}
break;
case 'string':
if (json[keys[i]].length <= 255) {
columns.push({
dp: null,
tn,
column_name: keys[i],
cno: keys[i],
dt: 'varchar',
np: 45,
ns: 0,
clen: null,
cop: 1,
pk: false,
nrqd: false,
rqd: false,
un: false,
ct: 'int(11) unsigned',
ai: false,
unique: false,
cdf: null,
cc: '',
csn: null,
dtx: 'specificType',
dtxp: '45',
dtxs: 0,
altered: 1,
});
} else {
columns.push({
dp: null,
tn,
column_name: keys[i],
cno: keys[i],
dt: 'text',
np: null,
ns: 0,
clen: null,
cop: 1,
pk: false,
nrqd: false,
rqd: false,
un: false,
ct: 'int(11) unsigned',
ai: false,
unique: false,
cdf: null,
cc: '',
csn: null,
dtx: 'specificType',
dtxp: null,
dtxs: 0,
altered: 1,
});
}
break;
case 'boolean':
columns.push({
dp: null,
tn,
column_name: keys[i],
cno: keys[i],
dt: 'boolean',
np: 3,
ns: 0,
clen: null,
cop: 1,
pk: false,
nrqd: false,
rqd: false,
un: false,
ct: 'int(11) unsigned',
ai: false,
unique: false,
cdf: null,
cc: '',
csn: null,
dtx: 'specificType',
dtxp: '1',
dtxs: 0,
altered: 1,
});
break;
case 'object':
columns.push({
dp: null,
tn,
column_name: keys[i],
cno: keys[i],
dt: 'json',
np: 3,
ns: 0,
clen: null,
cop: 1,
pk: false,
nrqd: false,
rqd: false,
un: false,
ct: 'int(11) unsigned',
ai: false,
unique: false,
cdf: null,
cc: '',
csn: null,
dtx: 'specificType',
dtxp: null,
dtxs: 0,
altered: 1,
});
break;
default:
break;
}
}
}
} catch (e) {
console.log('Error in getColumnsFromJson', e);
}
return columns;
}
static colPropAuDisabled(_col) {
return true;
}
static getAbstractType(col): any {
switch (col.dt?.toLowerCase()) {
case 'integer':
return 'integer';
case 'bfile':
case 'binary rowid':
case 'binary double':
case 'binary_float':
return 'string';
case 'blob':
return 'blob';
case 'canoical':
case 'cfile':
case 'char':
case 'clob':
case 'content pointer':
case 'contigous array':
return 'string';
case 'date':
return 'date';
case 'decimal':
case 'double precision':
case 'float':
return 'float';
case 'interval day to second':
case 'interval year to month':
return 'string';
case 'lob pointer':
return 'string';
case 'long':
return 'integer';
case 'long raw':
return 'string';
case 'named collection':
case 'named object':
case 'nchar':
case 'nclob':
return 'string';
case 'nvarchar2':
case 'octet':
case 'oid':
case 'pointer':
case 'raw':
return 'string';
case 'real':
case 'number':
return 'float';
case 'ref':
case 'ref cursor':
case 'rowid':
case 'signed binary integer':
return 'string';
case 'smallint':
return 'integer';
case 'table':
return 'string';
case 'time':
case 'time with tz':
return 'time';
case 'timestamp':
case 'timestamp with local time zone':
case 'timestamp with local tz':
case 'timestamp with timezone':
case 'timestamp with tz':
return 'datetime';
case 'unsigned binary integer':
case 'urowid':
case 'varchar':
case 'varchar2':
return 'string';
case 'varray':
case 'varying array':
return 'string';
}
}
static getUIType(col): any {
switch (this.getAbstractType(col)) {
case 'integer':
return 'Number';
case 'boolean':
return 'Checkbox';
case 'float':
return 'Decimal';
case 'date':
return 'Date';
case 'datetime':
return 'CreateTime';
case 'time':
return 'Time';
case 'year':
return 'Year';
case 'string':
return 'SingleLineText';
case 'text':
return 'LongText';
case 'blob':
return 'Attachment';
case 'enum':
return 'SingleSelect';
case 'set':
return 'MultiSelect';
case 'json':
return 'LongText';
}
}
static getDataTypeForUiType(
col: { uidt: UITypes | NormalColumnRequestType['uidt'] },
idType?: IDType
) {
const colProp: any = {};
switch (col.uidt) {
case 'ID':
{
const isAutoIncId = idType === 'AI';
const isAutoGenId = idType === 'AG';
colProp.dt = isAutoGenId ? 'varchar' : 'integer';
colProp.pk = true;
colProp.un = isAutoIncId;
colProp.ai = isAutoIncId;
colProp.rqd = true;
colProp.meta = isAutoGenId ? { ag: 'nc' } : undefined;
}
break;
case 'ForeignKey':
colProp.dt = 'varchar';
break;
case 'SingleLineText':
colProp.dt = 'varchar';
break;
case 'LongText':
colProp.dt = 'clob';
break;
case 'Attachment':
colProp.dt = 'clob';
break;
case 'GeoData':
colProp.dt = 'varchar';
break;
case 'Checkbox':
colProp.dt = 'tinyint';
colProp.dtxp = 1;
colProp.cdf = '0';
break;
case 'MultiSelect':
colProp.dt = 'varchar2';
break;
case 'SingleSelect':
colProp.dt = 'varchar2';
break;
case 'Collaborator':
colProp.dt = 'varchar';
break;
case 'Date':
colProp.dt = 'varchar';
break;
case 'Year':
colProp.dt = 'year';
break;
case 'Time':
colProp.dt = 'time';
break;
case 'PhoneNumber':
colProp.dt = 'varchar';
colProp.validate = {
func: ['isMobilePhone'],
args: [''],
msg: ['Validation failed : isMobilePhone'],
};
break;
case 'Email':
colProp.dt = 'varchar';
colProp.validate = {
func: ['isEmail'],
args: [''],
msg: ['Validation failed : isEmail'],
};
break;
case 'URL':
colProp.dt = 'varchar';
colProp.validate = {
func: ['isURL'],
args: [''],
msg: ['Validation failed : isURL'],
};
break;
case 'Number':
colProp.dt = 'integer';
break;
case 'Decimal':
colProp.dt = 'decimal';
break;
case 'Currency':
colProp.dt = 'decimal';
colProp.validate = {
func: ['isCurrency'],
args: [''],
msg: ['Validation failed : isCurrency'],
};
break;
case 'Percent':
colProp.dt = 'double';
break;
case 'Duration':
colProp.dt = 'integer';
break;
case 'Rating':
colProp.dt = 'integer';
colProp.cdf = '0';
break;
case 'Formula':
colProp.dt = 'varchar';
break;
case 'Rollup':
colProp.dt = 'varchar';
break;
case 'Count':
colProp.dt = 'integer';
break;
case 'Lookup':
colProp.dt = 'varchar';
break;
case 'DateTime':
colProp.dt = 'timestamp';
break;
case 'CreateTime':
colProp.dt = 'timestamp';
break;
case 'LastModifiedTime':
colProp.dt = 'timestamp';
break;
case 'AutoNumber':
colProp.dt = 'integer';
break;
case 'Barcode':
colProp.dt = 'varchar';
break;
case 'Button':
colProp.dt = 'varchar';
break;
default:
colProp.dt = 'varchar';
break;
}
return colProp;
}
static getUnsupportedFnList() {
return [];
}
}
// module.exports = PgUiHelp;
| packages/nocodb-sdk/src/lib/sqlUi/OracleUi.ts | 0 | https://github.com/nocodb/nocodb/commit/cfe6c234eee6067a01e9ccf6501d60f8a26513fd | [
0.00022894413268659264,
0.0001742900931276381,
0.00016618958034086972,
0.0001741895393934101,
0.000006210796527739149
] |
{
"id": 4,
"code_window": [
" }\n",
" return []\n",
"})\n",
"\n",
"const openListDlg = () => {\n",
" if (readOnly.value) return\n",
" listItemsDlg.value = true\n",
"}\n",
"</script>\n",
"\n",
"<template>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (isUnderLookup.value) return\n",
"\n"
],
"file_path": "packages/nc-gui/components/virtual-cell/Links.vue",
"type": "replace",
"edit_start_line_idx": 110
} | ---
title: 'Usage Information'
description: 'Non-sensitive and anonymous usage information'
---
NocoDB is a fast growing open source project which is UI heavy and we are committed to providing a solution that exceeds the expectations of the users and community.
We are also committed to continuing to develop and make NocoDB even better than it is today.
To that end, NocoDB contains a feature in which anonymous and otherwise non-sensitive data is collected.
This anonymous and non-sensitive data gives a better understanding of how users are interacting and using the product.
## Context
We will always continue to do hands-on UI/UX testing, surveys, issue tracking and roadmap.
Otherwise talk with the Community while striving to understand
and deliver what is being asked for and what is needed, by any means available.
However, these above actions alone are often insufficient
- To maintain an overall picture of the product usage.
- Prioritising the efforts.
- Impact of any breaking changes.
- To understand whether UI improvements are helpful to users.
## What we collect ?
We collect actions made on models (project, table, view, sharedView, user, hook, image, sharedBase etc) periodically with :
- System information (OS, node version, docker or npm)
- Environment (dev, staging, production)
- Instance information (Unique machine ID, database type, count of projects and users)
- Failures.
Our UI Dashboard is a Vuejs-Nuxtjs app. Actions taken on UI with completely anonymized route names are sent as payload.
## What we DO NOT collect ?
We do not collect any private or sensitive information, such as:
- Personally identifiable information
- Credential information (endpoints, ports, DB connections, username/password)
- Database/User data
## Opt-out
To disable usage information collection please set following environment variable.
> NC_DISABLE_TELE=true
| packages/noco-docs/versioned_docs/version-0.109.7/030.setup-and-usages/210.usage-information.md | 0 | https://github.com/nocodb/nocodb/commit/cfe6c234eee6067a01e9ccf6501d60f8a26513fd | [
0.00017575145466253161,
0.00017064409621525556,
0.00016594397311564535,
0.00017081023543141782,
0.0000032568966616963735
] |
{
"id": 0,
"code_window": [
" ns: string | void;\n",
" context: Component;\n",
" key: string | number | void;\n",
" parent?: VNodeWithData;\n",
" child?: Component;\n",
"}\n",
"\n",
"declare interface VNodeData {\n",
" key?: string | number;\n",
" slot?: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" isRootInsert: boolean;\n"
],
"file_path": "flow/vnode.js",
"type": "add",
"edit_start_line_idx": 30
} | /**
* Virtual DOM implementation based on Snabbdom by
* Simon Friis Vindum (@paldepind)
* with custom modifications.
*
* Not type-checking this because this file is perf-critical and the cost
* of making flow understand it is not worth it.
*/
import config from '../config'
import VNode from './vnode'
import { isPrimitive, _toString, warn } from '../util/index'
const emptyData = {}
const emptyNode = new VNode('', emptyData, [])
const hooks = ['create', 'update', 'postpatch', 'remove', 'destroy']
function isUndef (s) {
return s == null
}
function isDef (s) {
return s != null
}
function sameVnode (vnode1, vnode2) {
if (vnode1.isStatic || vnode2.isStatic) {
return vnode1 === vnode2
}
return (
vnode1.key === vnode2.key &&
vnode1.tag === vnode2.tag &&
!vnode1.data === !vnode2.data
)
}
function createKeyToOldIdx (children, beginIdx, endIdx) {
let i, key
const map = {}
for (i = beginIdx; i <= endIdx; ++i) {
key = children[i].key
if (isDef(key)) map[key] = i
}
return map
}
export function createPatchFunction (backend) {
let i, j
const cbs = {}
const { modules, nodeOps } = backend
for (i = 0; i < hooks.length; ++i) {
cbs[hooks[i]] = []
for (j = 0; j < modules.length; ++j) {
if (modules[j][hooks[i]] !== undefined) cbs[hooks[i]].push(modules[j][hooks[i]])
}
}
function emptyNodeAt (elm) {
return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm)
}
function createRmCb (childElm, listeners) {
function remove () {
if (--remove.listeners === 0) {
removeElement(childElm)
}
}
remove.listeners = listeners
return remove
}
function removeElement (el) {
const parent = nodeOps.parentNode(el)
nodeOps.removeChild(parent, el)
}
function createElm (vnode, insertedVnodeQueue) {
let i, elm
const data = vnode.data
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode)
// after calling the init hook, if the vnode is a child component
// it should've created a child instance and mounted it. the child
// component also has set the placeholder vnode's elm.
// in that case we can just return the element and be done.
if (isDef(i = vnode.child)) {
if (vnode.data.pendingInsert) {
insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert)
}
vnode.elm = vnode.child.$el
invokeCreateHooks(vnode, insertedVnodeQueue)
setScope(vnode)
return vnode.elm
}
}
const children = vnode.children
const tag = vnode.tag
if (isDef(tag)) {
if (process.env.NODE_ENV !== 'production') {
if (
!vnode.ns &&
!(config.ignoredElements && config.ignoredElements.indexOf(tag) > -1) &&
config.isUnknownElement(tag)
) {
warn(
'Unknown custom element: <' + tag + '> - did you ' +
'register the component correctly? For recursive components, ' +
'make sure to provide the "name" option.',
vnode.context
)
}
}
elm = vnode.elm = vnode.ns
? nodeOps.createElementNS(vnode.ns, tag)
: nodeOps.createElement(tag)
setScope(vnode)
if (Array.isArray(children)) {
for (i = 0; i < children.length; ++i) {
nodeOps.appendChild(elm, createElm(children[i], insertedVnodeQueue))
}
} else if (isPrimitive(vnode.text)) {
nodeOps.appendChild(elm, nodeOps.createTextNode(vnode.text))
}
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue)
}
} else {
elm = vnode.elm = nodeOps.createTextNode(vnode.text)
}
return vnode.elm
}
function invokeCreateHooks (vnode, insertedVnodeQueue) {
for (let i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, vnode)
}
i = vnode.data.hook // Reuse variable
if (isDef(i)) {
if (i.create) i.create(emptyNode, vnode)
if (i.insert) insertedVnodeQueue.push(vnode)
}
}
// set scope id attribute for scoped CSS.
// this is implemented as a special case to avoid the overhead
// of going through the normal attribute patching process.
function setScope (vnode) {
let i
if (isDef(i = vnode.host) && isDef(i = i.$options._scopeId)) {
nodeOps.setAttribute(vnode.elm, i, '')
}
if (isDef(i = vnode.context) && isDef(i = i.$options._scopeId)) {
nodeOps.setAttribute(vnode.elm, i, '')
}
}
function addVnodes (parentElm, before, vnodes, startIdx, endIdx, insertedVnodeQueue) {
for (; startIdx <= endIdx; ++startIdx) {
nodeOps.insertBefore(parentElm, createElm(vnodes[startIdx], insertedVnodeQueue), before)
}
}
function invokeDestroyHook (vnode) {
let i, j
const data = vnode.data
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.destroy)) i(vnode)
for (i = 0; i < cbs.destroy.length; ++i) cbs.destroy[i](vnode)
}
if (isDef(i = vnode.child) && !data.keepAlive) {
invokeDestroyHook(i._vnode)
}
if (isDef(i = vnode.children)) {
for (j = 0; j < vnode.children.length; ++j) {
invokeDestroyHook(vnode.children[j])
}
}
}
function removeVnodes (parentElm, vnodes, startIdx, endIdx) {
for (; startIdx <= endIdx; ++startIdx) {
const ch = vnodes[startIdx]
if (isDef(ch)) {
if (isDef(ch.tag)) {
invokeDestroyHook(ch)
removeAndInvokeRemoveHook(ch)
} else { // Text node
nodeOps.removeChild(parentElm, ch.elm)
}
}
}
}
function removeAndInvokeRemoveHook (vnode, rm) {
if (rm || isDef(vnode.data)) {
const listeners = cbs.remove.length + 1
if (!rm) {
// directly removing
rm = createRmCb(vnode.elm, listeners)
} else {
// we have a recursively passed down rm callback
// increase the listeners count
rm.listeners += listeners
}
// recursively invoke hooks on child component root node
if (isDef(i = vnode.child) && isDef(i = i._vnode) && isDef(i.data)) {
removeAndInvokeRemoveHook(i, rm)
}
for (i = 0; i < cbs.remove.length; ++i) {
cbs.remove[i](vnode, rm)
}
if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) {
i(vnode, rm)
} else {
rm()
}
} else {
removeElement(vnode.elm)
}
}
function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) {
let oldStartIdx = 0
let newStartIdx = 0
let oldEndIdx = oldCh.length - 1
let oldStartVnode = oldCh[0]
let oldEndVnode = oldCh[oldEndIdx]
let newEndIdx = newCh.length - 1
let newStartVnode = newCh[0]
let newEndVnode = newCh[newEndIdx]
let oldKeyToIdx, idxInOld, elmToMove, before
// removeOnly is a special flag used only by <transition-group>
// to ensure removed elements stay in correct relative positions
// during leaving transitions
const canMove = !removeOnly
while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
if (isUndef(oldStartVnode)) {
oldStartVnode = oldCh[++oldStartIdx] // Vnode has been moved left
} else if (isUndef(oldEndVnode)) {
oldEndVnode = oldCh[--oldEndIdx]
} else if (sameVnode(oldStartVnode, newStartVnode)) {
patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue)
oldStartVnode = oldCh[++oldStartIdx]
newStartVnode = newCh[++newStartIdx]
} else if (sameVnode(oldEndVnode, newEndVnode)) {
patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue)
oldEndVnode = oldCh[--oldEndIdx]
newEndVnode = newCh[--newEndIdx]
} else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right
patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue)
canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm))
oldStartVnode = oldCh[++oldStartIdx]
newEndVnode = newCh[--newEndIdx]
} else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left
patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue)
canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm)
oldEndVnode = oldCh[--oldEndIdx]
newStartVnode = newCh[++newStartIdx]
} else {
if (isUndef(oldKeyToIdx)) oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx)
idxInOld = isDef(newStartVnode.key)
? oldKeyToIdx[newStartVnode.key]
: newStartVnode.isStatic
? oldCh.indexOf(newStartVnode)
: null
if (isUndef(idxInOld) || idxInOld === -1) { // New element
nodeOps.insertBefore(parentElm, createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm)
newStartVnode = newCh[++newStartIdx]
} else {
elmToMove = oldCh[idxInOld]
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && !elmToMove) {
warn(
'It seems there are duplicate keys that is causing an update error. ' +
'Make sure each v-for item has a unique key.'
)
}
if (elmToMove.tag !== newStartVnode.tag) {
// same key but different element. treat as new element
nodeOps.insertBefore(parentElm, createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm)
newStartVnode = newCh[++newStartIdx]
} else {
patchVnode(elmToMove, newStartVnode, insertedVnodeQueue)
oldCh[idxInOld] = undefined
canMove && nodeOps.insertBefore(parentElm, newStartVnode.elm, oldStartVnode.elm)
newStartVnode = newCh[++newStartIdx]
}
}
}
}
if (oldStartIdx > oldEndIdx) {
before = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm
addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx, insertedVnodeQueue)
} else if (newStartIdx > newEndIdx) {
removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx)
}
}
function patchVnode (oldVnode, vnode, insertedVnodeQueue, removeOnly) {
if (oldVnode === vnode) return
let i, hook
const hasData = isDef(i = vnode.data)
if (hasData && isDef(hook = i.hook) && isDef(i = hook.prepatch)) {
i(oldVnode, vnode)
}
const elm = vnode.elm = oldVnode.elm
const oldCh = oldVnode.children
const ch = vnode.children
if (hasData) {
for (i = 0; i < cbs.update.length; ++i) cbs.update[i](oldVnode, vnode)
if (isDef(hook) && isDef(i = hook.update)) i(oldVnode, vnode)
}
if (isUndef(vnode.text)) {
if (isDef(oldCh) && isDef(ch)) {
if (oldCh !== ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly)
} else if (isDef(ch)) {
if (isDef(oldVnode.text)) nodeOps.setTextContent(elm, '')
addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue)
} else if (isDef(oldCh)) {
removeVnodes(elm, oldCh, 0, oldCh.length - 1)
} else if (isDef(oldVnode.text)) {
nodeOps.setTextContent(elm, '')
}
} else if (oldVnode.text !== vnode.text) {
nodeOps.setTextContent(elm, vnode.text)
}
if (hasData) {
for (i = 0; i < cbs.postpatch.length; ++i) cbs.postpatch[i](oldVnode, vnode)
if (isDef(hook) && isDef(i = hook.postpatch)) i(oldVnode, vnode)
}
}
function invokeInsertHook (vnode, queue, initial) {
// delay insert hooks for component root nodes, invoke them after the
// element is really inserted
if (initial && vnode.parent) {
vnode.parent.data.pendingInsert = queue
} else {
for (let i = 0; i < queue.length; ++i) {
queue[i].data.hook.insert(queue[i])
}
}
}
let bailed = false
function hydrate (elm, vnode, insertedVnodeQueue) {
if (process.env.NODE_ENV !== 'production') {
if (!assertNodeMatch(elm, vnode)) {
return false
}
}
vnode.elm = elm
const { tag, data, children } = vnode
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode, true /* hydrating */)
if (isDef(i = vnode.child)) {
// child component. it should have hydrated its own tree.
invokeCreateHooks(vnode, insertedVnodeQueue)
return true
}
}
if (isDef(tag)) {
if (isDef(children)) {
const childNodes = nodeOps.childNodes(elm)
let childrenMatch = true
if (childNodes.length !== children.length) {
childrenMatch = false
} else {
for (let i = 0; i < children.length; i++) {
if (!hydrate(childNodes[i], children[i], insertedVnodeQueue)) {
childrenMatch = false
break
}
}
}
if (!childrenMatch) {
if (process.env.NODE_ENV !== 'production' &&
typeof console !== 'undefined' &&
!bailed) {
bailed = true
console.warn('Parent: ', elm)
console.warn('Mismatching childNodes vs. VNodes: ', childNodes, children)
}
return false
}
}
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue)
}
}
return true
}
function assertNodeMatch (node, vnode) {
let match = true
if (!node) {
match = false
} else if (vnode.tag) {
match =
vnode.tag.indexOf('vue-component') === 0 ||
vnode.tag === nodeOps.tagName(node).toLowerCase()
} else {
match = _toString(vnode.text) === node.data
}
return match
}
return function patch (oldVnode, vnode, hydrating, removeOnly) {
let elm, parent
let isInitialPatch = false
const insertedVnodeQueue = []
if (!oldVnode) {
// empty mount, create new root element
isInitialPatch = true
createElm(vnode, insertedVnodeQueue)
} else {
const isRealElement = isDef(oldVnode.nodeType)
if (!isRealElement && sameVnode(oldVnode, vnode)) {
patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly)
} else {
if (isRealElement) {
// mounting to a real element
// check if this is server-rendered content and if we can perform
// a successful hydration.
if (oldVnode.hasAttribute('server-rendered')) {
oldVnode.removeAttribute('server-rendered')
hydrating = true
}
if (hydrating) {
if (hydrate(oldVnode, vnode, insertedVnodeQueue)) {
invokeInsertHook(vnode, insertedVnodeQueue, true)
return oldVnode
} else if (process.env.NODE_ENV !== 'production') {
warn(
'The client-side rendered virtual DOM tree is not matching ' +
'server-rendered content. This is likely caused by incorrect ' +
'HTML markup, for example nesting block-level elements inside ' +
'<p>, or missing <tbody>. Bailing hydration and performing ' +
'full client-side render.'
)
}
}
// either not server-rendered, or hydration failed.
// create an empty node and replace it
oldVnode = emptyNodeAt(oldVnode)
}
elm = oldVnode.elm
parent = nodeOps.parentNode(elm)
createElm(vnode, insertedVnodeQueue)
// component root element replaced.
// update parent placeholder node element.
if (vnode.parent) {
vnode.parent.elm = vnode.elm
for (let i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, vnode.parent)
}
}
if (parent !== null) {
nodeOps.insertBefore(parent, vnode.elm, nodeOps.nextSibling(elm))
removeVnodes(parent, [oldVnode], 0, 0)
} else if (isDef(oldVnode.tag)) {
invokeDestroyHook(oldVnode)
}
}
}
invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch)
return vnode.elm
}
}
| src/core/vdom/patch.js | 1 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.0005026964354328811,
0.00018005172023549676,
0.00016468028479721397,
0.00017035580822266638,
0.000048413374315714464
] |
{
"id": 0,
"code_window": [
" ns: string | void;\n",
" context: Component;\n",
" key: string | number | void;\n",
" parent?: VNodeWithData;\n",
" child?: Component;\n",
"}\n",
"\n",
"declare interface VNodeData {\n",
" key?: string | number;\n",
" slot?: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" isRootInsert: boolean;\n"
],
"file_path": "flow/vnode.js",
"type": "add",
"edit_start_line_idx": 30
} | import Vue from 'vue'
describe('Directive v-cloak', () => {
it('should be removed after compile', () => {
const el = document.createElement('div')
el.setAttribute('v-cloak', '')
const vm = new Vue({ el })
expect(vm.$el.hasAttribute('v-cloak')).toBe(false)
})
})
| test/unit/features/directives/cloak.spec.js | 0 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.00017847998242359608,
0.00017715376452542841,
0.00017582754662726074,
0.00017715376452542841,
0.0000013262178981676698
] |
{
"id": 0,
"code_window": [
" ns: string | void;\n",
" context: Component;\n",
" key: string | number | void;\n",
" parent?: VNodeWithData;\n",
" child?: Component;\n",
"}\n",
"\n",
"declare interface VNodeData {\n",
" key?: string | number;\n",
" slot?: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" isRootInsert: boolean;\n"
],
"file_path": "flow/vnode.js",
"type": "add",
"edit_start_line_idx": 30
} | import Vue from 'vue'
describe('Options name', () => {
it('should warn when giving instance a name', () => {
new Vue({
name: 'SuperVue'
}).$mount()
/* eslint-disable */
expect(`options "name" can only be used as a component definition option, not during instance creation.`)
.toHaveBeenWarned()
/* eslint-enable */
})
it('should contain itself in self components', () => {
const vm = Vue.extend({
name: 'SuperVue'
})
expect(vm.options.components['SuperVue']).toEqual(vm)
})
it('should warn when incorrect name given', () => {
Vue.extend({
name: 'Hyper*Vue'
})
/* eslint-disable */
expect(`Invalid component name: "Hyper*Vue". Component names can only contain alphanumeric characaters and the hyphen.`)
.toHaveBeenWarned()
/* eslint-enable */
})
it('when incorrect name given it should not contain itself in self components', () => {
const vm = Vue.extend({
name: 'Hyper*Vue'
})
expect(vm.options.components['Hyper*Vue']).toBeUndefined()
})
it('id should not override given name when using Vue.component', () => {
const SuperComponent = Vue.component('super-component', {
name: 'SuperVue'
})
expect(SuperComponent.options.components['SuperVue']).toEqual(SuperComponent)
expect(SuperComponent.options.components['super-component']).toEqual(SuperComponent)
})
})
| test/unit/features/options/name.spec.js | 0 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.00020208243222441524,
0.00017417983326595277,
0.00016054167645052075,
0.00016897227033041418,
0.000013239689906185959
] |
{
"id": 0,
"code_window": [
" ns: string | void;\n",
" context: Component;\n",
" key: string | number | void;\n",
" parent?: VNodeWithData;\n",
" child?: Component;\n",
"}\n",
"\n",
"declare interface VNodeData {\n",
" key?: string | number;\n",
" slot?: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" isRootInsert: boolean;\n"
],
"file_path": "flow/vnode.js",
"type": "add",
"edit_start_line_idx": 30
} | /* @flow */
import Vue from 'core/index'
import config from 'core/config'
import { extend, noop } from 'shared/util'
import { devtools, inBrowser } from 'core/util/index'
import { patch } from 'web/runtime/patch'
import platformDirectives from 'web/runtime/directives/index'
import platformComponents from 'web/runtime/components/index'
import {
query,
isUnknownElement,
isReservedTag,
getTagNamespace,
mustUseProp
} from 'web/util/index'
// install platform specific utils
Vue.config.isUnknownElement = isUnknownElement
Vue.config.isReservedTag = isReservedTag
Vue.config.getTagNamespace = getTagNamespace
Vue.config.mustUseProp = mustUseProp
// install platform runtime directives & components
extend(Vue.options.directives, platformDirectives)
extend(Vue.options.components, platformComponents)
// install platform patch function
Vue.prototype.__patch__ = config._isServer ? noop : patch
// wrap mount
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && !config._isServer ? query(el) : undefined
return this._mount(el, hydrating)
}
// devtools global hook
/* istanbul ignore next */
setTimeout(() => {
if (config.devtools) {
if (devtools) {
devtools.emit('init', Vue)
} else if (
process.env.NODE_ENV !== 'production' &&
inBrowser && /Chrome\/\d+/.test(window.navigator.userAgent)
) {
console.log(
'Download the Vue Devtools for a better development experience:\n' +
'https://github.com/vuejs/vue-devtools'
)
}
}
}, 0)
export default Vue
| src/entries/web-runtime.js | 0 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.00020751039846800268,
0.00017797712644096464,
0.00016972441517282277,
0.00017228140495717525,
0.000013293566553329583
] |
{
"id": 1,
"code_window": [
" nodeOps.removeChild(parent, el)\n",
" }\n",
"\n",
" function createElm (vnode, insertedVnodeQueue) {\n",
" let i, elm\n",
" const data = vnode.data\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" function createElm (vnode, insertedVnodeQueue, nested) {\n"
],
"file_path": "src/core/vdom/patch.js",
"type": "replace",
"edit_start_line_idx": 78
} | /* @flow */
export default class VNode {
tag: string | void;
data: VNodeData | void;
children: Array<VNode> | void;
text: string | void;
elm: Node | void;
ns: string | void;
context: Component | void;
host: ?Component;
key: string | number | void;
componentOptions: VNodeComponentOptions | void;
child: Component | void;
parent: VNode | void;
raw: ?boolean;
isStatic: ?boolean;
constructor (
tag?: string,
data?: VNodeData,
children?: Array<VNode> | void,
text?: string,
elm?: Node,
ns?: string | void,
context?: Component,
host?: ?Component,
componentOptions?: VNodeComponentOptions
) {
this.tag = tag
this.data = data
this.children = children
this.text = text
this.elm = elm
this.ns = ns
this.context = context
this.host = host
this.key = data && data.key
this.componentOptions = componentOptions
this.child = undefined
this.parent = undefined
this.raw = false
this.isStatic = false
// apply construct hook.
// this is applied during render, before patch happens.
// unlike other hooks, this is applied on both client and server.
const constructHook = data && data.hook && data.hook.construct
if (constructHook) {
constructHook(this)
}
}
}
export const emptyVNode = () => new VNode(undefined, undefined, undefined, '')
| src/core/vdom/vnode.js | 1 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.9957665205001831,
0.33160272240638733,
0.00016358897846657783,
0.0016308592166751623,
0.4676896631717682
] |
{
"id": 1,
"code_window": [
" nodeOps.removeChild(parent, el)\n",
" }\n",
"\n",
" function createElm (vnode, insertedVnodeQueue) {\n",
" let i, elm\n",
" const data = vnode.data\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" function createElm (vnode, insertedVnodeQueue, nested) {\n"
],
"file_path": "src/core/vdom/patch.js",
"type": "replace",
"edit_start_line_idx": 78
} | import Vue from 'vue'
import { compile } from 'entries/web-compiler'
import { getAndRemoveAttr } from 'compiler/helpers'
describe('compile options', () => {
it('should be compiled', () => {
const { render, staticRenderFns, errors } = compile(`
<div>
<input type="text" v-model="msg" required max="8" v-validate:field1.group1.group2>
</div>
`, {
directives: {
validate (el, dir) {
if (dir.name === 'validate' && dir.arg) {
el.validate = {
field: dir.arg,
groups: dir.modifiers ? Object.keys(dir.modifiers) : []
}
}
}
},
modules: [{
transformNode (el) {
el.validators = el.validators || []
const validators = ['required', 'min', 'max', 'pattern', 'maxlength', 'minlength']
validators.forEach(name => {
const rule = getAndRemoveAttr(el, name)
if (rule !== undefined) {
el.validators.push({ name, rule })
}
})
},
genData (el) {
let data = ''
if (el.validate) {
data += `validate:${JSON.stringify(el.validate)},`
}
if (el.validators) {
data += `validators:${JSON.stringify(el.validators)},`
}
return data
},
transformCode (el, code) {
// check
if (!el.validate || !el.validators) {
return code
}
// setup validation result props
const result = { dirty: false } // define something other prop
el.validators.forEach(validator => {
result[validator.name] = null
})
// generate code
return `_h('validate',{props:{
field:${JSON.stringify(el.validate.field)},
groups:${JSON.stringify(el.validate.groups)},
validators:${JSON.stringify(el.validators)},
result:${JSON.stringify(result)},
child:${code}}
})`
}
}]
})
expect(render).not.toBeUndefined()
expect(staticRenderFns).toEqual([])
expect(errors).toEqual([])
const renderFn = new Function(render)
const vm = new Vue({
data: {
msg: 'hello'
},
components: {
validate: {
props: ['field', 'groups', 'validators', 'result', 'child'],
render (h) {
return this.child
},
computed: {
valid () {
let ret = true
for (let i = 0; i > this.validators.length; i++) {
const { name } = this.validators[i]
if (!this.result[name]) {
ret = false
break
}
}
return ret
}
},
mounted () {
// initialize validation
const value = this.$el.value
this.validators.forEach(validator => {
const ret = this[validator.name](value, validator.rule)
this.result[validator.name] = ret
})
},
methods: {
// something validators logic
required (val) {
return val.length > 0
},
max (val, rule) {
return !(parseInt(val, 10) > parseInt(rule, 10))
}
}
}
},
render: renderFn,
staticRenderFns
}).$mount()
expect(vm.$el.innerHTML).toBe('<input type="text">')
expect(vm.$children[0].valid).toBe(true)
})
it('should collect errors', () => {
let compiled = compile('hello')
expect(compiled.errors.length).toBe(1)
expect(compiled.errors[0]).toContain('should contain exactly one root element')
compiled = compile('<div v-if="a----">{{ b++++ }}</div>')
expect(compiled.errors.length).toBe(2)
expect(compiled.errors[0]).toContain('invalid expression: v-if="a----"')
expect(compiled.errors[1]).toContain('invalid expression: {{ b++++ }}')
})
})
| test/unit/modules/compiler/compiler-options.spec.js | 0 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.9947150349617004,
0.07830159366130829,
0.00016638300439808518,
0.00017167544865515083,
0.2645834982395172
] |
{
"id": 1,
"code_window": [
" nodeOps.removeChild(parent, el)\n",
" }\n",
"\n",
" function createElm (vnode, insertedVnodeQueue) {\n",
" let i, elm\n",
" const data = vnode.data\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" function createElm (vnode, insertedVnodeQueue, nested) {\n"
],
"file_path": "src/core/vdom/patch.js",
"type": "replace",
"edit_start_line_idx": 78
} | /* not type checking this file because flow doesn't play well with Proxy */
import { warn, makeMap } from '../util/index'
let hasProxy, proxyHandlers, initProxy
if (process.env.NODE_ENV !== 'production') {
const allowedGlobals = makeMap(
'Infinity,undefined,NaN,isFinite,isNaN,' +
'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' +
'require,__webpack_require__' // for Webpack/Browserify
)
hasProxy =
typeof Proxy !== 'undefined' &&
Proxy.toString().match(/native code/)
proxyHandlers = {
has (target, key) {
const has = key in target
const isAllowedGlobal = allowedGlobals(key)
if (!has && !isAllowedGlobal) {
warn(
`Trying to access non-existent property "${key}" while rendering. ` +
`Make sure to declare reactive data properties in the data option.`,
target
)
}
return !isAllowedGlobal
}
}
initProxy = function initProxy (vm) {
if (hasProxy) {
vm._renderProxy = new Proxy(vm, proxyHandlers)
} else {
vm._renderProxy = vm
}
}
}
export { initProxy }
| src/core/instance/proxy.js | 0 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.0001762147294357419,
0.00017073977505788207,
0.00016871001571416855,
0.00016960292123258114,
0.0000028116351131757256
] |
{
"id": 1,
"code_window": [
" nodeOps.removeChild(parent, el)\n",
" }\n",
"\n",
" function createElm (vnode, insertedVnodeQueue) {\n",
" let i, elm\n",
" const data = vnode.data\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" function createElm (vnode, insertedVnodeQueue, nested) {\n"
],
"file_path": "src/core/vdom/patch.js",
"type": "replace",
"edit_start_line_idx": 78
} | import Vue from 'vue'
describe('Options lifecyce hooks', () => {
let spy
beforeEach(() => {
spy = jasmine.createSpy('hook')
})
describe('beforeCreate', () => {
it('should allow modifying options', () => {
const vm = new Vue({
data: {
a: 1
},
beforeCreate () {
spy()
expect(this.a).toBeUndefined()
this.$options.computed = {
b () {
return this.a + 1
}
}
}
})
expect(spy).toHaveBeenCalled()
expect(vm.b).toBe(2)
})
})
describe('created', () => {
it('should have completed observation', () => {
new Vue({
data: {
a: 1
},
created () {
expect(this.a).toBe(1)
spy()
}
})
expect(spy).toHaveBeenCalled()
})
})
describe('beforeMount', () => {
it('should not have mounted', () => {
const vm = new Vue({
beforeMount () {
spy()
expect(this._isMounted).toBe(false)
expect(this.$el).toBeUndefined() // due to empty mount
expect(this._vnode).toBeNull()
expect(this._watcher).toBeNull()
}
})
expect(spy).not.toHaveBeenCalled()
vm.$mount()
expect(spy).toHaveBeenCalled()
})
})
describe('mounted', () => {
it('should have mounted', () => {
const vm = new Vue({
template: '<div></div>',
mounted () {
spy()
expect(this._isMounted).toBe(true)
expect(this.$el.tagName).toBe('DIV')
expect(this._vnode.tag).toBe('div')
}
})
expect(spy).not.toHaveBeenCalled()
vm.$mount()
expect(spy).toHaveBeenCalled()
})
it('should mount child parent in correct order', () => {
const calls = []
new Vue({
template: '<div><test></test><div>',
mounted () {
calls.push('parent')
},
components: {
test: {
template: '<nested></nested>',
mounted () {
expect(this.$el.parentNode).toBeTruthy()
calls.push('child')
},
components: {
nested: {
template: '<div></div>',
mounted () {
expect(this.$el.parentNode).toBeTruthy()
calls.push('nested')
}
}
}
}
}
}).$mount()
expect(calls).toEqual(['nested', 'child', 'parent'])
})
})
describe('beforeUpdate', () => {
it('should be called before update', done => {
const vm = new Vue({
template: '<div>{{ msg }}</div>',
data: { msg: 'foo' },
beforeUpdate () {
spy()
expect(this.$el.textContent).toBe('foo')
}
}).$mount()
expect(spy).not.toHaveBeenCalled()
vm.msg = 'bar'
expect(spy).not.toHaveBeenCalled() // should be async
waitForUpdate(() => {
expect(spy).toHaveBeenCalled()
}).then(done)
})
})
describe('updated', () => {
it('should be called after update', done => {
const vm = new Vue({
template: '<div>{{ msg }}</div>',
data: { msg: 'foo' },
updated () {
spy()
expect(this.$el.textContent).toBe('bar')
}
}).$mount()
expect(spy).not.toHaveBeenCalled()
vm.msg = 'bar'
expect(spy).not.toHaveBeenCalled() // should be async
waitForUpdate(() => {
expect(spy).toHaveBeenCalled()
}).then(done)
})
})
describe('beforeDestroy', () => {
it('should be called before destroy', () => {
const vm = new Vue({
beforeDestroy () {
spy()
expect(this._isBeingDestroyed).toBe(false)
expect(this._isDestroyed).toBe(false)
}
}).$mount()
expect(spy).not.toHaveBeenCalled()
vm.$destroy()
vm.$destroy()
expect(spy).toHaveBeenCalled()
expect(spy.calls.count()).toBe(1)
})
})
describe('destroyed', () => {
it('should be called after destroy', () => {
const vm = new Vue({
destroyed () {
spy()
expect(this._isBeingDestroyed).toBe(true)
expect(this._isDestroyed).toBe(true)
}
}).$mount()
expect(spy).not.toHaveBeenCalled()
vm.$destroy()
vm.$destroy()
expect(spy).toHaveBeenCalled()
expect(spy.calls.count()).toBe(1)
})
})
})
| test/unit/features/options/lifecycle.spec.js | 0 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.0005522794090211391,
0.00021380011457949877,
0.00016428162052761763,
0.00017250500968657434,
0.0001118699146900326
] |
{
"id": 2,
"code_window": [
" let i, elm\n",
" const data = vnode.data\n",
" if (isDef(data)) {\n",
" if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode)\n",
" // after calling the init hook, if the vnode is a child component\n",
" // it should've created a child instance and mounted it. the child\n",
" // component also has set the placeholder vnode's elm.\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" vnode.isRootInsert = !nested\n"
],
"file_path": "src/core/vdom/patch.js",
"type": "add",
"edit_start_line_idx": 81
} | /* @flow */
export default class VNode {
tag: string | void;
data: VNodeData | void;
children: Array<VNode> | void;
text: string | void;
elm: Node | void;
ns: string | void;
context: Component | void;
host: ?Component;
key: string | number | void;
componentOptions: VNodeComponentOptions | void;
child: Component | void;
parent: VNode | void;
raw: ?boolean;
isStatic: ?boolean;
constructor (
tag?: string,
data?: VNodeData,
children?: Array<VNode> | void,
text?: string,
elm?: Node,
ns?: string | void,
context?: Component,
host?: ?Component,
componentOptions?: VNodeComponentOptions
) {
this.tag = tag
this.data = data
this.children = children
this.text = text
this.elm = elm
this.ns = ns
this.context = context
this.host = host
this.key = data && data.key
this.componentOptions = componentOptions
this.child = undefined
this.parent = undefined
this.raw = false
this.isStatic = false
// apply construct hook.
// this is applied during render, before patch happens.
// unlike other hooks, this is applied on both client and server.
const constructHook = data && data.hook && data.hook.construct
if (constructHook) {
constructHook(this)
}
}
}
export const emptyVNode = () => new VNode(undefined, undefined, undefined, '')
| src/core/vdom/vnode.js | 1 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.8509565591812134,
0.16856467723846436,
0.00016603594121988863,
0.0008606570772826672,
0.31057143211364746
] |
{
"id": 2,
"code_window": [
" let i, elm\n",
" const data = vnode.data\n",
" if (isDef(data)) {\n",
" if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode)\n",
" // after calling the init hook, if the vnode is a child component\n",
" // it should've created a child instance and mounted it. the child\n",
" // component also has set the placeholder vnode's elm.\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" vnode.isRootInsert = !nested\n"
],
"file_path": "src/core/vdom/patch.js",
"type": "add",
"edit_start_line_idx": 81
} | The MIT License (MIT)
Copyright (c) 2013-2016 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.
| LICENSE | 0 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.00017809460405260324,
0.0001738932478474453,
0.00017034340999089181,
0.0001732417440507561,
0.00000319777018376044
] |
{
"id": 2,
"code_window": [
" let i, elm\n",
" const data = vnode.data\n",
" if (isDef(data)) {\n",
" if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode)\n",
" // after calling the init hook, if the vnode is a child component\n",
" // it should've created a child instance and mounted it. the child\n",
" // component also has set the placeholder vnode's elm.\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" vnode.isRootInsert = !nested\n"
],
"file_path": "src/core/vdom/patch.js",
"type": "add",
"edit_start_line_idx": 81
} | import Vue from 'vue'
describe('Directive v-cloak', () => {
it('should be removed after compile', () => {
const el = document.createElement('div')
el.setAttribute('v-cloak', '')
const vm = new Vue({ el })
expect(vm.$el.hasAttribute('v-cloak')).toBe(false)
})
})
| test/unit/features/directives/cloak.spec.js | 0 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.00025317713152617216,
0.00021260556241031736,
0.00017203399329446256,
0.00021260556241031736,
0.0000405715691158548
] |
{
"id": 2,
"code_window": [
" let i, elm\n",
" const data = vnode.data\n",
" if (isDef(data)) {\n",
" if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode)\n",
" // after calling the init hook, if the vnode is a child component\n",
" // it should've created a child instance and mounted it. the child\n",
" // component also has set the placeholder vnode's elm.\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" vnode.isRootInsert = !nested\n"
],
"file_path": "src/core/vdom/patch.js",
"type": "add",
"edit_start_line_idx": 81
} | /* @flow */
import type Watcher from './watcher'
import config from '../config'
import {
warn,
nextTick,
devtools
} from '../util/index'
const queue: Array<Watcher> = []
let has: { [key: number]: ?true } = {}
let circular: { [key: number]: number } = {}
let waiting = false
let flushing = false
let index = 0
/**
* Reset the scheduler's state.
*/
function resetSchedulerState () {
queue.length = 0
has = {}
if (process.env.NODE_ENV !== 'production') {
circular = {}
}
waiting = flushing = false
}
/**
* Flush both queues and run the watchers.
*/
function flushSchedulerQueue () {
flushing = true
// Sort queue before flush.
// This ensures that:
// 1. Components are updated from parent to child. (because parent is always
// created before the child)
// 2. A component's user watchers are run before its render watcher (because
// user watchers are created before the render watcher)
// 3. If a component is destroyed during a parent component's watcher run,
// its watchers can be skipped.
queue.sort((a, b) => a.id - b.id)
// do not cache length because more watchers might be pushed
// as we run existing watchers
for (index = 0; index < queue.length; index++) {
const watcher = queue[index]
const id = watcher.id
has[id] = null
watcher.run()
// in dev build, check and stop circular updates.
if (process.env.NODE_ENV !== 'production' && has[id] != null) {
circular[id] = (circular[id] || 0) + 1
if (circular[id] > config._maxUpdateCount) {
warn(
'You may have an infinite update loop ' + (
watcher.user
? `in watcher with expression "${watcher.expression}"`
: `in a component render function.`
),
watcher.vm
)
break
}
}
}
// devtool hook
/* istanbul ignore if */
if (devtools && config.devtools) {
devtools.emit('flush')
}
resetSchedulerState()
}
/**
* Push a watcher into the watcher queue.
* Jobs with duplicate IDs will be skipped unless it's
* pushed when the queue is being flushed.
*/
export function queueWatcher (watcher: Watcher) {
const id = watcher.id
if (has[id] == null) {
has[id] = true
if (!flushing) {
queue.push(watcher)
} else {
// if already flushing, splice the watcher based on its id
// if already past its id, it will be run next immediately.
let i = queue.length - 1
while (i >= 0 && queue[i].id > watcher.id) {
i--
}
queue.splice(Math.max(i, index) + 1, 0, watcher)
}
// queue the flush
if (!waiting) {
waiting = true
nextTick(flushSchedulerQueue)
}
}
}
| src/core/observer/scheduler.js | 0 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.004484512843191624,
0.0005624814657494426,
0.0001658691471675411,
0.00017109172767959535,
0.001240257639437914
] |
{
"id": 3,
"code_window": [
" : nodeOps.createElement(tag)\n",
" setScope(vnode)\n",
" if (Array.isArray(children)) {\n",
" for (i = 0; i < children.length; ++i) {\n",
" nodeOps.appendChild(elm, createElm(children[i], insertedVnodeQueue))\n",
" }\n",
" } else if (isPrimitive(vnode.text)) {\n",
" nodeOps.appendChild(elm, nodeOps.createTextNode(vnode.text))\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" nodeOps.appendChild(elm, createElm(children[i], insertedVnodeQueue, true))\n"
],
"file_path": "src/core/vdom/patch.js",
"type": "replace",
"edit_start_line_idx": 120
} | /**
* Virtual DOM implementation based on Snabbdom by
* Simon Friis Vindum (@paldepind)
* with custom modifications.
*
* Not type-checking this because this file is perf-critical and the cost
* of making flow understand it is not worth it.
*/
import config from '../config'
import VNode from './vnode'
import { isPrimitive, _toString, warn } from '../util/index'
const emptyData = {}
const emptyNode = new VNode('', emptyData, [])
const hooks = ['create', 'update', 'postpatch', 'remove', 'destroy']
function isUndef (s) {
return s == null
}
function isDef (s) {
return s != null
}
function sameVnode (vnode1, vnode2) {
if (vnode1.isStatic || vnode2.isStatic) {
return vnode1 === vnode2
}
return (
vnode1.key === vnode2.key &&
vnode1.tag === vnode2.tag &&
!vnode1.data === !vnode2.data
)
}
function createKeyToOldIdx (children, beginIdx, endIdx) {
let i, key
const map = {}
for (i = beginIdx; i <= endIdx; ++i) {
key = children[i].key
if (isDef(key)) map[key] = i
}
return map
}
export function createPatchFunction (backend) {
let i, j
const cbs = {}
const { modules, nodeOps } = backend
for (i = 0; i < hooks.length; ++i) {
cbs[hooks[i]] = []
for (j = 0; j < modules.length; ++j) {
if (modules[j][hooks[i]] !== undefined) cbs[hooks[i]].push(modules[j][hooks[i]])
}
}
function emptyNodeAt (elm) {
return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm)
}
function createRmCb (childElm, listeners) {
function remove () {
if (--remove.listeners === 0) {
removeElement(childElm)
}
}
remove.listeners = listeners
return remove
}
function removeElement (el) {
const parent = nodeOps.parentNode(el)
nodeOps.removeChild(parent, el)
}
function createElm (vnode, insertedVnodeQueue) {
let i, elm
const data = vnode.data
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode)
// after calling the init hook, if the vnode is a child component
// it should've created a child instance and mounted it. the child
// component also has set the placeholder vnode's elm.
// in that case we can just return the element and be done.
if (isDef(i = vnode.child)) {
if (vnode.data.pendingInsert) {
insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert)
}
vnode.elm = vnode.child.$el
invokeCreateHooks(vnode, insertedVnodeQueue)
setScope(vnode)
return vnode.elm
}
}
const children = vnode.children
const tag = vnode.tag
if (isDef(tag)) {
if (process.env.NODE_ENV !== 'production') {
if (
!vnode.ns &&
!(config.ignoredElements && config.ignoredElements.indexOf(tag) > -1) &&
config.isUnknownElement(tag)
) {
warn(
'Unknown custom element: <' + tag + '> - did you ' +
'register the component correctly? For recursive components, ' +
'make sure to provide the "name" option.',
vnode.context
)
}
}
elm = vnode.elm = vnode.ns
? nodeOps.createElementNS(vnode.ns, tag)
: nodeOps.createElement(tag)
setScope(vnode)
if (Array.isArray(children)) {
for (i = 0; i < children.length; ++i) {
nodeOps.appendChild(elm, createElm(children[i], insertedVnodeQueue))
}
} else if (isPrimitive(vnode.text)) {
nodeOps.appendChild(elm, nodeOps.createTextNode(vnode.text))
}
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue)
}
} else {
elm = vnode.elm = nodeOps.createTextNode(vnode.text)
}
return vnode.elm
}
function invokeCreateHooks (vnode, insertedVnodeQueue) {
for (let i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, vnode)
}
i = vnode.data.hook // Reuse variable
if (isDef(i)) {
if (i.create) i.create(emptyNode, vnode)
if (i.insert) insertedVnodeQueue.push(vnode)
}
}
// set scope id attribute for scoped CSS.
// this is implemented as a special case to avoid the overhead
// of going through the normal attribute patching process.
function setScope (vnode) {
let i
if (isDef(i = vnode.host) && isDef(i = i.$options._scopeId)) {
nodeOps.setAttribute(vnode.elm, i, '')
}
if (isDef(i = vnode.context) && isDef(i = i.$options._scopeId)) {
nodeOps.setAttribute(vnode.elm, i, '')
}
}
function addVnodes (parentElm, before, vnodes, startIdx, endIdx, insertedVnodeQueue) {
for (; startIdx <= endIdx; ++startIdx) {
nodeOps.insertBefore(parentElm, createElm(vnodes[startIdx], insertedVnodeQueue), before)
}
}
function invokeDestroyHook (vnode) {
let i, j
const data = vnode.data
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.destroy)) i(vnode)
for (i = 0; i < cbs.destroy.length; ++i) cbs.destroy[i](vnode)
}
if (isDef(i = vnode.child) && !data.keepAlive) {
invokeDestroyHook(i._vnode)
}
if (isDef(i = vnode.children)) {
for (j = 0; j < vnode.children.length; ++j) {
invokeDestroyHook(vnode.children[j])
}
}
}
function removeVnodes (parentElm, vnodes, startIdx, endIdx) {
for (; startIdx <= endIdx; ++startIdx) {
const ch = vnodes[startIdx]
if (isDef(ch)) {
if (isDef(ch.tag)) {
invokeDestroyHook(ch)
removeAndInvokeRemoveHook(ch)
} else { // Text node
nodeOps.removeChild(parentElm, ch.elm)
}
}
}
}
function removeAndInvokeRemoveHook (vnode, rm) {
if (rm || isDef(vnode.data)) {
const listeners = cbs.remove.length + 1
if (!rm) {
// directly removing
rm = createRmCb(vnode.elm, listeners)
} else {
// we have a recursively passed down rm callback
// increase the listeners count
rm.listeners += listeners
}
// recursively invoke hooks on child component root node
if (isDef(i = vnode.child) && isDef(i = i._vnode) && isDef(i.data)) {
removeAndInvokeRemoveHook(i, rm)
}
for (i = 0; i < cbs.remove.length; ++i) {
cbs.remove[i](vnode, rm)
}
if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) {
i(vnode, rm)
} else {
rm()
}
} else {
removeElement(vnode.elm)
}
}
function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) {
let oldStartIdx = 0
let newStartIdx = 0
let oldEndIdx = oldCh.length - 1
let oldStartVnode = oldCh[0]
let oldEndVnode = oldCh[oldEndIdx]
let newEndIdx = newCh.length - 1
let newStartVnode = newCh[0]
let newEndVnode = newCh[newEndIdx]
let oldKeyToIdx, idxInOld, elmToMove, before
// removeOnly is a special flag used only by <transition-group>
// to ensure removed elements stay in correct relative positions
// during leaving transitions
const canMove = !removeOnly
while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
if (isUndef(oldStartVnode)) {
oldStartVnode = oldCh[++oldStartIdx] // Vnode has been moved left
} else if (isUndef(oldEndVnode)) {
oldEndVnode = oldCh[--oldEndIdx]
} else if (sameVnode(oldStartVnode, newStartVnode)) {
patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue)
oldStartVnode = oldCh[++oldStartIdx]
newStartVnode = newCh[++newStartIdx]
} else if (sameVnode(oldEndVnode, newEndVnode)) {
patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue)
oldEndVnode = oldCh[--oldEndIdx]
newEndVnode = newCh[--newEndIdx]
} else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right
patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue)
canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm))
oldStartVnode = oldCh[++oldStartIdx]
newEndVnode = newCh[--newEndIdx]
} else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left
patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue)
canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm)
oldEndVnode = oldCh[--oldEndIdx]
newStartVnode = newCh[++newStartIdx]
} else {
if (isUndef(oldKeyToIdx)) oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx)
idxInOld = isDef(newStartVnode.key)
? oldKeyToIdx[newStartVnode.key]
: newStartVnode.isStatic
? oldCh.indexOf(newStartVnode)
: null
if (isUndef(idxInOld) || idxInOld === -1) { // New element
nodeOps.insertBefore(parentElm, createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm)
newStartVnode = newCh[++newStartIdx]
} else {
elmToMove = oldCh[idxInOld]
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && !elmToMove) {
warn(
'It seems there are duplicate keys that is causing an update error. ' +
'Make sure each v-for item has a unique key.'
)
}
if (elmToMove.tag !== newStartVnode.tag) {
// same key but different element. treat as new element
nodeOps.insertBefore(parentElm, createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm)
newStartVnode = newCh[++newStartIdx]
} else {
patchVnode(elmToMove, newStartVnode, insertedVnodeQueue)
oldCh[idxInOld] = undefined
canMove && nodeOps.insertBefore(parentElm, newStartVnode.elm, oldStartVnode.elm)
newStartVnode = newCh[++newStartIdx]
}
}
}
}
if (oldStartIdx > oldEndIdx) {
before = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm
addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx, insertedVnodeQueue)
} else if (newStartIdx > newEndIdx) {
removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx)
}
}
function patchVnode (oldVnode, vnode, insertedVnodeQueue, removeOnly) {
if (oldVnode === vnode) return
let i, hook
const hasData = isDef(i = vnode.data)
if (hasData && isDef(hook = i.hook) && isDef(i = hook.prepatch)) {
i(oldVnode, vnode)
}
const elm = vnode.elm = oldVnode.elm
const oldCh = oldVnode.children
const ch = vnode.children
if (hasData) {
for (i = 0; i < cbs.update.length; ++i) cbs.update[i](oldVnode, vnode)
if (isDef(hook) && isDef(i = hook.update)) i(oldVnode, vnode)
}
if (isUndef(vnode.text)) {
if (isDef(oldCh) && isDef(ch)) {
if (oldCh !== ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly)
} else if (isDef(ch)) {
if (isDef(oldVnode.text)) nodeOps.setTextContent(elm, '')
addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue)
} else if (isDef(oldCh)) {
removeVnodes(elm, oldCh, 0, oldCh.length - 1)
} else if (isDef(oldVnode.text)) {
nodeOps.setTextContent(elm, '')
}
} else if (oldVnode.text !== vnode.text) {
nodeOps.setTextContent(elm, vnode.text)
}
if (hasData) {
for (i = 0; i < cbs.postpatch.length; ++i) cbs.postpatch[i](oldVnode, vnode)
if (isDef(hook) && isDef(i = hook.postpatch)) i(oldVnode, vnode)
}
}
function invokeInsertHook (vnode, queue, initial) {
// delay insert hooks for component root nodes, invoke them after the
// element is really inserted
if (initial && vnode.parent) {
vnode.parent.data.pendingInsert = queue
} else {
for (let i = 0; i < queue.length; ++i) {
queue[i].data.hook.insert(queue[i])
}
}
}
let bailed = false
function hydrate (elm, vnode, insertedVnodeQueue) {
if (process.env.NODE_ENV !== 'production') {
if (!assertNodeMatch(elm, vnode)) {
return false
}
}
vnode.elm = elm
const { tag, data, children } = vnode
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode, true /* hydrating */)
if (isDef(i = vnode.child)) {
// child component. it should have hydrated its own tree.
invokeCreateHooks(vnode, insertedVnodeQueue)
return true
}
}
if (isDef(tag)) {
if (isDef(children)) {
const childNodes = nodeOps.childNodes(elm)
let childrenMatch = true
if (childNodes.length !== children.length) {
childrenMatch = false
} else {
for (let i = 0; i < children.length; i++) {
if (!hydrate(childNodes[i], children[i], insertedVnodeQueue)) {
childrenMatch = false
break
}
}
}
if (!childrenMatch) {
if (process.env.NODE_ENV !== 'production' &&
typeof console !== 'undefined' &&
!bailed) {
bailed = true
console.warn('Parent: ', elm)
console.warn('Mismatching childNodes vs. VNodes: ', childNodes, children)
}
return false
}
}
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue)
}
}
return true
}
function assertNodeMatch (node, vnode) {
let match = true
if (!node) {
match = false
} else if (vnode.tag) {
match =
vnode.tag.indexOf('vue-component') === 0 ||
vnode.tag === nodeOps.tagName(node).toLowerCase()
} else {
match = _toString(vnode.text) === node.data
}
return match
}
return function patch (oldVnode, vnode, hydrating, removeOnly) {
let elm, parent
let isInitialPatch = false
const insertedVnodeQueue = []
if (!oldVnode) {
// empty mount, create new root element
isInitialPatch = true
createElm(vnode, insertedVnodeQueue)
} else {
const isRealElement = isDef(oldVnode.nodeType)
if (!isRealElement && sameVnode(oldVnode, vnode)) {
patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly)
} else {
if (isRealElement) {
// mounting to a real element
// check if this is server-rendered content and if we can perform
// a successful hydration.
if (oldVnode.hasAttribute('server-rendered')) {
oldVnode.removeAttribute('server-rendered')
hydrating = true
}
if (hydrating) {
if (hydrate(oldVnode, vnode, insertedVnodeQueue)) {
invokeInsertHook(vnode, insertedVnodeQueue, true)
return oldVnode
} else if (process.env.NODE_ENV !== 'production') {
warn(
'The client-side rendered virtual DOM tree is not matching ' +
'server-rendered content. This is likely caused by incorrect ' +
'HTML markup, for example nesting block-level elements inside ' +
'<p>, or missing <tbody>. Bailing hydration and performing ' +
'full client-side render.'
)
}
}
// either not server-rendered, or hydration failed.
// create an empty node and replace it
oldVnode = emptyNodeAt(oldVnode)
}
elm = oldVnode.elm
parent = nodeOps.parentNode(elm)
createElm(vnode, insertedVnodeQueue)
// component root element replaced.
// update parent placeholder node element.
if (vnode.parent) {
vnode.parent.elm = vnode.elm
for (let i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, vnode.parent)
}
}
if (parent !== null) {
nodeOps.insertBefore(parent, vnode.elm, nodeOps.nextSibling(elm))
removeVnodes(parent, [oldVnode], 0, 0)
} else if (isDef(oldVnode.tag)) {
invokeDestroyHook(oldVnode)
}
}
}
invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch)
return vnode.elm
}
}
| src/core/vdom/patch.js | 1 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.9976485371589661,
0.19545312225818634,
0.00016396188584621996,
0.003981243818998337,
0.3748013973236084
] |
{
"id": 3,
"code_window": [
" : nodeOps.createElement(tag)\n",
" setScope(vnode)\n",
" if (Array.isArray(children)) {\n",
" for (i = 0; i < children.length; ++i) {\n",
" nodeOps.appendChild(elm, createElm(children[i], insertedVnodeQueue))\n",
" }\n",
" } else if (isPrimitive(vnode.text)) {\n",
" nodeOps.appendChild(elm, nodeOps.createTextNode(vnode.text))\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" nodeOps.appendChild(elm, createElm(children[i], insertedVnodeQueue, true))\n"
],
"file_path": "src/core/vdom/patch.js",
"type": "replace",
"edit_start_line_idx": 120
} | /* @flow */
import { addHandler, addProp, getBindingAttr } from 'compiler/helpers'
let warn
export default function model (
el: ASTElement,
dir: ASTDirective,
_warn: Function
): ?boolean {
warn = _warn
const value = dir.value
const modifiers = dir.modifiers
if (el.tag === 'select') {
return genSelect(el, value)
} else {
switch (el.attrsMap.type) {
case 'checkbox':
genCheckboxModel(el, value)
break
case 'radio':
genRadioModel(el, value)
break
default:
return genDefaultModel(el, value, modifiers)
}
}
}
function genCheckboxModel (el: ASTElement, value: ?string) {
if (process.env.NODE_ENV !== 'production' &&
el.attrsMap.checked != null) {
warn(
`<${el.tag} v-model="${value}" checked>:\n` +
`inline checked attributes will be ignored when using v-model. ` +
'Declare initial values in the component\'s data option instead.'
)
}
const valueBinding = getBindingAttr(el, 'value')
const trueValueBinding = getBindingAttr(el, 'true-value') || 'true'
const falseValueBinding = getBindingAttr(el, 'false-value') || 'false'
addProp(el, 'checked',
`Array.isArray(${value})` +
`?(${value}).indexOf(${valueBinding})>-1` +
`:(${value})===(${trueValueBinding})`
)
addHandler(el, 'change',
`var $$a=${value},` +
'$$el=$event.target,' +
`$$c=$$el.checked?(${trueValueBinding}):(${falseValueBinding});` +
'if(Array.isArray($$a)){' +
`var $$v=${valueBinding},` +
'$$i=$$a.indexOf($$v);' +
`if($$c){$$i<0&&(${value}=$$a.concat($$v))}` +
`else{$$i>-1&&(${value}=$$a.slice(0,$$i).concat($$a.slice($$i+1)))}` +
`}else{${value}=$$c}`
)
}
function genRadioModel (el: ASTElement, value: ?string) {
if (process.env.NODE_ENV !== 'production' &&
el.attrsMap.checked != null) {
warn(
`<${el.tag} v-model="${value}" checked>:\n` +
`inline checked attributes will be ignored when using v-model. ` +
'Declare initial values in the component\'s data option instead.'
)
}
const valueBinding = getBindingAttr(el, 'value')
addProp(el, 'checked', `(${value})===(${valueBinding})`)
addHandler(el, 'change', `${value}=${valueBinding}`)
}
function genDefaultModel (
el: ASTElement,
value: ?string,
modifiers: ?Object
): ?boolean {
if (process.env.NODE_ENV !== 'production') {
if (el.tag === 'input' && el.attrsMap.value) {
warn(
`<${el.tag} v-model="${value}" value="${el.attrsMap.value}">:\n` +
'inline value attributes will be ignored when using v-model. ' +
'Declare initial values in the component\'s data option instead.'
)
}
if (el.tag === 'textarea' && el.children.length) {
warn(
`<textarea v-model="${value}">:\n` +
'inline content inside <textarea> will be ignored when using v-model. ' +
'Declare initial values in the component\'s data option instead.'
)
}
}
const type = el.attrsMap.type
const { lazy, number, trim } = modifiers || {}
const event = lazy ? 'change' : 'input'
const needCompositionGuard = !lazy && type !== 'range'
const isNative = el.tag === 'input' || el.tag === 'textarea'
const valueExpression = isNative
? `$event.target.value${trim ? '.trim()' : ''}`
: `$event`
let code = number || type === 'number'
? `${value}=_n(${valueExpression})`
: `${value}=${valueExpression}`
if (isNative && needCompositionGuard) {
code = `if($event.target.composing)return;${code}`
}
addProp(el, 'value', isNative ? `_s(${value})` : `(${value})`)
addHandler(el, event, code)
if (needCompositionGuard) {
// need runtime directive code to help with composition events
return true
}
}
function genSelect (el: ASTElement, value: ?string) {
if (process.env.NODE_ENV !== 'production') {
el.children.some(checkOptionWarning)
}
const code = `${value}=Array.prototype.filter` +
`.call($event.target.options,function(o){return o.selected})` +
`.map(function(o){return "_value" in o ? o._value : o.value})` +
(el.attrsMap.multiple == null ? '[0]' : '')
addHandler(el, 'change', code)
// need runtime to help with possible dynamically generated options
return true
}
function checkOptionWarning (option: ASTNode) {
if (option.type === 1 &&
option.tag === 'option' &&
option.attrsMap.selected != null) {
const parentModel = option.parent &&
option.parent.type === 1 &&
option.parent.attrsMap['v-model']
warn(
`<select v-model="${parentModel}">:\n` +
'inline selected attributes on <option> will be ignored when using v-model. ' +
'Declare initial values in the component\'s data option instead.'
)
return true
}
}
| src/platforms/web/compiler/directives/model.js | 0 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.00017587431648280472,
0.0001711965014692396,
0.00016527663683518767,
0.00017104443395510316,
0.000002611279342090711
] |
{
"id": 3,
"code_window": [
" : nodeOps.createElement(tag)\n",
" setScope(vnode)\n",
" if (Array.isArray(children)) {\n",
" for (i = 0; i < children.length; ++i) {\n",
" nodeOps.appendChild(elm, createElm(children[i], insertedVnodeQueue))\n",
" }\n",
" } else if (isPrimitive(vnode.text)) {\n",
" nodeOps.appendChild(elm, nodeOps.createTextNode(vnode.text))\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" nodeOps.appendChild(elm, createElm(children[i], insertedVnodeQueue, true))\n"
],
"file_path": "src/core/vdom/patch.js",
"type": "replace",
"edit_start_line_idx": 120
} | import klass from './class'
import style from './style'
export default [
klass,
style
]
| src/platforms/web/compiler/modules/index.js | 0 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.00017689974629320204,
0.00017689974629320204,
0.00017689974629320204,
0.00017689974629320204,
0
] |
{
"id": 3,
"code_window": [
" : nodeOps.createElement(tag)\n",
" setScope(vnode)\n",
" if (Array.isArray(children)) {\n",
" for (i = 0; i < children.length; ++i) {\n",
" nodeOps.appendChild(elm, createElm(children[i], insertedVnodeQueue))\n",
" }\n",
" } else if (isPrimitive(vnode.text)) {\n",
" nodeOps.appendChild(elm, nodeOps.createTextNode(vnode.text))\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" nodeOps.appendChild(elm, createElm(children[i], insertedVnodeQueue, true))\n"
],
"file_path": "src/core/vdom/patch.js",
"type": "replace",
"edit_start_line_idx": 120
} | import Vue from 'vue'
describe('Directive v-on', () => {
let vm, spy, spy2, el
beforeEach(() => {
spy = jasmine.createSpy()
spy2 = jasmine.createSpy()
el = document.createElement('div')
document.body.appendChild(el)
})
afterEach(() => {
document.body.removeChild(vm.$el)
})
it('should bind event to a method', () => {
vm = new Vue({
el,
template: '<div v-on:click="foo"></div>',
methods: { foo: spy }
})
triggerEvent(vm.$el, 'click')
expect(spy.calls.count()).toBe(1)
const args = spy.calls.allArgs()
const event = args[0] && args[0][0] || {}
expect(event.type).toBe('click')
})
it('should bind event to a inline method', () => {
vm = new Vue({
el,
template: '<div v-on:click="foo(1,2,3,$event)"></div>',
methods: { foo: spy }
})
triggerEvent(vm.$el, 'click')
expect(spy.calls.count()).toBe(1)
const args = spy.calls.allArgs()
const firstArgs = args[0]
expect(firstArgs.length).toBe(4)
expect(firstArgs[0]).toBe(1)
expect(firstArgs[1]).toBe(2)
expect(firstArgs[2]).toBe(3)
expect(firstArgs[3].type).toBe('click')
})
it('should support shorthand', () => {
vm = new Vue({
el,
template: '<a href="#test" @click.prevent="foo"></a>',
methods: { foo: spy }
})
triggerEvent(vm.$el, 'click')
expect(spy.calls.count()).toBe(1)
})
it('should support stop propagation', () => {
vm = new Vue({
el,
template: `
<div @click.stop="foo"></div>
`,
methods: { foo: spy }
})
const hash = window.location.hash
triggerEvent(vm.$el, 'click')
expect(window.location.hash).toBe(hash)
})
it('should support prevent default', () => {
vm = new Vue({
el,
template: `
<div @click="bar">
<div @click.stop="foo"></div>
</div>
`,
methods: { foo: spy, bar: spy2 }
})
triggerEvent(vm.$el.firstChild, 'click')
expect(spy).toHaveBeenCalled()
expect(spy2).not.toHaveBeenCalled()
})
it('should support capture', () => {
const callOrder = []
vm = new Vue({
el,
template: `
<div @click.capture="foo">
<div @click="bar"></div>
</div>
`,
methods: {
foo () { callOrder.push(1) },
bar () { callOrder.push(2) }
}
})
triggerEvent(vm.$el.firstChild, 'click')
expect(callOrder.toString()).toBe('1,2')
})
it('should support keyCode', () => {
vm = new Vue({
el,
template: `<input @keyup.enter="foo">`,
methods: { foo: spy }
})
triggerEvent(vm.$el, 'keyup', e => {
e.keyCode = 13
})
expect(spy).toHaveBeenCalled()
})
it('should support number keyCode', () => {
vm = new Vue({
el,
template: `<input @keyup.13="foo">`,
methods: { foo: spy }
})
triggerEvent(vm.$el, 'keyup', e => {
e.keyCode = 13
})
expect(spy).toHaveBeenCalled()
})
it('should support custom keyCode', () => {
Vue.config.keyCodes.test = 1
vm = new Vue({
el,
template: `<input @keyup.test="foo">`,
methods: { foo: spy }
})
triggerEvent(vm.$el, 'keyup', e => {
e.keyCode = 1
})
expect(spy).toHaveBeenCalled()
})
it('should bind to a child component', () => {
Vue.component('bar', {
template: '<span>Hello</span>'
})
vm = new Vue({
el,
template: '<bar @custom="foo"></bar>',
methods: { foo: spy }
})
vm.$children[0].$emit('custom', 'foo', 'bar')
expect(spy).toHaveBeenCalledWith('foo', 'bar')
})
it('should be able to bind native events for a child component', () => {
Vue.component('bar', {
template: '<span>Hello</span>'
})
vm = new Vue({
el,
template: '<bar @click.native="foo"></bar>',
methods: { foo: spy }
})
vm.$children[0].$emit('click')
expect(spy).not.toHaveBeenCalled()
triggerEvent(vm.$children[0].$el, 'click')
expect(spy).toHaveBeenCalled()
})
it('remove listener', done => {
const spy2 = jasmine.createSpy('remove listener')
vm = new Vue({
el,
methods: { foo: spy, bar: spy2 },
data: {
ok: true
},
render (h) {
return this.ok
? h('input', { on: { click: this.foo }})
: h('input', { on: { input: this.bar }})
}
})
triggerEvent(vm.$el, 'click')
expect(spy.calls.count()).toBe(1)
expect(spy2.calls.count()).toBe(0)
vm.ok = false
waitForUpdate(() => {
triggerEvent(vm.$el, 'click')
expect(spy.calls.count()).toBe(1) // should no longer trigger
triggerEvent(vm.$el, 'input')
expect(spy2.calls.count()).toBe(1)
}).then(done)
})
it('remove listener on child component', done => {
const spy2 = jasmine.createSpy('remove listener')
vm = new Vue({
el,
methods: { foo: spy, bar: spy2 },
data: {
ok: true
},
components: {
test: {
template: '<div></div>'
}
},
render (h) {
return this.ok
? h('test', { on: { foo: this.foo }})
: h('test', { on: { bar: this.bar }})
}
})
vm.$children[0].$emit('foo')
expect(spy.calls.count()).toBe(1)
expect(spy2.calls.count()).toBe(0)
vm.ok = false
waitForUpdate(() => {
vm.$children[0].$emit('foo')
expect(spy.calls.count()).toBe(1) // should no longer trigger
vm.$children[0].$emit('bar')
expect(spy2.calls.count()).toBe(1)
}).then(done)
})
})
| test/unit/features/directives/on.spec.js | 0 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.00017825717804953456,
0.0001728155475575477,
0.00016465438238810748,
0.00017383064550813287,
0.000003912680767825805
] |
{
"id": 4,
"code_window": [
" data: VNodeData | void;\n",
" children: Array<VNode> | void;\n",
" text: string | void;\n",
" elm: Node | void;\n",
" ns: string | void;\n",
" context: Component | void;\n",
" host: ?Component;\n",
" key: string | number | void;\n",
" componentOptions: VNodeComponentOptions | void;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" context: Component | void; // rendered in this component's scope\n",
" host: ?Component; // inserted into this component as children\n"
],
"file_path": "src/core/vdom/vnode.js",
"type": "replace",
"edit_start_line_idx": 9
} | /**
* Virtual DOM implementation based on Snabbdom by
* Simon Friis Vindum (@paldepind)
* with custom modifications.
*
* Not type-checking this because this file is perf-critical and the cost
* of making flow understand it is not worth it.
*/
import config from '../config'
import VNode from './vnode'
import { isPrimitive, _toString, warn } from '../util/index'
const emptyData = {}
const emptyNode = new VNode('', emptyData, [])
const hooks = ['create', 'update', 'postpatch', 'remove', 'destroy']
function isUndef (s) {
return s == null
}
function isDef (s) {
return s != null
}
function sameVnode (vnode1, vnode2) {
if (vnode1.isStatic || vnode2.isStatic) {
return vnode1 === vnode2
}
return (
vnode1.key === vnode2.key &&
vnode1.tag === vnode2.tag &&
!vnode1.data === !vnode2.data
)
}
function createKeyToOldIdx (children, beginIdx, endIdx) {
let i, key
const map = {}
for (i = beginIdx; i <= endIdx; ++i) {
key = children[i].key
if (isDef(key)) map[key] = i
}
return map
}
export function createPatchFunction (backend) {
let i, j
const cbs = {}
const { modules, nodeOps } = backend
for (i = 0; i < hooks.length; ++i) {
cbs[hooks[i]] = []
for (j = 0; j < modules.length; ++j) {
if (modules[j][hooks[i]] !== undefined) cbs[hooks[i]].push(modules[j][hooks[i]])
}
}
function emptyNodeAt (elm) {
return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm)
}
function createRmCb (childElm, listeners) {
function remove () {
if (--remove.listeners === 0) {
removeElement(childElm)
}
}
remove.listeners = listeners
return remove
}
function removeElement (el) {
const parent = nodeOps.parentNode(el)
nodeOps.removeChild(parent, el)
}
function createElm (vnode, insertedVnodeQueue) {
let i, elm
const data = vnode.data
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode)
// after calling the init hook, if the vnode is a child component
// it should've created a child instance and mounted it. the child
// component also has set the placeholder vnode's elm.
// in that case we can just return the element and be done.
if (isDef(i = vnode.child)) {
if (vnode.data.pendingInsert) {
insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert)
}
vnode.elm = vnode.child.$el
invokeCreateHooks(vnode, insertedVnodeQueue)
setScope(vnode)
return vnode.elm
}
}
const children = vnode.children
const tag = vnode.tag
if (isDef(tag)) {
if (process.env.NODE_ENV !== 'production') {
if (
!vnode.ns &&
!(config.ignoredElements && config.ignoredElements.indexOf(tag) > -1) &&
config.isUnknownElement(tag)
) {
warn(
'Unknown custom element: <' + tag + '> - did you ' +
'register the component correctly? For recursive components, ' +
'make sure to provide the "name" option.',
vnode.context
)
}
}
elm = vnode.elm = vnode.ns
? nodeOps.createElementNS(vnode.ns, tag)
: nodeOps.createElement(tag)
setScope(vnode)
if (Array.isArray(children)) {
for (i = 0; i < children.length; ++i) {
nodeOps.appendChild(elm, createElm(children[i], insertedVnodeQueue))
}
} else if (isPrimitive(vnode.text)) {
nodeOps.appendChild(elm, nodeOps.createTextNode(vnode.text))
}
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue)
}
} else {
elm = vnode.elm = nodeOps.createTextNode(vnode.text)
}
return vnode.elm
}
function invokeCreateHooks (vnode, insertedVnodeQueue) {
for (let i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, vnode)
}
i = vnode.data.hook // Reuse variable
if (isDef(i)) {
if (i.create) i.create(emptyNode, vnode)
if (i.insert) insertedVnodeQueue.push(vnode)
}
}
// set scope id attribute for scoped CSS.
// this is implemented as a special case to avoid the overhead
// of going through the normal attribute patching process.
function setScope (vnode) {
let i
if (isDef(i = vnode.host) && isDef(i = i.$options._scopeId)) {
nodeOps.setAttribute(vnode.elm, i, '')
}
if (isDef(i = vnode.context) && isDef(i = i.$options._scopeId)) {
nodeOps.setAttribute(vnode.elm, i, '')
}
}
function addVnodes (parentElm, before, vnodes, startIdx, endIdx, insertedVnodeQueue) {
for (; startIdx <= endIdx; ++startIdx) {
nodeOps.insertBefore(parentElm, createElm(vnodes[startIdx], insertedVnodeQueue), before)
}
}
function invokeDestroyHook (vnode) {
let i, j
const data = vnode.data
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.destroy)) i(vnode)
for (i = 0; i < cbs.destroy.length; ++i) cbs.destroy[i](vnode)
}
if (isDef(i = vnode.child) && !data.keepAlive) {
invokeDestroyHook(i._vnode)
}
if (isDef(i = vnode.children)) {
for (j = 0; j < vnode.children.length; ++j) {
invokeDestroyHook(vnode.children[j])
}
}
}
function removeVnodes (parentElm, vnodes, startIdx, endIdx) {
for (; startIdx <= endIdx; ++startIdx) {
const ch = vnodes[startIdx]
if (isDef(ch)) {
if (isDef(ch.tag)) {
invokeDestroyHook(ch)
removeAndInvokeRemoveHook(ch)
} else { // Text node
nodeOps.removeChild(parentElm, ch.elm)
}
}
}
}
function removeAndInvokeRemoveHook (vnode, rm) {
if (rm || isDef(vnode.data)) {
const listeners = cbs.remove.length + 1
if (!rm) {
// directly removing
rm = createRmCb(vnode.elm, listeners)
} else {
// we have a recursively passed down rm callback
// increase the listeners count
rm.listeners += listeners
}
// recursively invoke hooks on child component root node
if (isDef(i = vnode.child) && isDef(i = i._vnode) && isDef(i.data)) {
removeAndInvokeRemoveHook(i, rm)
}
for (i = 0; i < cbs.remove.length; ++i) {
cbs.remove[i](vnode, rm)
}
if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) {
i(vnode, rm)
} else {
rm()
}
} else {
removeElement(vnode.elm)
}
}
function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) {
let oldStartIdx = 0
let newStartIdx = 0
let oldEndIdx = oldCh.length - 1
let oldStartVnode = oldCh[0]
let oldEndVnode = oldCh[oldEndIdx]
let newEndIdx = newCh.length - 1
let newStartVnode = newCh[0]
let newEndVnode = newCh[newEndIdx]
let oldKeyToIdx, idxInOld, elmToMove, before
// removeOnly is a special flag used only by <transition-group>
// to ensure removed elements stay in correct relative positions
// during leaving transitions
const canMove = !removeOnly
while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
if (isUndef(oldStartVnode)) {
oldStartVnode = oldCh[++oldStartIdx] // Vnode has been moved left
} else if (isUndef(oldEndVnode)) {
oldEndVnode = oldCh[--oldEndIdx]
} else if (sameVnode(oldStartVnode, newStartVnode)) {
patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue)
oldStartVnode = oldCh[++oldStartIdx]
newStartVnode = newCh[++newStartIdx]
} else if (sameVnode(oldEndVnode, newEndVnode)) {
patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue)
oldEndVnode = oldCh[--oldEndIdx]
newEndVnode = newCh[--newEndIdx]
} else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right
patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue)
canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm))
oldStartVnode = oldCh[++oldStartIdx]
newEndVnode = newCh[--newEndIdx]
} else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left
patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue)
canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm)
oldEndVnode = oldCh[--oldEndIdx]
newStartVnode = newCh[++newStartIdx]
} else {
if (isUndef(oldKeyToIdx)) oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx)
idxInOld = isDef(newStartVnode.key)
? oldKeyToIdx[newStartVnode.key]
: newStartVnode.isStatic
? oldCh.indexOf(newStartVnode)
: null
if (isUndef(idxInOld) || idxInOld === -1) { // New element
nodeOps.insertBefore(parentElm, createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm)
newStartVnode = newCh[++newStartIdx]
} else {
elmToMove = oldCh[idxInOld]
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && !elmToMove) {
warn(
'It seems there are duplicate keys that is causing an update error. ' +
'Make sure each v-for item has a unique key.'
)
}
if (elmToMove.tag !== newStartVnode.tag) {
// same key but different element. treat as new element
nodeOps.insertBefore(parentElm, createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm)
newStartVnode = newCh[++newStartIdx]
} else {
patchVnode(elmToMove, newStartVnode, insertedVnodeQueue)
oldCh[idxInOld] = undefined
canMove && nodeOps.insertBefore(parentElm, newStartVnode.elm, oldStartVnode.elm)
newStartVnode = newCh[++newStartIdx]
}
}
}
}
if (oldStartIdx > oldEndIdx) {
before = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm
addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx, insertedVnodeQueue)
} else if (newStartIdx > newEndIdx) {
removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx)
}
}
function patchVnode (oldVnode, vnode, insertedVnodeQueue, removeOnly) {
if (oldVnode === vnode) return
let i, hook
const hasData = isDef(i = vnode.data)
if (hasData && isDef(hook = i.hook) && isDef(i = hook.prepatch)) {
i(oldVnode, vnode)
}
const elm = vnode.elm = oldVnode.elm
const oldCh = oldVnode.children
const ch = vnode.children
if (hasData) {
for (i = 0; i < cbs.update.length; ++i) cbs.update[i](oldVnode, vnode)
if (isDef(hook) && isDef(i = hook.update)) i(oldVnode, vnode)
}
if (isUndef(vnode.text)) {
if (isDef(oldCh) && isDef(ch)) {
if (oldCh !== ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly)
} else if (isDef(ch)) {
if (isDef(oldVnode.text)) nodeOps.setTextContent(elm, '')
addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue)
} else if (isDef(oldCh)) {
removeVnodes(elm, oldCh, 0, oldCh.length - 1)
} else if (isDef(oldVnode.text)) {
nodeOps.setTextContent(elm, '')
}
} else if (oldVnode.text !== vnode.text) {
nodeOps.setTextContent(elm, vnode.text)
}
if (hasData) {
for (i = 0; i < cbs.postpatch.length; ++i) cbs.postpatch[i](oldVnode, vnode)
if (isDef(hook) && isDef(i = hook.postpatch)) i(oldVnode, vnode)
}
}
function invokeInsertHook (vnode, queue, initial) {
// delay insert hooks for component root nodes, invoke them after the
// element is really inserted
if (initial && vnode.parent) {
vnode.parent.data.pendingInsert = queue
} else {
for (let i = 0; i < queue.length; ++i) {
queue[i].data.hook.insert(queue[i])
}
}
}
let bailed = false
function hydrate (elm, vnode, insertedVnodeQueue) {
if (process.env.NODE_ENV !== 'production') {
if (!assertNodeMatch(elm, vnode)) {
return false
}
}
vnode.elm = elm
const { tag, data, children } = vnode
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode, true /* hydrating */)
if (isDef(i = vnode.child)) {
// child component. it should have hydrated its own tree.
invokeCreateHooks(vnode, insertedVnodeQueue)
return true
}
}
if (isDef(tag)) {
if (isDef(children)) {
const childNodes = nodeOps.childNodes(elm)
let childrenMatch = true
if (childNodes.length !== children.length) {
childrenMatch = false
} else {
for (let i = 0; i < children.length; i++) {
if (!hydrate(childNodes[i], children[i], insertedVnodeQueue)) {
childrenMatch = false
break
}
}
}
if (!childrenMatch) {
if (process.env.NODE_ENV !== 'production' &&
typeof console !== 'undefined' &&
!bailed) {
bailed = true
console.warn('Parent: ', elm)
console.warn('Mismatching childNodes vs. VNodes: ', childNodes, children)
}
return false
}
}
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue)
}
}
return true
}
function assertNodeMatch (node, vnode) {
let match = true
if (!node) {
match = false
} else if (vnode.tag) {
match =
vnode.tag.indexOf('vue-component') === 0 ||
vnode.tag === nodeOps.tagName(node).toLowerCase()
} else {
match = _toString(vnode.text) === node.data
}
return match
}
return function patch (oldVnode, vnode, hydrating, removeOnly) {
let elm, parent
let isInitialPatch = false
const insertedVnodeQueue = []
if (!oldVnode) {
// empty mount, create new root element
isInitialPatch = true
createElm(vnode, insertedVnodeQueue)
} else {
const isRealElement = isDef(oldVnode.nodeType)
if (!isRealElement && sameVnode(oldVnode, vnode)) {
patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly)
} else {
if (isRealElement) {
// mounting to a real element
// check if this is server-rendered content and if we can perform
// a successful hydration.
if (oldVnode.hasAttribute('server-rendered')) {
oldVnode.removeAttribute('server-rendered')
hydrating = true
}
if (hydrating) {
if (hydrate(oldVnode, vnode, insertedVnodeQueue)) {
invokeInsertHook(vnode, insertedVnodeQueue, true)
return oldVnode
} else if (process.env.NODE_ENV !== 'production') {
warn(
'The client-side rendered virtual DOM tree is not matching ' +
'server-rendered content. This is likely caused by incorrect ' +
'HTML markup, for example nesting block-level elements inside ' +
'<p>, or missing <tbody>. Bailing hydration and performing ' +
'full client-side render.'
)
}
}
// either not server-rendered, or hydration failed.
// create an empty node and replace it
oldVnode = emptyNodeAt(oldVnode)
}
elm = oldVnode.elm
parent = nodeOps.parentNode(elm)
createElm(vnode, insertedVnodeQueue)
// component root element replaced.
// update parent placeholder node element.
if (vnode.parent) {
vnode.parent.elm = vnode.elm
for (let i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, vnode.parent)
}
}
if (parent !== null) {
nodeOps.insertBefore(parent, vnode.elm, nodeOps.nextSibling(elm))
removeVnodes(parent, [oldVnode], 0, 0)
} else if (isDef(oldVnode.tag)) {
invokeDestroyHook(oldVnode)
}
}
}
invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch)
return vnode.elm
}
}
| src/core/vdom/patch.js | 1 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.004622327629476786,
0.0003734936472028494,
0.00016386796778533608,
0.00016990001313388348,
0.0006948976661078632
] |
{
"id": 4,
"code_window": [
" data: VNodeData | void;\n",
" children: Array<VNode> | void;\n",
" text: string | void;\n",
" elm: Node | void;\n",
" ns: string | void;\n",
" context: Component | void;\n",
" host: ?Component;\n",
" key: string | number | void;\n",
" componentOptions: VNodeComponentOptions | void;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" context: Component | void; // rendered in this component's scope\n",
" host: ?Component; // inserted into this component as children\n"
],
"file_path": "src/core/vdom/vnode.js",
"type": "replace",
"edit_start_line_idx": 9
} | /* @flow */
import { hyphenate, toObject } from 'shared/util'
export default function renderStyle (node: VNodeWithData): ?string {
const staticStyle = node.data.attrs && node.data.attrs.style
if (node.data.style || staticStyle) {
let styles = node.data.style
let res = ''
if (styles) {
if (typeof styles === 'string') {
res += styles
} else {
if (Array.isArray(styles)) {
styles = toObject(styles)
}
for (const key in styles) {
res += `${hyphenate(key)}:${styles[key]};`
}
res += staticStyle || ''
}
}
return ` style=${JSON.stringify(res)}`
}
}
| src/platforms/web/server/modules/style.js | 0 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.00032335970900021493,
0.0002233042032457888,
0.00017042351828422397,
0.000176129411556758,
0.00007078825728967786
] |
{
"id": 4,
"code_window": [
" data: VNodeData | void;\n",
" children: Array<VNode> | void;\n",
" text: string | void;\n",
" elm: Node | void;\n",
" ns: string | void;\n",
" context: Component | void;\n",
" host: ?Component;\n",
" key: string | number | void;\n",
" componentOptions: VNodeComponentOptions | void;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" context: Component | void; // rendered in this component's scope\n",
" host: ?Component; // inserted into this component as children\n"
],
"file_path": "src/core/vdom/vnode.js",
"type": "replace",
"edit_start_line_idx": 9
} | {
"rules": {
"indent": 0
}
}
| test/e2e/.eslintrc | 0 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.00018006509344559163,
0.00018006509344559163,
0.00018006509344559163,
0.00018006509344559163,
0
] |
{
"id": 4,
"code_window": [
" data: VNodeData | void;\n",
" children: Array<VNode> | void;\n",
" text: string | void;\n",
" elm: Node | void;\n",
" ns: string | void;\n",
" context: Component | void;\n",
" host: ?Component;\n",
" key: string | number | void;\n",
" componentOptions: VNodeComponentOptions | void;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" context: Component | void; // rendered in this component's scope\n",
" host: ?Component; // inserted into this component as children\n"
],
"file_path": "src/core/vdom/vnode.js",
"type": "replace",
"edit_start_line_idx": 9
} | declare interface GlobalAPI {
cid: number;
options: Object;
config: Config;
util: Object;
extend: (options: Object) => Function;
set: (obj: Object, key: string, value: any) => void;
delete: (obj: Object, key: string) => void;
nextTick: (fn: Function, context?: Object) => void;
use: (plugin: Function | Object) => void;
mixin: (mixin: Object) => void;
compile: (template: string) => { render: Function, staticRenderFns: Array<Function> };
directive: (id: string, def?: Function | Object) => Function | Object | void;
component: (id: string, def?: Class<Component> | Object) => Class<Component>;
filter: (id: string, def?: Function) => Function | void;
// allow dynamic method registration
[key: string]: any
}
| flow/global-api.js | 0 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.00022723371512256563,
0.00020466519345063716,
0.00018032212392427027,
0.0002064397995127365,
0.000019192641047993675
] |
{
"id": 5,
"code_window": [
" key: string | number | void;\n",
" componentOptions: VNodeComponentOptions | void;\n",
" child: Component | void;\n",
" parent: VNode | void;\n",
" raw: ?boolean;\n",
" isStatic: ?boolean;\n",
"\n",
" constructor (\n",
" tag?: string,\n",
" data?: VNodeData,\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" child: Component | void; // component instance\n",
" parent: VNode | void; // compoennt placeholder node\n",
" raw: ?boolean; // contains raw HTML\n",
" isStatic: ?boolean; // hoisted static node\n",
" isRootInsert: boolean; // necessary for enter transition check\n"
],
"file_path": "src/core/vdom/vnode.js",
"type": "replace",
"edit_start_line_idx": 13
} | /**
* Virtual DOM implementation based on Snabbdom by
* Simon Friis Vindum (@paldepind)
* with custom modifications.
*
* Not type-checking this because this file is perf-critical and the cost
* of making flow understand it is not worth it.
*/
import config from '../config'
import VNode from './vnode'
import { isPrimitive, _toString, warn } from '../util/index'
const emptyData = {}
const emptyNode = new VNode('', emptyData, [])
const hooks = ['create', 'update', 'postpatch', 'remove', 'destroy']
function isUndef (s) {
return s == null
}
function isDef (s) {
return s != null
}
function sameVnode (vnode1, vnode2) {
if (vnode1.isStatic || vnode2.isStatic) {
return vnode1 === vnode2
}
return (
vnode1.key === vnode2.key &&
vnode1.tag === vnode2.tag &&
!vnode1.data === !vnode2.data
)
}
function createKeyToOldIdx (children, beginIdx, endIdx) {
let i, key
const map = {}
for (i = beginIdx; i <= endIdx; ++i) {
key = children[i].key
if (isDef(key)) map[key] = i
}
return map
}
export function createPatchFunction (backend) {
let i, j
const cbs = {}
const { modules, nodeOps } = backend
for (i = 0; i < hooks.length; ++i) {
cbs[hooks[i]] = []
for (j = 0; j < modules.length; ++j) {
if (modules[j][hooks[i]] !== undefined) cbs[hooks[i]].push(modules[j][hooks[i]])
}
}
function emptyNodeAt (elm) {
return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm)
}
function createRmCb (childElm, listeners) {
function remove () {
if (--remove.listeners === 0) {
removeElement(childElm)
}
}
remove.listeners = listeners
return remove
}
function removeElement (el) {
const parent = nodeOps.parentNode(el)
nodeOps.removeChild(parent, el)
}
function createElm (vnode, insertedVnodeQueue) {
let i, elm
const data = vnode.data
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode)
// after calling the init hook, if the vnode is a child component
// it should've created a child instance and mounted it. the child
// component also has set the placeholder vnode's elm.
// in that case we can just return the element and be done.
if (isDef(i = vnode.child)) {
if (vnode.data.pendingInsert) {
insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert)
}
vnode.elm = vnode.child.$el
invokeCreateHooks(vnode, insertedVnodeQueue)
setScope(vnode)
return vnode.elm
}
}
const children = vnode.children
const tag = vnode.tag
if (isDef(tag)) {
if (process.env.NODE_ENV !== 'production') {
if (
!vnode.ns &&
!(config.ignoredElements && config.ignoredElements.indexOf(tag) > -1) &&
config.isUnknownElement(tag)
) {
warn(
'Unknown custom element: <' + tag + '> - did you ' +
'register the component correctly? For recursive components, ' +
'make sure to provide the "name" option.',
vnode.context
)
}
}
elm = vnode.elm = vnode.ns
? nodeOps.createElementNS(vnode.ns, tag)
: nodeOps.createElement(tag)
setScope(vnode)
if (Array.isArray(children)) {
for (i = 0; i < children.length; ++i) {
nodeOps.appendChild(elm, createElm(children[i], insertedVnodeQueue))
}
} else if (isPrimitive(vnode.text)) {
nodeOps.appendChild(elm, nodeOps.createTextNode(vnode.text))
}
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue)
}
} else {
elm = vnode.elm = nodeOps.createTextNode(vnode.text)
}
return vnode.elm
}
function invokeCreateHooks (vnode, insertedVnodeQueue) {
for (let i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, vnode)
}
i = vnode.data.hook // Reuse variable
if (isDef(i)) {
if (i.create) i.create(emptyNode, vnode)
if (i.insert) insertedVnodeQueue.push(vnode)
}
}
// set scope id attribute for scoped CSS.
// this is implemented as a special case to avoid the overhead
// of going through the normal attribute patching process.
function setScope (vnode) {
let i
if (isDef(i = vnode.host) && isDef(i = i.$options._scopeId)) {
nodeOps.setAttribute(vnode.elm, i, '')
}
if (isDef(i = vnode.context) && isDef(i = i.$options._scopeId)) {
nodeOps.setAttribute(vnode.elm, i, '')
}
}
function addVnodes (parentElm, before, vnodes, startIdx, endIdx, insertedVnodeQueue) {
for (; startIdx <= endIdx; ++startIdx) {
nodeOps.insertBefore(parentElm, createElm(vnodes[startIdx], insertedVnodeQueue), before)
}
}
function invokeDestroyHook (vnode) {
let i, j
const data = vnode.data
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.destroy)) i(vnode)
for (i = 0; i < cbs.destroy.length; ++i) cbs.destroy[i](vnode)
}
if (isDef(i = vnode.child) && !data.keepAlive) {
invokeDestroyHook(i._vnode)
}
if (isDef(i = vnode.children)) {
for (j = 0; j < vnode.children.length; ++j) {
invokeDestroyHook(vnode.children[j])
}
}
}
function removeVnodes (parentElm, vnodes, startIdx, endIdx) {
for (; startIdx <= endIdx; ++startIdx) {
const ch = vnodes[startIdx]
if (isDef(ch)) {
if (isDef(ch.tag)) {
invokeDestroyHook(ch)
removeAndInvokeRemoveHook(ch)
} else { // Text node
nodeOps.removeChild(parentElm, ch.elm)
}
}
}
}
function removeAndInvokeRemoveHook (vnode, rm) {
if (rm || isDef(vnode.data)) {
const listeners = cbs.remove.length + 1
if (!rm) {
// directly removing
rm = createRmCb(vnode.elm, listeners)
} else {
// we have a recursively passed down rm callback
// increase the listeners count
rm.listeners += listeners
}
// recursively invoke hooks on child component root node
if (isDef(i = vnode.child) && isDef(i = i._vnode) && isDef(i.data)) {
removeAndInvokeRemoveHook(i, rm)
}
for (i = 0; i < cbs.remove.length; ++i) {
cbs.remove[i](vnode, rm)
}
if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) {
i(vnode, rm)
} else {
rm()
}
} else {
removeElement(vnode.elm)
}
}
function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) {
let oldStartIdx = 0
let newStartIdx = 0
let oldEndIdx = oldCh.length - 1
let oldStartVnode = oldCh[0]
let oldEndVnode = oldCh[oldEndIdx]
let newEndIdx = newCh.length - 1
let newStartVnode = newCh[0]
let newEndVnode = newCh[newEndIdx]
let oldKeyToIdx, idxInOld, elmToMove, before
// removeOnly is a special flag used only by <transition-group>
// to ensure removed elements stay in correct relative positions
// during leaving transitions
const canMove = !removeOnly
while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
if (isUndef(oldStartVnode)) {
oldStartVnode = oldCh[++oldStartIdx] // Vnode has been moved left
} else if (isUndef(oldEndVnode)) {
oldEndVnode = oldCh[--oldEndIdx]
} else if (sameVnode(oldStartVnode, newStartVnode)) {
patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue)
oldStartVnode = oldCh[++oldStartIdx]
newStartVnode = newCh[++newStartIdx]
} else if (sameVnode(oldEndVnode, newEndVnode)) {
patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue)
oldEndVnode = oldCh[--oldEndIdx]
newEndVnode = newCh[--newEndIdx]
} else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right
patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue)
canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm))
oldStartVnode = oldCh[++oldStartIdx]
newEndVnode = newCh[--newEndIdx]
} else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left
patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue)
canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm)
oldEndVnode = oldCh[--oldEndIdx]
newStartVnode = newCh[++newStartIdx]
} else {
if (isUndef(oldKeyToIdx)) oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx)
idxInOld = isDef(newStartVnode.key)
? oldKeyToIdx[newStartVnode.key]
: newStartVnode.isStatic
? oldCh.indexOf(newStartVnode)
: null
if (isUndef(idxInOld) || idxInOld === -1) { // New element
nodeOps.insertBefore(parentElm, createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm)
newStartVnode = newCh[++newStartIdx]
} else {
elmToMove = oldCh[idxInOld]
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && !elmToMove) {
warn(
'It seems there are duplicate keys that is causing an update error. ' +
'Make sure each v-for item has a unique key.'
)
}
if (elmToMove.tag !== newStartVnode.tag) {
// same key but different element. treat as new element
nodeOps.insertBefore(parentElm, createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm)
newStartVnode = newCh[++newStartIdx]
} else {
patchVnode(elmToMove, newStartVnode, insertedVnodeQueue)
oldCh[idxInOld] = undefined
canMove && nodeOps.insertBefore(parentElm, newStartVnode.elm, oldStartVnode.elm)
newStartVnode = newCh[++newStartIdx]
}
}
}
}
if (oldStartIdx > oldEndIdx) {
before = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm
addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx, insertedVnodeQueue)
} else if (newStartIdx > newEndIdx) {
removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx)
}
}
function patchVnode (oldVnode, vnode, insertedVnodeQueue, removeOnly) {
if (oldVnode === vnode) return
let i, hook
const hasData = isDef(i = vnode.data)
if (hasData && isDef(hook = i.hook) && isDef(i = hook.prepatch)) {
i(oldVnode, vnode)
}
const elm = vnode.elm = oldVnode.elm
const oldCh = oldVnode.children
const ch = vnode.children
if (hasData) {
for (i = 0; i < cbs.update.length; ++i) cbs.update[i](oldVnode, vnode)
if (isDef(hook) && isDef(i = hook.update)) i(oldVnode, vnode)
}
if (isUndef(vnode.text)) {
if (isDef(oldCh) && isDef(ch)) {
if (oldCh !== ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly)
} else if (isDef(ch)) {
if (isDef(oldVnode.text)) nodeOps.setTextContent(elm, '')
addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue)
} else if (isDef(oldCh)) {
removeVnodes(elm, oldCh, 0, oldCh.length - 1)
} else if (isDef(oldVnode.text)) {
nodeOps.setTextContent(elm, '')
}
} else if (oldVnode.text !== vnode.text) {
nodeOps.setTextContent(elm, vnode.text)
}
if (hasData) {
for (i = 0; i < cbs.postpatch.length; ++i) cbs.postpatch[i](oldVnode, vnode)
if (isDef(hook) && isDef(i = hook.postpatch)) i(oldVnode, vnode)
}
}
function invokeInsertHook (vnode, queue, initial) {
// delay insert hooks for component root nodes, invoke them after the
// element is really inserted
if (initial && vnode.parent) {
vnode.parent.data.pendingInsert = queue
} else {
for (let i = 0; i < queue.length; ++i) {
queue[i].data.hook.insert(queue[i])
}
}
}
let bailed = false
function hydrate (elm, vnode, insertedVnodeQueue) {
if (process.env.NODE_ENV !== 'production') {
if (!assertNodeMatch(elm, vnode)) {
return false
}
}
vnode.elm = elm
const { tag, data, children } = vnode
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode, true /* hydrating */)
if (isDef(i = vnode.child)) {
// child component. it should have hydrated its own tree.
invokeCreateHooks(vnode, insertedVnodeQueue)
return true
}
}
if (isDef(tag)) {
if (isDef(children)) {
const childNodes = nodeOps.childNodes(elm)
let childrenMatch = true
if (childNodes.length !== children.length) {
childrenMatch = false
} else {
for (let i = 0; i < children.length; i++) {
if (!hydrate(childNodes[i], children[i], insertedVnodeQueue)) {
childrenMatch = false
break
}
}
}
if (!childrenMatch) {
if (process.env.NODE_ENV !== 'production' &&
typeof console !== 'undefined' &&
!bailed) {
bailed = true
console.warn('Parent: ', elm)
console.warn('Mismatching childNodes vs. VNodes: ', childNodes, children)
}
return false
}
}
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue)
}
}
return true
}
function assertNodeMatch (node, vnode) {
let match = true
if (!node) {
match = false
} else if (vnode.tag) {
match =
vnode.tag.indexOf('vue-component') === 0 ||
vnode.tag === nodeOps.tagName(node).toLowerCase()
} else {
match = _toString(vnode.text) === node.data
}
return match
}
return function patch (oldVnode, vnode, hydrating, removeOnly) {
let elm, parent
let isInitialPatch = false
const insertedVnodeQueue = []
if (!oldVnode) {
// empty mount, create new root element
isInitialPatch = true
createElm(vnode, insertedVnodeQueue)
} else {
const isRealElement = isDef(oldVnode.nodeType)
if (!isRealElement && sameVnode(oldVnode, vnode)) {
patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly)
} else {
if (isRealElement) {
// mounting to a real element
// check if this is server-rendered content and if we can perform
// a successful hydration.
if (oldVnode.hasAttribute('server-rendered')) {
oldVnode.removeAttribute('server-rendered')
hydrating = true
}
if (hydrating) {
if (hydrate(oldVnode, vnode, insertedVnodeQueue)) {
invokeInsertHook(vnode, insertedVnodeQueue, true)
return oldVnode
} else if (process.env.NODE_ENV !== 'production') {
warn(
'The client-side rendered virtual DOM tree is not matching ' +
'server-rendered content. This is likely caused by incorrect ' +
'HTML markup, for example nesting block-level elements inside ' +
'<p>, or missing <tbody>. Bailing hydration and performing ' +
'full client-side render.'
)
}
}
// either not server-rendered, or hydration failed.
// create an empty node and replace it
oldVnode = emptyNodeAt(oldVnode)
}
elm = oldVnode.elm
parent = nodeOps.parentNode(elm)
createElm(vnode, insertedVnodeQueue)
// component root element replaced.
// update parent placeholder node element.
if (vnode.parent) {
vnode.parent.elm = vnode.elm
for (let i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, vnode.parent)
}
}
if (parent !== null) {
nodeOps.insertBefore(parent, vnode.elm, nodeOps.nextSibling(elm))
removeVnodes(parent, [oldVnode], 0, 0)
} else if (isDef(oldVnode.tag)) {
invokeDestroyHook(oldVnode)
}
}
}
invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch)
return vnode.elm
}
}
| src/core/vdom/patch.js | 1 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.0061853001825511456,
0.000625955464784056,
0.0001650818157941103,
0.00017257951549254358,
0.0011732992716133595
] |
{
"id": 5,
"code_window": [
" key: string | number | void;\n",
" componentOptions: VNodeComponentOptions | void;\n",
" child: Component | void;\n",
" parent: VNode | void;\n",
" raw: ?boolean;\n",
" isStatic: ?boolean;\n",
"\n",
" constructor (\n",
" tag?: string,\n",
" data?: VNodeData,\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" child: Component | void; // component instance\n",
" parent: VNode | void; // compoennt placeholder node\n",
" raw: ?boolean; // contains raw HTML\n",
" isStatic: ?boolean; // hoisted static node\n",
" isRootInsert: boolean; // necessary for enter transition check\n"
],
"file_path": "src/core/vdom/vnode.js",
"type": "replace",
"edit_start_line_idx": 13
} | import Vue from 'vue'
import injectStyles from './inject-styles'
import { isIE9 } from 'web/util/index'
import { nextFrame } from 'web/runtime/transition-util'
if (!isIE9) {
describe('Transition basic', () => {
const duration = injectStyles()
let el
beforeEach(() => {
el = document.createElement('div')
document.body.appendChild(el)
})
it('basic transition', done => {
const vm = new Vue({
template: '<div><transition><div v-if="ok" class="test">foo</div></transition></div>',
data: { ok: true }
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.innerHTML).toBe('<div class="test">foo</div>')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test v-leave v-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test v-leave-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test v-enter v-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test v-enter-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('named transition', done => {
const vm = new Vue({
template: '<div><transition name="test"><div v-if="ok" class="test">foo</div></transition></div>',
data: { ok: true }
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.innerHTML).toBe('<div class="test">foo</div>')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test test-leave test-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-leave-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test test-enter test-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-enter-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('custom transition classes', done => {
const vm = new Vue({
template: `
<div>
<transition
enter-class="hello"
enter-active-class="hello-active"
leave-class="bye"
leave-active-class="byebye active">
<div v-if="ok" class="test">foo</div>
</transition>
</div>
`,
data: { ok: true }
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.innerHTML).toBe('<div class="test">foo</div>')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test bye byebye active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test byebye active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test hello hello-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test hello-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('dynamic transition', done => {
const vm = new Vue({
template: `
<div>
<transition :name="trans">
<div v-if="ok" class="test">foo</div>
</transition>
</div>
`,
data: {
ok: true,
trans: 'test'
}
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.innerHTML).toBe('<div class="test">foo</div>')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test test-leave test-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-leave-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
vm.trans = 'changed'
}).then(() => {
expect(vm.$el.children[0].className).toBe('test changed-enter changed-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test changed-enter-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('inline transition object', done => {
const enter = jasmine.createSpy('enter')
const leave = jasmine.createSpy('leave')
const vm = new Vue({
render (h) {
return h('div', null, [
h('transition', {
props: {
name: 'inline',
enterClass: 'hello',
enterActiveClass: 'hello-active',
leaveClass: 'bye',
leaveActiveClass: 'byebye active'
},
on: {
enter,
leave
}
}, () => [this.ok ? h('div', { class: 'test' }, 'foo') : undefined])
])
},
data: { ok: true }
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.innerHTML).toBe('<div class="test">foo</div>')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test bye byebye active')
expect(leave).toHaveBeenCalled()
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test byebye active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test hello hello-active')
expect(enter).toHaveBeenCalled()
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test hello-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('transition events', done => {
const onLeaveSpy = jasmine.createSpy('leave')
const onEnterSpy = jasmine.createSpy('enter')
const beforeLeaveSpy = jasmine.createSpy('beforeLeave')
const beforeEnterSpy = jasmine.createSpy('beforeEnter')
const afterLeaveSpy = jasmine.createSpy('afterLeave')
const afterEnterSpy = jasmine.createSpy('afterEnter')
const vm = new Vue({
template: `
<div>
<transition
name="test"
@before-enter="beforeEnter"
@enter="enter"
@after-enter="afterEnter"
@before-leave="beforeLeave"
@leave="leave"
@after-leave="afterLeave">
<div v-if="ok" class="test">foo</div>
</transition>
</div>
`,
data: { ok: true },
methods: {
beforeLeave: (el) => {
expect(el).toBe(vm.$el.children[0])
expect(el.className).toBe('test')
beforeLeaveSpy(el)
},
leave: (el) => onLeaveSpy(el),
afterLeave: (el) => afterLeaveSpy(el),
beforeEnter: (el) => {
expect(vm.$el.contains(el)).toBe(false)
expect(el.className).toBe('test')
beforeEnterSpy(el)
},
enter: (el) => {
expect(vm.$el.contains(el)).toBe(true)
onEnterSpy(el)
},
afterEnter: (el) => afterEnterSpy(el)
}
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.innerHTML).toBe('<div class="test">foo</div>')
let _el = vm.$el.children[0]
vm.ok = false
waitForUpdate(() => {
expect(beforeLeaveSpy).toHaveBeenCalledWith(_el)
expect(onLeaveSpy).toHaveBeenCalledWith(_el)
expect(vm.$el.children[0].className).toBe('test test-leave test-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(afterLeaveSpy).not.toHaveBeenCalled()
expect(vm.$el.children[0].className).toBe('test test-leave-active')
}).thenWaitFor(duration + 10).then(() => {
expect(afterLeaveSpy).toHaveBeenCalledWith(_el)
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
_el = vm.$el.children[0]
expect(beforeEnterSpy).toHaveBeenCalledWith(_el)
expect(onEnterSpy).toHaveBeenCalledWith(_el)
expect(vm.$el.children[0].className).toBe('test test-enter test-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(afterEnterSpy).not.toHaveBeenCalled()
expect(vm.$el.children[0].className).toBe('test test-enter-active')
}).thenWaitFor(duration + 10).then(() => {
expect(afterEnterSpy).toHaveBeenCalledWith(_el)
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('explicit user callback in JavaScript hooks', done => {
let next
const vm = new Vue({
template: `<div>
<transition name="test" @enter="enter" @leave="leave">
<div v-if="ok" class="test">foo</div>
</transition>
</div>`,
data: { ok: true },
methods: {
enter: (el, cb) => {
next = cb
},
leave: (el, cb) => {
next = cb
}
}
}).$mount(el)
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test test-leave test-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-leave-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children[0].className).toBe('test test-leave-active')
expect(next).toBeTruthy()
next()
expect(vm.$el.children.length).toBe(0)
}).then(() => {
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test test-enter test-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-enter-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children[0].className).toBe('test test-enter-active')
expect(next).toBeTruthy()
next()
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('css: false', done => {
const enterSpy = jasmine.createSpy('enter')
const leaveSpy = jasmine.createSpy('leave')
const vm = new Vue({
template: `
<div>
<transition :css="false" name="test" @enter="enter" @leave="leave">
<div v-if="ok" class="test">foo</div>
</transition>
</div>
`,
data: { ok: true },
methods: {
enter: enterSpy,
leave: leaveSpy
}
}).$mount(el)
vm.ok = false
waitForUpdate(() => {
expect(leaveSpy).toHaveBeenCalled()
expect(vm.$el.innerHTML).toBe('')
vm.ok = true
}).then(() => {
expect(enterSpy).toHaveBeenCalled()
expect(vm.$el.innerHTML).toBe('<div class="test">foo</div>')
}).then(done)
})
it('no transition detected', done => {
const enterSpy = jasmine.createSpy('enter')
const leaveSpy = jasmine.createSpy('leave')
const vm = new Vue({
template: '<div><transition name="nope" @enter="enter" @leave="leave"><div v-if="ok">foo</div></transition></div>',
data: { ok: true },
methods: {
enter: enterSpy,
leave: leaveSpy
}
}).$mount(el)
vm.ok = false
waitForUpdate(() => {
expect(leaveSpy).toHaveBeenCalled()
expect(vm.$el.innerHTML).toBe('<div class="nope-leave nope-leave-active">foo</div>')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe('')
vm.ok = true
}).then(() => {
expect(enterSpy).toHaveBeenCalled()
expect(vm.$el.innerHTML).toBe('<div class="nope-enter nope-enter-active">foo</div>')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toMatch(/<div( class="")?>foo<\/div>/)
}).then(done)
})
it('enterCancelled', done => {
const spy = jasmine.createSpy('enterCancelled')
const vm = new Vue({
template: `
<div>
<transition name="test" @enter-cancelled="enterCancelled">
<div v-if="ok" class="test">foo</div>
</transition>
</div>
`,
data: { ok: false },
methods: {
enterCancelled: spy
}
}).$mount(el)
expect(vm.$el.innerHTML).toBe('')
vm.ok = true
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test test-enter test-enter-active')
}).thenWaitFor(duration / 2).then(() => {
vm.ok = false
}).then(() => {
expect(spy).toHaveBeenCalled()
expect(vm.$el.children[0].className).toBe('test test-leave test-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-leave-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children.length).toBe(0)
}).then(done)
})
it('should remove stale leaving elements', done => {
const spy = jasmine.createSpy('afterLeave')
const vm = new Vue({
template: `
<div>
<transition name="test" @after-leave="afterLeave">
<div v-if="ok" class="test">foo</div>
</transition>
</div>
`,
data: { ok: true },
methods: {
afterLeave: spy
}
}).$mount(el)
expect(vm.$el.innerHTML).toBe('<div class="test">foo</div>')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test test-leave test-leave-active')
}).thenWaitFor(duration / 2).then(() => {
vm.ok = true
}).then(() => {
expect(spy).toHaveBeenCalled()
expect(vm.$el.children.length).toBe(1) // should have removed leaving element
expect(vm.$el.children[0].className).toBe('test test-enter test-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-enter-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.innerHTML).toBe('<div class="test">foo</div>')
}).then(done)
})
it('transition with v-show', done => {
const vm = new Vue({
template: `
<div>
<transition name="test">
<div v-show="ok" class="test">foo</div>
</transition>
</div>
`,
data: { ok: true }
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.textContent).toBe('foo')
expect(vm.$el.children[0].style.display).toBe('')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test test-leave test-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-leave-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children[0].style.display).toBe('none')
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].style.display).toBe('')
expect(vm.$el.children[0].className).toBe('test test-enter test-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-enter-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('transition with v-show, inside child component', done => {
const vm = new Vue({
template: `
<div>
<test v-show="ok"></test>
</div>
`,
data: { ok: true },
components: {
test: {
template: `<transition name="test"><div class="test">foo</div></transition>`
}
}
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.textContent).toBe('foo')
expect(vm.$el.children[0].style.display).toBe('')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test test-leave test-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-leave-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children[0].style.display).toBe('none')
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].style.display).toBe('')
expect(vm.$el.children[0].className).toBe('test test-enter test-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-enter-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('leaveCancelled (v-show only)', done => {
const spy = jasmine.createSpy('leaveCancelled')
const vm = new Vue({
template: `
<div>
<transition name="test" @leave-cancelled="leaveCancelled">
<div v-show="ok" class="test">foo</div>
</transition>
</div>
`,
data: { ok: true },
methods: {
leaveCancelled: spy
}
}).$mount(el)
expect(vm.$el.children[0].style.display).toBe('')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test test-leave test-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-leave-active')
}).thenWaitFor(10).then(() => {
vm.ok = true
}).then(() => {
expect(spy).toHaveBeenCalled()
expect(vm.$el.children[0].className).toBe('test test-enter test-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-enter-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children[0].style.display).toBe('')
}).then(done)
})
it('animations', done => {
const vm = new Vue({
template: `
<div>
<transition name="test-anim">
<div v-if="ok">foo</div>
</transition>
</div>
`,
data: { ok: true }
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.innerHTML).toBe('<div>foo</div>')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test-anim-leave test-anim-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test-anim-leave-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test-anim-enter test-anim-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test-anim-enter-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children[0].className).toBe('')
}).then(done)
})
it('explicit transition type', done => {
const vm = new Vue({
template: `
<div>
<transition name="test-anim-long" type="animation">
<div v-if="ok" class="test">foo</div>
</transition>
</div>
`,
data: { ok: true }
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.innerHTML).toBe('<div class="test">foo</div>')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test test-anim-long-leave test-anim-long-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-anim-long-leave-active')
}).thenWaitFor(duration + 5).then(() => {
// should not end early due to transition presence
expect(vm.$el.children[0].className).toBe('test test-anim-long-leave-active')
}).thenWaitFor(duration + 5).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test test-anim-long-enter test-anim-long-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-anim-long-enter-active')
}).thenWaitFor(duration + 5).then(() => {
expect(vm.$el.children[0].className).toBe('test test-anim-long-enter-active')
}).thenWaitFor(duration + 5).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('transition on appear', done => {
const vm = new Vue({
template: `
<div>
<transition name="test"
appear
appear-class="test-appear"
appear-active-class="test-appear-active">
<div v-if="ok" class="test">foo</div>
</transition>
</div>
`,
data: { ok: true }
}).$mount(el)
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test test-appear test-appear-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-appear-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('transition on appear with v-show', done => {
const vm = new Vue({
template: `
<div>
<transition name="test" appear>
<div v-show="ok" class="test">foo</div>
</transition>
</div>
`,
data: { ok: true }
}).$mount(el)
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test test-enter test-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-enter-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('transition on SVG elements', done => {
const vm = new Vue({
template: `
<svg>
<transition>
<circle cx="0" cy="0" r="10" v-if="ok" class="test"></circle>
</transition>
</svg>
`,
data: { ok: true }
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.childNodes[0].getAttribute('class')).toBe('test')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.childNodes[0].getAttribute('class')).toBe('test v-leave v-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.childNodes[0].getAttribute('class')).toBe('test v-leave-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.childNodes.length).toBe(1)
expect(vm.$el.childNodes[0].nodeType).toBe(3) // should be an empty text node
expect(vm.$el.childNodes[0].textContent).toBe('')
vm.ok = true
}).then(() => {
expect(vm.$el.childNodes[0].getAttribute('class')).toBe('test v-enter v-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.childNodes[0].getAttribute('class')).toBe('test v-enter-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.childNodes[0].getAttribute('class')).toBe('test')
}).then(done)
})
it('transition on child components', done => {
const vm = new Vue({
template: `
<div>
<transition>
<test v-if="ok" class="test"></test>
</transition>
</div>
`,
data: { ok: true },
components: {
test: {
template: `
<transition name="test">
<div>foo</div>
</transition>
` // test transition override from parent
}
}
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.innerHTML).toBe('<div class="test">foo</div>')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test v-leave v-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test v-leave-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test v-enter v-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test v-enter-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('transition inside child component', done => {
const vm = new Vue({
template: `
<div>
<test v-if="ok" class="test"></test>
</div>
`,
data: { ok: true },
components: {
test: {
template: `
<transition>
<div>foo</div>
</transition>
`
}
}
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.innerHTML).toBe('<div class="test">foo</div>')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test v-leave v-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test v-leave-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test v-enter v-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test v-enter-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
it('custom transition higher-order component', done => {
const vm = new Vue({
template: '<div><my-transition><div v-if="ok" class="test">foo</div></my-transition></div>',
data: { ok: true },
components: {
'my-transition': {
functional: true,
render (h, { data, children }) {
(data.props || (data.props = {})).name = 'test'
return h('transition', data, children)
}
}
}
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.innerHTML).toBe('<div class="test">foo</div>')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].className).toBe('test test-leave test-leave-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-leave-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children.length).toBe(0)
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].className).toBe('test test-enter test-enter-active')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.children[0].className).toBe('test test-enter-active')
}).thenWaitFor(duration + 10).then(() => {
expect(vm.$el.children[0].className).toBe('test')
}).then(done)
})
})
}
| test/unit/features/transition/transition.spec.js | 0 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.00018647807883098722,
0.00017291268159169704,
0.0001644770527491346,
0.00017251874669454992,
0.0000031047386528371135
] |
{
"id": 5,
"code_window": [
" key: string | number | void;\n",
" componentOptions: VNodeComponentOptions | void;\n",
" child: Component | void;\n",
" parent: VNode | void;\n",
" raw: ?boolean;\n",
" isStatic: ?boolean;\n",
"\n",
" constructor (\n",
" tag?: string,\n",
" data?: VNodeData,\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" child: Component | void; // component instance\n",
" parent: VNode | void; // compoennt placeholder node\n",
" raw: ?boolean; // contains raw HTML\n",
" isStatic: ?boolean; // hoisted static node\n",
" isRootInsert: boolean; // necessary for enter transition check\n"
],
"file_path": "src/core/vdom/vnode.js",
"type": "replace",
"edit_start_line_idx": 13
} | var base = require('./karma.base.config.js')
/**
* Having too many tests running concurrently on saucelabs
* causes timeouts and errors, so we have to run them in
* smaller batches.
*/
var batches = [
// the cool kids
{
sl_chrome: {
base: 'SauceLabs',
browserName: 'chrome',
platform: 'Windows 7'
},
sl_firefox: {
base: 'SauceLabs',
browserName: 'firefox'
},
sl_mac_safari: {
base: 'SauceLabs',
browserName: 'safari',
platform: 'OS X 10.10'
}
},
// ie family
{
sl_ie_9: {
base: 'SauceLabs',
browserName: 'internet explorer',
platform: 'Windows 7',
version: '9'
},
sl_ie_10: {
base: 'SauceLabs',
browserName: 'internet explorer',
platform: 'Windows 8',
version: '10'
},
sl_ie_11: {
base: 'SauceLabs',
browserName: 'internet explorer',
platform: 'Windows 8.1',
version: '11'
},
sl_edge: {
base: 'SauceLabs',
browserName: 'MicrosoftEdge',
platform: 'Windows 10'
}
},
// mobile
{
sl_ios_safari_7: {
base: 'SauceLabs',
browserName: 'iphone',
version: '7.0'
},
sl_ios_safari_9: {
base: 'SauceLabs',
browserName: 'iphone',
version: '9.2'
},
sl_android_4_2: {
base: 'SauceLabs',
browserName: 'android',
version: '4.2'
},
sl_android_5_1: {
base: 'SauceLabs',
browserName: 'android',
version: '5.1'
}
}
]
module.exports = function (config) {
var batch = batches[process.argv[4] || 0]
config.set(Object.assign(base, {
singleRun: true,
browsers: Object.keys(batch),
customLaunchers: batch,
reporters: process.env.CI
? ['dots', 'saucelabs'] // avoid spamming CI output
: ['progress', 'saucelabs'],
sauceLabs: {
testName: 'Vue.js unit tests',
recordScreenshots: false,
build: process.env.CIRCLE_BUILD_NUM || process.env.SAUCE_BUILD_ID || Date.now()
},
// mobile emulators are really slow
captureTimeout: 300000,
browserNoActivityTimeout: 300000
}))
}
| build/karma.sauce.config.js | 0 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.00017620633298065513,
0.00017159097478725016,
0.00016576053167227656,
0.00017170723003800958,
0.0000029451002774294466
] |
{
"id": 5,
"code_window": [
" key: string | number | void;\n",
" componentOptions: VNodeComponentOptions | void;\n",
" child: Component | void;\n",
" parent: VNode | void;\n",
" raw: ?boolean;\n",
" isStatic: ?boolean;\n",
"\n",
" constructor (\n",
" tag?: string,\n",
" data?: VNodeData,\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" child: Component | void; // component instance\n",
" parent: VNode | void; // compoennt placeholder node\n",
" raw: ?boolean; // contains raw HTML\n",
" isStatic: ?boolean; // hoisted static node\n",
" isRootInsert: boolean; // necessary for enter transition check\n"
],
"file_path": "src/core/vdom/vnode.js",
"type": "replace",
"edit_start_line_idx": 13
} | /* @flow */
import { bind, toArray } from '../util/index'
import { updateListeners } from '../vdom/helpers'
export function initEvents (vm: Component) {
vm._events = Object.create(null)
// init parent attached events
const listeners = vm.$options._parentListeners
const on = bind(vm.$on, vm)
const off = bind(vm.$off, vm)
vm._updateListeners = (listeners, oldListeners) => {
updateListeners(listeners, oldListeners || {}, on, off)
}
if (listeners) {
vm._updateListeners(listeners)
}
}
export function eventsMixin (Vue: Class<Component>) {
Vue.prototype.$on = function (event: string, fn: Function): Component {
const vm: Component = this
;(vm._events[event] || (vm._events[event] = [])).push(fn)
return vm
}
Vue.prototype.$once = function (event: string, fn: Function): Component {
const vm: Component = this
function on () {
vm.$off(event, on)
fn.apply(vm, arguments)
}
on.fn = fn
vm.$on(event, on)
return vm
}
Vue.prototype.$off = function (event?: string, fn?: Function): Component {
const vm: Component = this
// all
if (!arguments.length) {
vm._events = Object.create(null)
return vm
}
// specific event
const cbs = vm._events[event]
if (!cbs) {
return vm
}
if (arguments.length === 1) {
vm._events[event] = null
return vm
}
// specific handler
let cb
let i = cbs.length
while (i--) {
cb = cbs[i]
if (cb === fn || cb.fn === fn) {
cbs.splice(i, 1)
break
}
}
return vm
}
Vue.prototype.$emit = function (event: string): Component {
const vm: Component = this
let cbs = vm._events[event]
if (cbs) {
cbs = cbs.length > 1 ? toArray(cbs) : cbs
const args = toArray(arguments, 1)
for (let i = 0, l = cbs.length; i < l; i++) {
cbs[i].apply(vm, args)
}
}
return vm
}
}
| src/core/instance/events.js | 0 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.0007593774353154004,
0.00034757613320834935,
0.00017182120063807815,
0.00028550007846206427,
0.00019608464208431542
] |
{
"id": 6,
"code_window": [
" this.child = undefined\n",
" this.parent = undefined\n",
" this.raw = false\n",
" this.isStatic = false\n",
" // apply construct hook.\n",
" // this is applied during render, before patch happens.\n",
" // unlike other hooks, this is applied on both client and server.\n",
" const constructHook = data && data.hook && data.hook.construct\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.isRootInsert = true\n"
],
"file_path": "src/core/vdom/vnode.js",
"type": "add",
"edit_start_line_idx": 43
} | /* @flow */
export default class VNode {
tag: string | void;
data: VNodeData | void;
children: Array<VNode> | void;
text: string | void;
elm: Node | void;
ns: string | void;
context: Component | void;
host: ?Component;
key: string | number | void;
componentOptions: VNodeComponentOptions | void;
child: Component | void;
parent: VNode | void;
raw: ?boolean;
isStatic: ?boolean;
constructor (
tag?: string,
data?: VNodeData,
children?: Array<VNode> | void,
text?: string,
elm?: Node,
ns?: string | void,
context?: Component,
host?: ?Component,
componentOptions?: VNodeComponentOptions
) {
this.tag = tag
this.data = data
this.children = children
this.text = text
this.elm = elm
this.ns = ns
this.context = context
this.host = host
this.key = data && data.key
this.componentOptions = componentOptions
this.child = undefined
this.parent = undefined
this.raw = false
this.isStatic = false
// apply construct hook.
// this is applied during render, before patch happens.
// unlike other hooks, this is applied on both client and server.
const constructHook = data && data.hook && data.hook.construct
if (constructHook) {
constructHook(this)
}
}
}
export const emptyVNode = () => new VNode(undefined, undefined, undefined, '')
| src/core/vdom/vnode.js | 1 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.9984923601150513,
0.16777318716049194,
0.0001695065584499389,
0.0013011867413297296,
0.37151315808296204
] |
{
"id": 6,
"code_window": [
" this.child = undefined\n",
" this.parent = undefined\n",
" this.raw = false\n",
" this.isStatic = false\n",
" // apply construct hook.\n",
" // this is applied during render, before patch happens.\n",
" // unlike other hooks, this is applied on both client and server.\n",
" const constructHook = data && data.hook && data.hook.construct\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.isRootInsert = true\n"
],
"file_path": "src/core/vdom/vnode.js",
"type": "add",
"edit_start_line_idx": 43
} | {
"env": {
"jasmine": true
}
}
| test/ssr/.eslintrc | 0 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.0001710049546090886,
0.0001710049546090886,
0.0001710049546090886,
0.0001710049546090886,
0
] |
{
"id": 6,
"code_window": [
" this.child = undefined\n",
" this.parent = undefined\n",
" this.raw = false\n",
" this.isStatic = false\n",
" // apply construct hook.\n",
" // this is applied during render, before patch happens.\n",
" // unlike other hooks, this is applied on both client and server.\n",
" const constructHook = data && data.hook && data.hook.construct\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.isRootInsert = true\n"
],
"file_path": "src/core/vdom/vnode.js",
"type": "add",
"edit_start_line_idx": 43
} | /* @flow */
import Watcher from '../observer/watcher'
import { emptyVNode } from '../vdom/vnode'
import { observerState } from '../observer/index'
import { warn, validateProp, remove, noop } from '../util/index'
export function initLifecycle (vm: Component) {
const options = vm.$options
// locate first non-abstract parent
let parent = options.parent
if (parent && !options.abstract) {
while (parent.$options.abstract && parent.$parent) {
parent = parent.$parent
}
parent.$children.push(vm)
}
vm.$parent = parent
vm.$root = parent ? parent.$root : vm
vm.$children = []
vm.$refs = {}
vm._watcher = null
vm._inactive = false
vm._isMounted = false
vm._isDestroyed = false
vm._isBeingDestroyed = false
}
export function lifecycleMixin (Vue: Class<Component>) {
Vue.prototype._mount = function (
el?: Element | void,
hydrating?: boolean
): Component {
const vm: Component = this
vm.$el = el
if (!vm.$options.render) {
vm.$options.render = emptyVNode
if (process.env.NODE_ENV !== 'production') {
/* istanbul ignore if */
if (vm.$options.template) {
warn(
'You are using the runtime-only build of Vue where the template ' +
'option is not available. Either pre-compile the templates into ' +
'render functions, or use the compiler-included build.',
vm
)
} else {
warn(
'Failed to mount component: template or render function not defined.',
vm
)
}
}
}
callHook(vm, 'beforeMount')
vm._watcher = new Watcher(vm, () => {
vm._update(vm._render(), hydrating)
}, noop)
hydrating = false
// root instance, call mounted on self
// mounted is called for child components in its inserted hook
if (vm.$root === vm) {
vm._isMounted = true
callHook(vm, 'mounted')
}
return vm
}
Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {
const vm: Component = this
if (vm._isMounted) {
callHook(vm, 'beforeUpdate')
}
const prevEl = vm.$el
if (!vm._vnode) {
// Vue.prototype.__patch__ is injected in entry points
// based on the rendering backend used.
vm.$el = vm.__patch__(vm.$el, vnode, hydrating)
} else {
vm.$el = vm.__patch__(vm._vnode, vnode)
}
vm._vnode = vnode
// update __vue__ reference
if (prevEl) {
prevEl.__vue__ = null
}
if (vm.$el) {
vm.$el.__vue__ = vm
}
// if parent is an HOC, update its $el as well
if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {
vm.$parent.$el = vm.$el
}
if (vm._isMounted) {
callHook(vm, 'updated')
}
}
Vue.prototype._updateFromParent = function (
propsData: ?Object,
listeners: ?Object,
parentVnode: VNode,
renderChildren: ?VNodeChildren
) {
const vm: Component = this
vm.$options._parentVnode = parentVnode
vm.$options._renderChildren = renderChildren
// update props
if (propsData && vm.$options.props) {
observerState.shouldConvert = false
if (process.env.NODE_ENV !== 'production') {
observerState.isSettingProps = true
}
const propKeys = vm.$options._propKeys || []
for (let i = 0; i < propKeys.length; i++) {
const key = propKeys[i]
vm[key] = validateProp(key, vm.$options.props, propsData, vm)
}
observerState.shouldConvert = true
if (process.env.NODE_ENV !== 'production') {
observerState.isSettingProps = false
}
}
// update listeners
if (listeners) {
const oldListeners = vm.$options._parentListeners
vm.$options._parentListeners = listeners
vm._updateListeners(listeners, oldListeners)
}
}
Vue.prototype.$forceUpdate = function () {
const vm: Component = this
if (vm._watcher) {
vm._watcher.update()
}
if (vm._watchers.length) {
for (let i = 0; i < vm._watchers.length; i++) {
vm._watchers[i].update(true /* shallow */)
}
}
}
Vue.prototype.$destroy = function () {
const vm: Component = this
if (vm._isBeingDestroyed) {
return
}
callHook(vm, 'beforeDestroy')
vm._isBeingDestroyed = true
// remove self from parent
const parent = vm.$parent
if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) {
remove(parent.$children, vm)
}
// teardown watchers
if (vm._watcher) {
vm._watcher.teardown()
}
let i = vm._watchers.length
while (i--) {
vm._watchers[i].teardown()
}
// remove reference from data ob
// frozen object may not have observer.
if (vm._data.__ob__) {
vm._data.__ob__.vmCount--
}
// call the last hook...
vm._isDestroyed = true
callHook(vm, 'destroyed')
// turn off all instance listeners.
vm.$off()
// remove __vue__ reference
if (vm.$el) {
vm.$el.__vue__ = null
}
}
}
export function callHook (vm: Component, hook: string) {
const handlers = vm.$options[hook]
if (handlers) {
for (let i = 0, j = handlers.length; i < j; i++) {
handlers[i].call(vm)
}
}
vm.$emit('hook:' + hook)
}
| src/core/instance/lifecycle.js | 0 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.0029104757122695446,
0.00037005817284807563,
0.0001659987319726497,
0.0001791394461179152,
0.0005908627063035965
] |
{
"id": 6,
"code_window": [
" this.child = undefined\n",
" this.parent = undefined\n",
" this.raw = false\n",
" this.isStatic = false\n",
" // apply construct hook.\n",
" // this is applied during render, before patch happens.\n",
" // unlike other hooks, this is applied on both client and server.\n",
" const constructHook = data && data.hook && data.hook.construct\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this.isRootInsert = true\n"
],
"file_path": "src/core/vdom/vnode.js",
"type": "add",
"edit_start_line_idx": 43
} | /* @flow */
import { addProp } from 'compiler/helpers'
export default function html (el: ASTElement, dir: ASTDirective) {
if (dir.value) {
addProp(el, 'innerHTML', `_s(${dir.value})`)
}
}
| src/platforms/web/compiler/directives/html.js | 0 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.00016957995831035078,
0.00016957995831035078,
0.00016957995831035078,
0.00016957995831035078,
0
] |
{
"id": 7,
"code_window": [
" afterAppear,\n",
" appearCancelled\n",
" } = data\n",
"\n",
" const context = vnode.context.$parent || vnode.context\n",
" const isAppear = !context._isMounted\n",
" if (isAppear && !appear && appear !== '') {\n",
" return\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const isAppear = !context._isMounted || !vnode.isRootInsert\n"
],
"file_path": "src/platforms/web/runtime/modules/transition.js",
"type": "replace",
"edit_start_line_idx": 50
} | /**
* Virtual DOM implementation based on Snabbdom by
* Simon Friis Vindum (@paldepind)
* with custom modifications.
*
* Not type-checking this because this file is perf-critical and the cost
* of making flow understand it is not worth it.
*/
import config from '../config'
import VNode from './vnode'
import { isPrimitive, _toString, warn } from '../util/index'
const emptyData = {}
const emptyNode = new VNode('', emptyData, [])
const hooks = ['create', 'update', 'postpatch', 'remove', 'destroy']
function isUndef (s) {
return s == null
}
function isDef (s) {
return s != null
}
function sameVnode (vnode1, vnode2) {
if (vnode1.isStatic || vnode2.isStatic) {
return vnode1 === vnode2
}
return (
vnode1.key === vnode2.key &&
vnode1.tag === vnode2.tag &&
!vnode1.data === !vnode2.data
)
}
function createKeyToOldIdx (children, beginIdx, endIdx) {
let i, key
const map = {}
for (i = beginIdx; i <= endIdx; ++i) {
key = children[i].key
if (isDef(key)) map[key] = i
}
return map
}
export function createPatchFunction (backend) {
let i, j
const cbs = {}
const { modules, nodeOps } = backend
for (i = 0; i < hooks.length; ++i) {
cbs[hooks[i]] = []
for (j = 0; j < modules.length; ++j) {
if (modules[j][hooks[i]] !== undefined) cbs[hooks[i]].push(modules[j][hooks[i]])
}
}
function emptyNodeAt (elm) {
return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm)
}
function createRmCb (childElm, listeners) {
function remove () {
if (--remove.listeners === 0) {
removeElement(childElm)
}
}
remove.listeners = listeners
return remove
}
function removeElement (el) {
const parent = nodeOps.parentNode(el)
nodeOps.removeChild(parent, el)
}
function createElm (vnode, insertedVnodeQueue) {
let i, elm
const data = vnode.data
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode)
// after calling the init hook, if the vnode is a child component
// it should've created a child instance and mounted it. the child
// component also has set the placeholder vnode's elm.
// in that case we can just return the element and be done.
if (isDef(i = vnode.child)) {
if (vnode.data.pendingInsert) {
insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert)
}
vnode.elm = vnode.child.$el
invokeCreateHooks(vnode, insertedVnodeQueue)
setScope(vnode)
return vnode.elm
}
}
const children = vnode.children
const tag = vnode.tag
if (isDef(tag)) {
if (process.env.NODE_ENV !== 'production') {
if (
!vnode.ns &&
!(config.ignoredElements && config.ignoredElements.indexOf(tag) > -1) &&
config.isUnknownElement(tag)
) {
warn(
'Unknown custom element: <' + tag + '> - did you ' +
'register the component correctly? For recursive components, ' +
'make sure to provide the "name" option.',
vnode.context
)
}
}
elm = vnode.elm = vnode.ns
? nodeOps.createElementNS(vnode.ns, tag)
: nodeOps.createElement(tag)
setScope(vnode)
if (Array.isArray(children)) {
for (i = 0; i < children.length; ++i) {
nodeOps.appendChild(elm, createElm(children[i], insertedVnodeQueue))
}
} else if (isPrimitive(vnode.text)) {
nodeOps.appendChild(elm, nodeOps.createTextNode(vnode.text))
}
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue)
}
} else {
elm = vnode.elm = nodeOps.createTextNode(vnode.text)
}
return vnode.elm
}
function invokeCreateHooks (vnode, insertedVnodeQueue) {
for (let i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, vnode)
}
i = vnode.data.hook // Reuse variable
if (isDef(i)) {
if (i.create) i.create(emptyNode, vnode)
if (i.insert) insertedVnodeQueue.push(vnode)
}
}
// set scope id attribute for scoped CSS.
// this is implemented as a special case to avoid the overhead
// of going through the normal attribute patching process.
function setScope (vnode) {
let i
if (isDef(i = vnode.host) && isDef(i = i.$options._scopeId)) {
nodeOps.setAttribute(vnode.elm, i, '')
}
if (isDef(i = vnode.context) && isDef(i = i.$options._scopeId)) {
nodeOps.setAttribute(vnode.elm, i, '')
}
}
function addVnodes (parentElm, before, vnodes, startIdx, endIdx, insertedVnodeQueue) {
for (; startIdx <= endIdx; ++startIdx) {
nodeOps.insertBefore(parentElm, createElm(vnodes[startIdx], insertedVnodeQueue), before)
}
}
function invokeDestroyHook (vnode) {
let i, j
const data = vnode.data
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.destroy)) i(vnode)
for (i = 0; i < cbs.destroy.length; ++i) cbs.destroy[i](vnode)
}
if (isDef(i = vnode.child) && !data.keepAlive) {
invokeDestroyHook(i._vnode)
}
if (isDef(i = vnode.children)) {
for (j = 0; j < vnode.children.length; ++j) {
invokeDestroyHook(vnode.children[j])
}
}
}
function removeVnodes (parentElm, vnodes, startIdx, endIdx) {
for (; startIdx <= endIdx; ++startIdx) {
const ch = vnodes[startIdx]
if (isDef(ch)) {
if (isDef(ch.tag)) {
invokeDestroyHook(ch)
removeAndInvokeRemoveHook(ch)
} else { // Text node
nodeOps.removeChild(parentElm, ch.elm)
}
}
}
}
function removeAndInvokeRemoveHook (vnode, rm) {
if (rm || isDef(vnode.data)) {
const listeners = cbs.remove.length + 1
if (!rm) {
// directly removing
rm = createRmCb(vnode.elm, listeners)
} else {
// we have a recursively passed down rm callback
// increase the listeners count
rm.listeners += listeners
}
// recursively invoke hooks on child component root node
if (isDef(i = vnode.child) && isDef(i = i._vnode) && isDef(i.data)) {
removeAndInvokeRemoveHook(i, rm)
}
for (i = 0; i < cbs.remove.length; ++i) {
cbs.remove[i](vnode, rm)
}
if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) {
i(vnode, rm)
} else {
rm()
}
} else {
removeElement(vnode.elm)
}
}
function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) {
let oldStartIdx = 0
let newStartIdx = 0
let oldEndIdx = oldCh.length - 1
let oldStartVnode = oldCh[0]
let oldEndVnode = oldCh[oldEndIdx]
let newEndIdx = newCh.length - 1
let newStartVnode = newCh[0]
let newEndVnode = newCh[newEndIdx]
let oldKeyToIdx, idxInOld, elmToMove, before
// removeOnly is a special flag used only by <transition-group>
// to ensure removed elements stay in correct relative positions
// during leaving transitions
const canMove = !removeOnly
while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
if (isUndef(oldStartVnode)) {
oldStartVnode = oldCh[++oldStartIdx] // Vnode has been moved left
} else if (isUndef(oldEndVnode)) {
oldEndVnode = oldCh[--oldEndIdx]
} else if (sameVnode(oldStartVnode, newStartVnode)) {
patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue)
oldStartVnode = oldCh[++oldStartIdx]
newStartVnode = newCh[++newStartIdx]
} else if (sameVnode(oldEndVnode, newEndVnode)) {
patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue)
oldEndVnode = oldCh[--oldEndIdx]
newEndVnode = newCh[--newEndIdx]
} else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right
patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue)
canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm))
oldStartVnode = oldCh[++oldStartIdx]
newEndVnode = newCh[--newEndIdx]
} else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left
patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue)
canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm)
oldEndVnode = oldCh[--oldEndIdx]
newStartVnode = newCh[++newStartIdx]
} else {
if (isUndef(oldKeyToIdx)) oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx)
idxInOld = isDef(newStartVnode.key)
? oldKeyToIdx[newStartVnode.key]
: newStartVnode.isStatic
? oldCh.indexOf(newStartVnode)
: null
if (isUndef(idxInOld) || idxInOld === -1) { // New element
nodeOps.insertBefore(parentElm, createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm)
newStartVnode = newCh[++newStartIdx]
} else {
elmToMove = oldCh[idxInOld]
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && !elmToMove) {
warn(
'It seems there are duplicate keys that is causing an update error. ' +
'Make sure each v-for item has a unique key.'
)
}
if (elmToMove.tag !== newStartVnode.tag) {
// same key but different element. treat as new element
nodeOps.insertBefore(parentElm, createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm)
newStartVnode = newCh[++newStartIdx]
} else {
patchVnode(elmToMove, newStartVnode, insertedVnodeQueue)
oldCh[idxInOld] = undefined
canMove && nodeOps.insertBefore(parentElm, newStartVnode.elm, oldStartVnode.elm)
newStartVnode = newCh[++newStartIdx]
}
}
}
}
if (oldStartIdx > oldEndIdx) {
before = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm
addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx, insertedVnodeQueue)
} else if (newStartIdx > newEndIdx) {
removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx)
}
}
function patchVnode (oldVnode, vnode, insertedVnodeQueue, removeOnly) {
if (oldVnode === vnode) return
let i, hook
const hasData = isDef(i = vnode.data)
if (hasData && isDef(hook = i.hook) && isDef(i = hook.prepatch)) {
i(oldVnode, vnode)
}
const elm = vnode.elm = oldVnode.elm
const oldCh = oldVnode.children
const ch = vnode.children
if (hasData) {
for (i = 0; i < cbs.update.length; ++i) cbs.update[i](oldVnode, vnode)
if (isDef(hook) && isDef(i = hook.update)) i(oldVnode, vnode)
}
if (isUndef(vnode.text)) {
if (isDef(oldCh) && isDef(ch)) {
if (oldCh !== ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly)
} else if (isDef(ch)) {
if (isDef(oldVnode.text)) nodeOps.setTextContent(elm, '')
addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue)
} else if (isDef(oldCh)) {
removeVnodes(elm, oldCh, 0, oldCh.length - 1)
} else if (isDef(oldVnode.text)) {
nodeOps.setTextContent(elm, '')
}
} else if (oldVnode.text !== vnode.text) {
nodeOps.setTextContent(elm, vnode.text)
}
if (hasData) {
for (i = 0; i < cbs.postpatch.length; ++i) cbs.postpatch[i](oldVnode, vnode)
if (isDef(hook) && isDef(i = hook.postpatch)) i(oldVnode, vnode)
}
}
function invokeInsertHook (vnode, queue, initial) {
// delay insert hooks for component root nodes, invoke them after the
// element is really inserted
if (initial && vnode.parent) {
vnode.parent.data.pendingInsert = queue
} else {
for (let i = 0; i < queue.length; ++i) {
queue[i].data.hook.insert(queue[i])
}
}
}
let bailed = false
function hydrate (elm, vnode, insertedVnodeQueue) {
if (process.env.NODE_ENV !== 'production') {
if (!assertNodeMatch(elm, vnode)) {
return false
}
}
vnode.elm = elm
const { tag, data, children } = vnode
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode, true /* hydrating */)
if (isDef(i = vnode.child)) {
// child component. it should have hydrated its own tree.
invokeCreateHooks(vnode, insertedVnodeQueue)
return true
}
}
if (isDef(tag)) {
if (isDef(children)) {
const childNodes = nodeOps.childNodes(elm)
let childrenMatch = true
if (childNodes.length !== children.length) {
childrenMatch = false
} else {
for (let i = 0; i < children.length; i++) {
if (!hydrate(childNodes[i], children[i], insertedVnodeQueue)) {
childrenMatch = false
break
}
}
}
if (!childrenMatch) {
if (process.env.NODE_ENV !== 'production' &&
typeof console !== 'undefined' &&
!bailed) {
bailed = true
console.warn('Parent: ', elm)
console.warn('Mismatching childNodes vs. VNodes: ', childNodes, children)
}
return false
}
}
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue)
}
}
return true
}
function assertNodeMatch (node, vnode) {
let match = true
if (!node) {
match = false
} else if (vnode.tag) {
match =
vnode.tag.indexOf('vue-component') === 0 ||
vnode.tag === nodeOps.tagName(node).toLowerCase()
} else {
match = _toString(vnode.text) === node.data
}
return match
}
return function patch (oldVnode, vnode, hydrating, removeOnly) {
let elm, parent
let isInitialPatch = false
const insertedVnodeQueue = []
if (!oldVnode) {
// empty mount, create new root element
isInitialPatch = true
createElm(vnode, insertedVnodeQueue)
} else {
const isRealElement = isDef(oldVnode.nodeType)
if (!isRealElement && sameVnode(oldVnode, vnode)) {
patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly)
} else {
if (isRealElement) {
// mounting to a real element
// check if this is server-rendered content and if we can perform
// a successful hydration.
if (oldVnode.hasAttribute('server-rendered')) {
oldVnode.removeAttribute('server-rendered')
hydrating = true
}
if (hydrating) {
if (hydrate(oldVnode, vnode, insertedVnodeQueue)) {
invokeInsertHook(vnode, insertedVnodeQueue, true)
return oldVnode
} else if (process.env.NODE_ENV !== 'production') {
warn(
'The client-side rendered virtual DOM tree is not matching ' +
'server-rendered content. This is likely caused by incorrect ' +
'HTML markup, for example nesting block-level elements inside ' +
'<p>, or missing <tbody>. Bailing hydration and performing ' +
'full client-side render.'
)
}
}
// either not server-rendered, or hydration failed.
// create an empty node and replace it
oldVnode = emptyNodeAt(oldVnode)
}
elm = oldVnode.elm
parent = nodeOps.parentNode(elm)
createElm(vnode, insertedVnodeQueue)
// component root element replaced.
// update parent placeholder node element.
if (vnode.parent) {
vnode.parent.elm = vnode.elm
for (let i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, vnode.parent)
}
}
if (parent !== null) {
nodeOps.insertBefore(parent, vnode.elm, nodeOps.nextSibling(elm))
removeVnodes(parent, [oldVnode], 0, 0)
} else if (isDef(oldVnode.tag)) {
invokeDestroyHook(oldVnode)
}
}
}
invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch)
return vnode.elm
}
}
| src/core/vdom/patch.js | 1 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.27158844470977783,
0.006842298433184624,
0.00016419436724390835,
0.0004896002355962992,
0.03866581991314888
] |
{
"id": 7,
"code_window": [
" afterAppear,\n",
" appearCancelled\n",
" } = data\n",
"\n",
" const context = vnode.context.$parent || vnode.context\n",
" const isAppear = !context._isMounted\n",
" if (isAppear && !appear && appear !== '') {\n",
" return\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const isAppear = !context._isMounted || !vnode.isRootInsert\n"
],
"file_path": "src/platforms/web/runtime/modules/transition.js",
"type": "replace",
"edit_start_line_idx": 50
} | /* @flow */
export function parseFilters (exp: string): string {
let inSingle = false
let inDouble = false
let curly = 0
let square = 0
let paren = 0
let lastFilterIndex = 0
let c, prev, i, expression, filters
for (i = 0; i < exp.length; i++) {
prev = c
c = exp.charCodeAt(i)
if (inSingle) {
// check single quote
if (c === 0x27 && prev !== 0x5C) inSingle = !inSingle
} else if (inDouble) {
// check double quote
if (c === 0x22 && prev !== 0x5C) inDouble = !inDouble
} else if (
c === 0x7C && // pipe
exp.charCodeAt(i + 1) !== 0x7C &&
exp.charCodeAt(i - 1) !== 0x7C &&
!curly && !square && !paren
) {
if (expression === undefined) {
// first filter, end of expression
lastFilterIndex = i + 1
expression = exp.slice(0, i).trim()
} else {
pushFilter()
}
} else {
switch (c) {
case 0x22: inDouble = true; break // "
case 0x27: inSingle = true; break // '
case 0x28: paren++; break // (
case 0x29: paren--; break // )
case 0x5B: square++; break // [
case 0x5D: square--; break // ]
case 0x7B: curly++; break // {
case 0x7D: curly--; break // }
}
}
}
if (expression === undefined) {
expression = exp.slice(0, i).trim()
} else if (lastFilterIndex !== 0) {
pushFilter()
}
function pushFilter () {
(filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim())
lastFilterIndex = i + 1
}
if (filters) {
for (i = 0; i < filters.length; i++) {
expression = wrapFilter(expression, filters[i])
}
}
return expression
}
function wrapFilter (exp: string, filter: string): string {
const i = filter.indexOf('(')
if (i < 0) {
// _f: resolveFilter
return `_f("${filter}")(${exp})`
} else {
const name = filter.slice(0, i)
const args = filter.slice(i + 1)
return `_f("${name}")(${exp},${args}`
}
}
| src/compiler/parser/filter-parser.js | 0 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.00017469018348492682,
0.0001727766648400575,
0.00017031906463671476,
0.00017350915004499257,
0.0000015403467159558204
] |
{
"id": 7,
"code_window": [
" afterAppear,\n",
" appearCancelled\n",
" } = data\n",
"\n",
" const context = vnode.context.$parent || vnode.context\n",
" const isAppear = !context._isMounted\n",
" if (isAppear && !appear && appear !== '') {\n",
" return\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const isAppear = !context._isMounted || !vnode.isRootInsert\n"
],
"file_path": "src/platforms/web/runtime/modules/transition.js",
"type": "replace",
"edit_start_line_idx": 50
} | import { callHook } from 'core/instance/lifecycle'
import { getRealChild } from 'core/vdom/helpers'
export default {
name: 'keep-alive',
abstract: true,
props: {
child: Object
},
created () {
this.cache = Object.create(null)
},
render () {
const rawChild = this.child
const realChild = getRealChild(this.child)
if (realChild && realChild.componentOptions) {
const opts = realChild.componentOptions
// same constructor may get registered as different local components
// so cid alone is not enough (#3269)
const key = opts.Ctor.cid + '::' + opts.tag
if (this.cache[key]) {
const child = realChild.child = this.cache[key].child
realChild.elm = this.$el = child.$el
} else {
this.cache[key] = realChild
}
realChild.data.keepAlive = true
}
return rawChild
},
destroyed () {
for (const key in this.cache) {
const vnode = this.cache[key]
callHook(vnode.child, 'deactivated')
vnode.child.$destroy()
}
}
}
| src/core/components/keep-alive.js | 0 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.003544439561665058,
0.0010232912609353662,
0.00016912490536924452,
0.0001898002519737929,
0.0014556406531482935
] |
{
"id": 7,
"code_window": [
" afterAppear,\n",
" appearCancelled\n",
" } = data\n",
"\n",
" const context = vnode.context.$parent || vnode.context\n",
" const isAppear = !context._isMounted\n",
" if (isAppear && !appear && appear !== '') {\n",
" return\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const isAppear = !context._isMounted || !vnode.isRootInsert\n"
],
"file_path": "src/platforms/web/runtime/modules/transition.js",
"type": "replace",
"edit_start_line_idx": 50
} | import Vue from 'vue'
describe('Global config', () => {
it('should warn replacing config object', () => {
const originalConfig = Vue.config
Vue.config = {}
expect(Vue.config).toBe(originalConfig)
expect('Do not replace the Vue.config object').toHaveBeenWarned()
})
describe('silent', () => {
it('should be false by default', () => {
Vue.util.warn('foo')
expect('foo').toHaveBeenWarned()
})
it('should work when set to true', () => {
Vue.config.silent = true
Vue.util.warn('foo')
expect('foo').not.toHaveBeenWarned()
Vue.config.silent = false
})
})
describe('errorHandler', () => {
it('should be called with correct args', () => {
const spy = jasmine.createSpy('errorHandler')
Vue.config.errorHandler = spy
const err = new Error()
const vm = new Vue({
render () { throw err }
}).$mount()
expect(spy).toHaveBeenCalledWith(err, vm)
Vue.config.errorHandler = null
})
it('should capture user watcher callback errors', done => {
const spy = jasmine.createSpy('errorHandler')
Vue.config.errorHandler = spy
const err = new Error()
const vm = new Vue({
data: { a: 1 },
watch: {
a: () => {
throw err
}
}
}).$mount()
vm.a = 2
waitForUpdate(() => {
expect(spy).toHaveBeenCalledWith(err, vm)
Vue.config.errorHandler = null
}).then(done)
})
})
describe('optionMergeStrategies', () => {
it('should allow defining custom option merging strategies', () => {
const spy = jasmine.createSpy('option merging')
Vue.config.optionMergeStrategies.__test__ = (parent, child, vm) => {
spy(parent, child, vm)
return child + 1
}
const Test = Vue.extend({
__test__: 1
})
expect(spy.calls.count()).toBe(1)
expect(spy).toHaveBeenCalledWith(undefined, 1, undefined)
expect(Test.options.__test__).toBe(2)
const test = new Test({
__test__: 2
})
expect(spy.calls.count()).toBe(2)
expect(spy).toHaveBeenCalledWith(2, 2, test)
expect(test.$options.__test__).toBe(3)
})
})
})
| test/unit/features/global-api/config.spec.js | 0 | https://github.com/vuejs/vue/commit/40b93e6527d9ecdb308925114bf14cb60b36eae0 | [
0.00017712556291371584,
0.0001740916632115841,
0.00017022716929204762,
0.00017440252122469246,
0.000002215097538282862
] |
{
"id": 0,
"code_window": [
" margin: ${({ theme }) => theme.gridUnit * GUTTER_SIZE_FACTOR}px auto;\n",
" }\n",
"\n",
" .gutter.gutter-vertical {\n",
" cursor: row-resize;\n",
" }\n",
"\n",
" .ant-collapse {\n",
" .ant-tabs {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" display: ${({ showSplite }) => (showSplite ? 'block' : 'none')};\n"
],
"file_path": "superset-frontend/src/explore/components/ExploreChartPanel.jsx",
"type": "add",
"edit_start_line_idx": 100
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import userEvent from '@testing-library/user-event';
import { render, screen } from 'spec/helpers/testing-library';
import { getChartMetadataRegistry, ChartMetadata } from '@superset-ui/core';
import ChartContainer from 'src/explore/components/ExploreChartPanel';
const createProps = (overrides = {}) => ({
sliceName: 'Trend Line',
height: '500px',
actions: {},
can_overwrite: false,
can_download: false,
containerId: 'foo',
width: '500px',
isStarred: false,
vizType: 'histogram',
chart: {
id: 1,
latestQueryFormData: {
viz_type: 'histogram',
datasource: '49__table',
slice_id: 318,
url_params: {},
granularity_sqla: 'time_start',
time_range: 'No filter',
all_columns_x: ['age'],
adhoc_filters: [],
row_limit: 10000,
groupby: null,
color_scheme: 'supersetColors',
label_colors: {},
link_length: '25',
x_axis_label: 'age',
y_axis_label: 'count',
},
chartStatus: 'rendered',
queriesResponse: [{ is_cached: true }],
},
...overrides,
});
describe('ChartContainer', () => {
test('renders when vizType is line', () => {
const props = createProps();
expect(React.isValidElement(<ChartContainer {...props} />)).toBe(true);
});
test('renders with alert banner', async () => {
const props = createProps({
chartIsStale: true,
chart: { chartStatus: 'rendered', queriesResponse: [{}] },
});
getChartMetadataRegistry().registerValue(
'histogram',
new ChartMetadata({
name: 'fake table',
thumbnail: '.png',
useLegacyApi: false,
}),
);
render(<ChartContainer {...props} />, { useRedux: true });
expect(
await screen.findByText('Your chart is not up to date'),
).toBeVisible();
});
test('doesnt render alert banner when no changes in control panel were made (chart is not stale)', async () => {
const props = createProps({
chartIsStale: false,
});
render(<ChartContainer {...props} />, { useRedux: true });
expect(await screen.findByText(/cached/i)).toBeInTheDocument();
expect(
screen.queryByText('Your chart is not up to date'),
).not.toBeInTheDocument();
});
test('doesnt render alert banner when chart not created yet (no queries response)', async () => {
const props = createProps({
chartIsStale: true,
chart: { queriesResponse: [] },
});
render(<ChartContainer {...props} />, { useRedux: true });
expect(await screen.findByRole('timer')).toBeInTheDocument();
expect(
screen.queryByText('Your chart is not up to date'),
).not.toBeInTheDocument();
});
test('renders prompt to fill required controls when required control removed', async () => {
const props = createProps({
chartIsStale: true,
chart: { chartStatus: 'rendered', queriesResponse: [{}] },
errorMessage: 'error',
});
render(<ChartContainer {...props} />, { useRedux: true });
expect(
await screen.findByText('Required control values have been removed'),
).toBeVisible();
});
test('should render cached button and call expected actions', async () => {
const setForceQuery = jest.fn();
const postChartFormData = jest.fn();
const updateQueryFormData = jest.fn();
const props = createProps({
actions: {
setForceQuery,
postChartFormData,
updateQueryFormData,
},
});
render(<ChartContainer {...props} />, { useRedux: true });
const cached = await screen.findByText('Cached');
expect(cached).toBeInTheDocument();
userEvent.click(cached);
expect(setForceQuery).toHaveBeenCalledTimes(1);
expect(postChartFormData).toHaveBeenCalledTimes(1);
expect(updateQueryFormData).toHaveBeenCalledTimes(1);
});
test('should hide cached button', async () => {
const props = createProps({
chart: {
chartStatus: 'rendered',
queriesResponse: [{ is_cached: false }],
},
});
render(<ChartContainer {...props} />, { useRedux: true });
expect(await screen.findByRole('timer')).toBeInTheDocument();
expect(screen.queryByText(/cached/i)).not.toBeInTheDocument();
});
});
| superset-frontend/src/explore/components/ExploreChartPanel.test.jsx | 1 | https://github.com/apache/superset/commit/d28909d56c21c160a0140b87c4f268b1c4ea90f1 | [
0.00017907081928569824,
0.0001748243666952476,
0.00017169951752293855,
0.00017426026170141995,
0.0000019341659935889766
] |
{
"id": 0,
"code_window": [
" margin: ${({ theme }) => theme.gridUnit * GUTTER_SIZE_FACTOR}px auto;\n",
" }\n",
"\n",
" .gutter.gutter-vertical {\n",
" cursor: row-resize;\n",
" }\n",
"\n",
" .ant-collapse {\n",
" .ant-tabs {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" display: ${({ showSplite }) => (showSplite ? 'block' : 'none')};\n"
],
"file_path": "superset-frontend/src/explore/components/ExploreChartPanel.jsx",
"type": "add",
"edit_start_line_idx": 100
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { getChartDataUri } from '.';
test('Get ChartUri when allowDomainSharding:false', () => {
expect(
getChartDataUri({
path: '/path',
qs: 'same-string',
allowDomainSharding: false,
}),
).toEqual({
_deferred_build: true,
_parts: {
duplicateQueryParameters: false,
escapeQuerySpace: true,
fragment: null,
hostname: 'localhost',
password: null,
path: '/path',
port: '',
preventInvalidHostname: false,
protocol: 'http',
query: 'same-string',
urn: null,
username: null,
},
_string: '',
});
});
test('Get ChartUri when allowDomainSharding:true', () => {
expect(
getChartDataUri({
path: '/path-allowDomainSharding-true',
qs: 'same-string-allowDomainSharding-true',
allowDomainSharding: true,
}),
).toEqual({
_deferred_build: true,
_parts: {
duplicateQueryParameters: false,
escapeQuerySpace: true,
fragment: null,
hostname: undefined,
password: null,
path: '/path-allowDomainSharding-true',
port: '',
preventInvalidHostname: false,
protocol: 'http',
query: 'same-string-allowDomainSharding-true',
urn: null,
username: null,
},
_string: '',
});
});
| superset-frontend/src/explore/exploreUtils/getChartDataUri.test.ts | 0 | https://github.com/apache/superset/commit/d28909d56c21c160a0140b87c4f268b1c4ea90f1 | [
0.00017755405860953033,
0.0001744900073390454,
0.00017188215861096978,
0.00017446721903979778,
0.0000017737215785018634
] |
{
"id": 0,
"code_window": [
" margin: ${({ theme }) => theme.gridUnit * GUTTER_SIZE_FACTOR}px auto;\n",
" }\n",
"\n",
" .gutter.gutter-vertical {\n",
" cursor: row-resize;\n",
" }\n",
"\n",
" .ant-collapse {\n",
" .ant-tabs {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" display: ${({ showSplite }) => (showSplite ? 'block' : 'none')};\n"
],
"file_path": "superset-frontend/src/explore/components/ExploreChartPanel.jsx",
"type": "add",
"edit_start_line_idx": 100
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import { render, screen } from 'spec/helpers/testing-library';
import userEvent from '@testing-library/user-event';
import ErrorMessageWithStackTrace from './ErrorMessageWithStackTrace';
import { ErrorLevel, ErrorSource } from './types';
const mockedProps = {
level: 'warning' as ErrorLevel,
link: 'https://sample.com',
source: 'dashboard' as ErrorSource,
stackTrace: 'Stacktrace',
};
test('should render', () => {
const { container } = render(<ErrorMessageWithStackTrace {...mockedProps} />);
expect(container).toBeInTheDocument();
});
test('should render the stacktrace', () => {
render(<ErrorMessageWithStackTrace {...mockedProps} />, { useRedux: true });
const button = screen.getByText('See more');
userEvent.click(button);
expect(screen.getByText('Stacktrace')).toBeInTheDocument();
});
test('should render the link', () => {
render(<ErrorMessageWithStackTrace {...mockedProps} />, { useRedux: true });
const button = screen.getByText('See more');
userEvent.click(button);
const link = screen.getByRole('link');
expect(link).toHaveTextContent('(Request Access)');
expect(link).toHaveAttribute('href', mockedProps.link);
});
| superset-frontend/src/components/ErrorMessage/ErrorMessageWithStackTrace.test.tsx | 0 | https://github.com/apache/superset/commit/d28909d56c21c160a0140b87c4f268b1c4ea90f1 | [
0.00017737453163135797,
0.0001742226886563003,
0.00017066793225239962,
0.00017417539493180811,
0.0000023012441943137674
] |
{
"id": 0,
"code_window": [
" margin: ${({ theme }) => theme.gridUnit * GUTTER_SIZE_FACTOR}px auto;\n",
" }\n",
"\n",
" .gutter.gutter-vertical {\n",
" cursor: row-resize;\n",
" }\n",
"\n",
" .ant-collapse {\n",
" .ant-tabs {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" display: ${({ showSplite }) => (showSplite ? 'block' : 'none')};\n"
],
"file_path": "superset-frontend/src/explore/components/ExploreChartPanel.jsx",
"type": "add",
"edit_start_line_idx": 100
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import json
from contextlib import closing
from typing import Any, Dict, Optional
from flask_babel import gettext as __
from superset.commands.base import BaseCommand
from superset.databases.commands.exceptions import (
DatabaseOfflineError,
DatabaseTestConnectionFailedError,
InvalidEngineError,
InvalidParametersError,
)
from superset.databases.dao import DatabaseDAO
from superset.databases.utils import make_url_safe
from superset.db_engine_specs import get_engine_spec
from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
from superset.extensions import event_logger
from superset.models.core import Database
BYPASS_VALIDATION_ENGINES = {"bigquery"}
class ValidateDatabaseParametersCommand(BaseCommand):
def __init__(self, parameters: Dict[str, Any]):
self._properties = parameters.copy()
self._model: Optional[Database] = None
def run(self) -> None:
self.validate()
engine = self._properties["engine"]
driver = self._properties.get("driver")
if engine in BYPASS_VALIDATION_ENGINES:
# Skip engines that are only validated onCreate
return
engine_spec = get_engine_spec(engine, driver)
if not hasattr(engine_spec, "parameters_schema"):
raise InvalidEngineError(
SupersetError(
message=__(
'Engine "%(engine)s" cannot be configured through parameters.',
engine=engine,
),
error_type=SupersetErrorType.GENERIC_DB_ENGINE_ERROR,
level=ErrorLevel.ERROR,
),
)
# perform initial validation
errors = engine_spec.validate_parameters( # type: ignore
self._properties.get("parameters", {})
)
if errors:
event_logger.log_with_context(action="validation_error", engine=engine)
raise InvalidParametersError(errors)
serialized_encrypted_extra = self._properties.get(
"masked_encrypted_extra",
"{}",
)
if self._model:
serialized_encrypted_extra = engine_spec.unmask_encrypted_extra(
self._model.encrypted_extra,
serialized_encrypted_extra,
)
try:
encrypted_extra = json.loads(serialized_encrypted_extra)
except json.decoder.JSONDecodeError:
encrypted_extra = {}
# try to connect
sqlalchemy_uri = engine_spec.build_sqlalchemy_uri( # type: ignore
self._properties.get("parameters"),
encrypted_extra,
)
if self._model and sqlalchemy_uri == self._model.safe_sqlalchemy_uri():
sqlalchemy_uri = self._model.sqlalchemy_uri_decrypted
database = DatabaseDAO.build_db_for_connection_test(
server_cert=self._properties.get("server_cert", ""),
extra=self._properties.get("extra", "{}"),
impersonate_user=self._properties.get("impersonate_user", False),
encrypted_extra=serialized_encrypted_extra,
)
database.set_sqlalchemy_uri(sqlalchemy_uri)
database.db_engine_spec.mutate_db_for_connection_test(database)
engine = database.get_sqla_engine()
try:
with closing(engine.raw_connection()) as conn:
alive = engine.dialect.do_ping(conn)
except Exception as ex:
url = make_url_safe(sqlalchemy_uri)
context = {
"hostname": url.host,
"password": url.password,
"port": url.port,
"username": url.username,
"database": url.database,
}
errors = database.db_engine_spec.extract_errors(ex, context)
raise DatabaseTestConnectionFailedError(errors) from ex
if not alive:
raise DatabaseOfflineError(
SupersetError(
message=__("Database is offline."),
error_type=SupersetErrorType.GENERIC_DB_ENGINE_ERROR,
level=ErrorLevel.ERROR,
),
)
def validate(self) -> None:
database_id = self._properties.get("id")
if database_id is not None:
self._model = DatabaseDAO.find_by_id(database_id)
| superset/databases/commands/validate.py | 0 | https://github.com/apache/superset/commit/d28909d56c21c160a0140b87c4f268b1c4ea90f1 | [
0.00017700940952636302,
0.00017220388690475374,
0.0001677151012700051,
0.00017197683337144554,
0.0000022503852505906252
] |
{
"id": 1,
"code_window": [
" refreshRate: 300,\n",
" });\n",
" const [splitSizes, setSplitSizes] = useState(\n",
" getItem(LocalStorageKeys.chart_split_sizes, INITIAL_SIZES),\n",
" );\n",
"\n",
" const [showDatasetModal, setShowDatasetModal] = useState(false);\n",
"\n",
" const metaDataRegistry = getChartMetadataRegistry();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const [showSplite, setShowSplit] = useState(\n",
" getItem(LocalStorageKeys.is_datapanel_open, false),\n",
" );\n"
],
"file_path": "superset-frontend/src/explore/components/ExploreChartPanel.jsx",
"type": "add",
"edit_start_line_idx": 151
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import PropTypes from 'prop-types';
import Split from 'react-split';
import {
css,
ensureIsArray,
styled,
SupersetClient,
t,
useTheme,
getChartMetadataRegistry,
DatasourceType,
} from '@superset-ui/core';
import { useResizeDetector } from 'react-resize-detector';
import { chartPropShape } from 'src/dashboard/util/propShapes';
import ChartContainer from 'src/components/Chart/ChartContainer';
import {
getItem,
setItem,
LocalStorageKeys,
} from 'src/utils/localStorageHelpers';
import Alert from 'src/components/Alert';
import { SaveDatasetModal } from 'src/SqlLab/components/SaveDatasetModal';
import { getDatasourceAsSaveableDataset } from 'src/utils/datasourceUtils';
import { DataTablesPane } from './DataTablesPane';
import { buildV1ChartDataPayload } from '../exploreUtils';
import { ChartPills } from './ChartPills';
import { ExploreAlert } from './ExploreAlert';
import { getChartRequiredFieldsMissingMessage } from '../../utils/getChartRequiredFieldsMissingMessage';
const propTypes = {
actions: PropTypes.object.isRequired,
onQuery: PropTypes.func,
can_overwrite: PropTypes.bool.isRequired,
can_download: PropTypes.bool.isRequired,
datasource: PropTypes.object,
dashboardId: PropTypes.number,
column_formats: PropTypes.object,
containerId: PropTypes.string.isRequired,
isStarred: PropTypes.bool.isRequired,
slice: PropTypes.object,
sliceName: PropTypes.string,
table_name: PropTypes.string,
vizType: PropTypes.string.isRequired,
form_data: PropTypes.object,
ownState: PropTypes.object,
standalone: PropTypes.bool,
force: PropTypes.bool,
timeout: PropTypes.number,
chartIsStale: PropTypes.bool,
chart: chartPropShape,
errorMessage: PropTypes.node,
triggerRender: PropTypes.bool,
};
const GUTTER_SIZE_FACTOR = 1.25;
const INITIAL_SIZES = [100, 0];
const MIN_SIZES = [300, 65];
const DEFAULT_SOUTH_PANE_HEIGHT_PERCENT = 40;
const Styles = styled.div`
display: flex;
flex-direction: column;
align-items: stretch;
align-content: stretch;
overflow: auto;
box-shadow: none;
height: 100%;
& > div {
height: 100%;
}
.gutter {
border-top: 1px solid ${({ theme }) => theme.colors.grayscale.light2};
border-bottom: 1px solid ${({ theme }) => theme.colors.grayscale.light2};
width: ${({ theme }) => theme.gridUnit * 9}px;
margin: ${({ theme }) => theme.gridUnit * GUTTER_SIZE_FACTOR}px auto;
}
.gutter.gutter-vertical {
cursor: row-resize;
}
.ant-collapse {
.ant-tabs {
height: 100%;
.ant-tabs-nav {
padding-left: ${({ theme }) => theme.gridUnit * 5}px;
margin: 0;
}
.ant-tabs-content-holder {
overflow: hidden;
.ant-tabs-content {
height: 100%;
}
}
}
}
`;
const ExploreChartPanel = ({
chart,
slice,
vizType,
ownState,
triggerRender,
force,
datasource,
errorMessage,
form_data: formData,
onQuery,
actions,
timeout,
standalone,
chartIsStale,
chartAlert,
}) => {
const theme = useTheme();
const gutterMargin = theme.gridUnit * GUTTER_SIZE_FACTOR;
const gutterHeight = theme.gridUnit * GUTTER_SIZE_FACTOR;
const {
width: chartPanelWidth,
height: chartPanelHeight,
ref: chartPanelRef,
} = useResizeDetector({
refreshMode: 'debounce',
refreshRate: 300,
});
const [splitSizes, setSplitSizes] = useState(
getItem(LocalStorageKeys.chart_split_sizes, INITIAL_SIZES),
);
const [showDatasetModal, setShowDatasetModal] = useState(false);
const metaDataRegistry = getChartMetadataRegistry();
const { useLegacyApi } = metaDataRegistry.get(vizType) ?? {};
const vizTypeNeedsDataset =
useLegacyApi && datasource.type !== DatasourceType.Table;
// added boolean column to below show boolean so that the errors aren't overlapping
const showAlertBanner =
!chartAlert &&
chartIsStale &&
!vizTypeNeedsDataset &&
chart.chartStatus !== 'failed' &&
ensureIsArray(chart.queriesResponse).length > 0;
const updateQueryContext = useCallback(
async function fetchChartData() {
if (slice && slice.query_context === null) {
const queryContext = buildV1ChartDataPayload({
formData: slice.form_data,
force,
resultFormat: 'json',
resultType: 'full',
setDataMask: null,
ownState: null,
});
await SupersetClient.put({
endpoint: `/api/v1/chart/${slice.slice_id}`,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query_context: JSON.stringify(queryContext),
query_context_generation: true,
}),
});
}
},
[slice],
);
useEffect(() => {
updateQueryContext();
}, [updateQueryContext]);
useEffect(() => {
setItem(LocalStorageKeys.chart_split_sizes, splitSizes);
}, [splitSizes]);
const onDragEnd = useCallback(sizes => {
setSplitSizes(sizes);
}, []);
const refreshCachedQuery = useCallback(() => {
actions.setForceQuery(true);
actions.postChartFormData(
formData,
true,
timeout,
chart.id,
undefined,
ownState,
);
actions.updateQueryFormData(formData, chart.id);
}, [actions, chart.id, formData, ownState, timeout]);
const onCollapseChange = useCallback(isOpen => {
let splitSizes;
if (!isOpen) {
splitSizes = INITIAL_SIZES;
} else {
splitSizes = [
100 - DEFAULT_SOUTH_PANE_HEIGHT_PERCENT,
DEFAULT_SOUTH_PANE_HEIGHT_PERCENT,
];
}
setSplitSizes(splitSizes);
}, []);
const renderChart = useCallback(
() => (
<div
css={css`
min-height: 0;
flex: 1;
overflow: auto;
`}
ref={chartPanelRef}
>
{chartPanelWidth && chartPanelHeight && (
<ChartContainer
width={Math.floor(chartPanelWidth)}
height={chartPanelHeight}
ownState={ownState}
annotationData={chart.annotationData}
chartAlert={chart.chartAlert}
chartStackTrace={chart.chartStackTrace}
chartId={chart.id}
chartStatus={chart.chartStatus}
triggerRender={triggerRender}
force={force}
datasource={datasource}
errorMessage={errorMessage}
formData={formData}
latestQueryFormData={chart.latestQueryFormData}
onQuery={onQuery}
queriesResponse={chart.queriesResponse}
chartIsStale={chartIsStale}
setControlValue={actions.setControlValue}
timeout={timeout}
triggerQuery={chart.triggerQuery}
vizType={vizType}
/>
)}
</div>
),
[
actions.setControlValue,
chart.annotationData,
chart.chartAlert,
chart.chartStackTrace,
chart.chartStatus,
chart.id,
chart.latestQueryFormData,
chart.queriesResponse,
chart.triggerQuery,
chartIsStale,
chartPanelHeight,
chartPanelRef,
chartPanelWidth,
datasource,
errorMessage,
force,
formData,
onQuery,
ownState,
timeout,
triggerRender,
vizType,
],
);
const panelBody = useMemo(
() => (
<div
className="panel-body"
css={css`
display: flex;
flex-direction: column;
`}
>
{vizTypeNeedsDataset && (
<Alert
message={t('Chart type requires a dataset')}
type="error"
css={theme => css`
margin: 0 0 ${theme.gridUnit * 4}px 0;
`}
description={
<>
{t(
'This chart type is not supported when using an unsaved query as a chart source. ',
)}
<span
role="button"
tabIndex={0}
onClick={() => setShowDatasetModal(true)}
css={{ textDecoration: 'underline' }}
>
{t('Create a dataset')}
</span>
{t(' to visualize your data.')}
</>
}
/>
)}
{showAlertBanner && (
<ExploreAlert
title={
errorMessage
? t('Required control values have been removed')
: t('Your chart is not up to date')
}
bodyText={
errorMessage ? (
getChartRequiredFieldsMissingMessage(false)
) : (
<span>
{t(
'You updated the values in the control panel, but the chart was not updated automatically. Run the query by clicking on the "Update chart" button or',
)}{' '}
<span role="button" tabIndex={0} onClick={onQuery}>
{t('click here')}
</span>
.
</span>
)
}
type="warning"
css={theme => css`
margin: 0 0 ${theme.gridUnit * 4}px 0;
`}
/>
)}
<ChartPills
queriesResponse={chart.queriesResponse}
chartStatus={chart.chartStatus}
chartUpdateStartTime={chart.chartUpdateStartTime}
chartUpdateEndTime={chart.chartUpdateEndTime}
refreshCachedQuery={refreshCachedQuery}
rowLimit={formData?.row_limit}
/>
{renderChart()}
</div>
),
[
showAlertBanner,
errorMessage,
onQuery,
chart.queriesResponse,
chart.chartStatus,
chart.chartUpdateStartTime,
chart.chartUpdateEndTime,
refreshCachedQuery,
formData?.row_limit,
renderChart,
],
);
const standaloneChartBody = useMemo(() => renderChart(), [renderChart]);
const [queryFormData, setQueryFormData] = useState(chart.latestQueryFormData);
useEffect(() => {
// only update when `latestQueryFormData` changes AND `triggerRender`
// is false. No update should be done when only `triggerRender` changes,
// as this can trigger a query downstream based on incomplete form data.
// (`latestQueryFormData` is only updated when a a valid request has been
// triggered).
if (!triggerRender) {
setQueryFormData(chart.latestQueryFormData);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [chart.latestQueryFormData]);
const elementStyle = useCallback(
(dimension, elementSize, gutterSize) => ({
[dimension]: `calc(${elementSize}% - ${gutterSize + gutterMargin}px)`,
}),
[gutterMargin],
);
if (standalone) {
// dom manipulation hack to get rid of the boostrap theme's body background
const standaloneClass = 'background-transparent';
const bodyClasses = document.body.className.split(' ');
if (!bodyClasses.includes(standaloneClass)) {
document.body.className += ` ${standaloneClass}`;
}
return standaloneChartBody;
}
return (
<Styles className="panel panel-default chart-container">
{vizType === 'filter_box' ? (
panelBody
) : (
<Split
sizes={splitSizes}
minSize={MIN_SIZES}
direction="vertical"
gutterSize={gutterHeight}
onDragEnd={onDragEnd}
elementStyle={elementStyle}
expandToMin
>
{panelBody}
<DataTablesPane
ownState={ownState}
queryFormData={queryFormData}
datasource={datasource}
queryForce={force}
onCollapseChange={onCollapseChange}
chartStatus={chart.chartStatus}
errorMessage={errorMessage}
actions={actions}
/>
</Split>
)}
{showDatasetModal && (
<SaveDatasetModal
visible={showDatasetModal}
onHide={() => setShowDatasetModal(false)}
buttonTextOnSave={t('Save')}
buttonTextOnOverwrite={t('Overwrite')}
datasource={getDatasourceAsSaveableDataset(datasource)}
openWindow={false}
formData={formData}
/>
)}
</Styles>
);
};
ExploreChartPanel.propTypes = propTypes;
export default ExploreChartPanel;
| superset-frontend/src/explore/components/ExploreChartPanel.jsx | 1 | https://github.com/apache/superset/commit/d28909d56c21c160a0140b87c4f268b1c4ea90f1 | [
0.9990730285644531,
0.19622650742530823,
0.00016372115351259708,
0.00017418386414647102,
0.3954710364341736
] |
{
"id": 1,
"code_window": [
" refreshRate: 300,\n",
" });\n",
" const [splitSizes, setSplitSizes] = useState(\n",
" getItem(LocalStorageKeys.chart_split_sizes, INITIAL_SIZES),\n",
" );\n",
"\n",
" const [showDatasetModal, setShowDatasetModal] = useState(false);\n",
"\n",
" const metaDataRegistry = getChartMetadataRegistry();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const [showSplite, setShowSplit] = useState(\n",
" getItem(LocalStorageKeys.is_datapanel_open, false),\n",
" );\n"
],
"file_path": "superset-frontend/src/explore/components/ExploreChartPanel.jsx",
"type": "add",
"edit_start_line_idx": 151
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Add access_request table to manage requests to access datastores.
Revision ID: 5e4a03ef0bf0
Revises: 41f6a59a61f2
Create Date: 2016-09-09 17:39:57.846309
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "5e4a03ef0bf0"
down_revision = "b347b202819b"
def upgrade():
op.create_table(
"access_request",
sa.Column("created_on", sa.DateTime(), nullable=True),
sa.Column("changed_on", sa.DateTime(), nullable=True),
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("datasource_type", sa.String(length=200), nullable=True),
sa.Column("datasource_id", sa.Integer(), nullable=True),
sa.Column("changed_by_fk", sa.Integer(), nullable=True),
sa.Column("created_by_fk", sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(["changed_by_fk"], ["ab_user.id"]),
sa.ForeignKeyConstraint(["created_by_fk"], ["ab_user.id"]),
sa.PrimaryKeyConstraint("id"),
)
def downgrade():
op.drop_table("access_request")
| superset/migrations/versions/2016-09-09_17-39_5e4a03ef0bf0_add_request_access_model.py | 0 | https://github.com/apache/superset/commit/d28909d56c21c160a0140b87c4f268b1c4ea90f1 | [
0.00017752274288795888,
0.00017477190704084933,
0.0001726489281281829,
0.00017382153600919992,
0.000001828253743951791
] |
{
"id": 1,
"code_window": [
" refreshRate: 300,\n",
" });\n",
" const [splitSizes, setSplitSizes] = useState(\n",
" getItem(LocalStorageKeys.chart_split_sizes, INITIAL_SIZES),\n",
" );\n",
"\n",
" const [showDatasetModal, setShowDatasetModal] = useState(false);\n",
"\n",
" const metaDataRegistry = getChartMetadataRegistry();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const [showSplite, setShowSplit] = useState(\n",
" getItem(LocalStorageKeys.is_datapanel_open, false),\n",
" );\n"
],
"file_path": "superset-frontend/src/explore/components/ExploreChartPanel.jsx",
"type": "add",
"edit_start_line_idx": 151
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import {
AnnotationType,
Behavior,
ChartMetadata,
ChartPlugin,
FeatureFlag,
isFeatureEnabled,
t,
} from '@superset-ui/core';
import {
EchartsTimeseriesChartProps,
EchartsTimeseriesFormData,
EchartsTimeseriesSeriesType,
} from '../../types';
import buildQuery from '../../buildQuery';
import controlPanel from './controlPanel';
import transformProps from '../../transformProps';
import thumbnail from './images/thumbnail.png';
import example1 from './images/Scatter1.png';
const scatterTransformProps = (chartProps: EchartsTimeseriesChartProps) =>
transformProps({
...chartProps,
formData: {
...chartProps.formData,
seriesType: EchartsTimeseriesSeriesType.Scatter,
},
});
export default class EchartsTimeseriesScatterChartPlugin extends ChartPlugin<
EchartsTimeseriesFormData,
EchartsTimeseriesChartProps
> {
constructor() {
super({
buildQuery,
controlPanel,
loadChart: () => import('../../EchartsTimeseries'),
metadata: new ChartMetadata({
behaviors: [Behavior.INTERACTIVE_CHART],
category: t('Evolution'),
credits: ['https://echarts.apache.org'],
description: isFeatureEnabled(FeatureFlag.GENERIC_CHART_AXES)
? t(
'Scatter Plot has the horizontal axis in linear units, and the points are connected in order. It shows a statistical relationship between two variables.',
)
: t(
'Time-series Scatter Plot has time on the horizontal axis in linear units, and the points are connected in order. It shows a statistical relationship between two variables.',
),
exampleGallery: [{ url: example1 }],
supportedAnnotationTypes: [
AnnotationType.Event,
AnnotationType.Formula,
AnnotationType.Interval,
AnnotationType.Timeseries,
],
name: isFeatureEnabled(FeatureFlag.GENERIC_CHART_AXES)
? t('Scatter Plot')
: t('Time-series Scatter Plot'),
tags: [
t('ECharts'),
t('Predictive'),
t('Advanced-Analytics'),
t('Aesthetic'),
t('Time'),
t('Transformable'),
t('Scatter'),
t('Popular'),
],
thumbnail,
}),
transformProps: scatterTransformProps,
});
}
}
| superset-frontend/plugins/plugin-chart-echarts/src/Timeseries/Regular/Scatter/index.ts | 0 | https://github.com/apache/superset/commit/d28909d56c21c160a0140b87c4f268b1c4ea90f1 | [
0.0001936105836648494,
0.00017354291048832238,
0.00016511189460288733,
0.000173494903719984,
0.000007637110684299842
] |
{
"id": 1,
"code_window": [
" refreshRate: 300,\n",
" });\n",
" const [splitSizes, setSplitSizes] = useState(\n",
" getItem(LocalStorageKeys.chart_split_sizes, INITIAL_SIZES),\n",
" );\n",
"\n",
" const [showDatasetModal, setShowDatasetModal] = useState(false);\n",
"\n",
" const metaDataRegistry = getChartMetadataRegistry();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const [showSplite, setShowSplit] = useState(\n",
" getItem(LocalStorageKeys.is_datapanel_open, false),\n",
" );\n"
],
"file_path": "superset-frontend/src/explore/components/ExploreChartPanel.jsx",
"type": "add",
"edit_start_line_idx": 151
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import PropTypes from 'prop-types';
import componentTypes from './componentTypes';
import backgroundStyleOptions from './backgroundStyleOptions';
import headerStyleOptions from './headerStyleOptions';
export const componentShape = PropTypes.shape({
id: PropTypes.string.isRequired,
type: PropTypes.oneOf(Object.values(componentTypes)).isRequired,
parents: PropTypes.arrayOf(PropTypes.string),
children: PropTypes.arrayOf(PropTypes.string),
meta: PropTypes.shape({
// Dimensions
width: PropTypes.number,
height: PropTypes.number,
// Header
headerSize: PropTypes.oneOf(headerStyleOptions.map(opt => opt.value)),
// Row
background: PropTypes.oneOf(backgroundStyleOptions.map(opt => opt.value)),
// Chart
chartId: PropTypes.number,
}),
});
export const chartPropShape = PropTypes.shape({
id: PropTypes.number.isRequired,
chartAlert: PropTypes.string,
chartStatus: PropTypes.string,
chartUpdateEndTime: PropTypes.number,
chartUpdateStartTime: PropTypes.number,
latestQueryFormData: PropTypes.object,
queryController: PropTypes.shape({ abort: PropTypes.func }),
queriesResponse: PropTypes.arrayOf(PropTypes.object),
triggerQuery: PropTypes.bool,
lastRendered: PropTypes.number,
});
export const slicePropShape = PropTypes.shape({
slice_id: PropTypes.number.isRequired,
slice_url: PropTypes.string.isRequired,
slice_name: PropTypes.string.isRequired,
datasource: PropTypes.string,
datasource_name: PropTypes.string,
datasource_link: PropTypes.string,
changed_on: PropTypes.number.isRequired,
modified: PropTypes.string.isRequired,
viz_type: PropTypes.string.isRequired,
description: PropTypes.string,
description_markeddown: PropTypes.string,
owners: PropTypes.arrayOf(PropTypes.string),
});
export const dashboardFilterPropShape = PropTypes.shape({
chartId: PropTypes.number.isRequired,
componentId: PropTypes.string.isRequired,
filterName: PropTypes.string.isRequired,
datasourceId: PropTypes.string.isRequired,
directPathToFilter: PropTypes.arrayOf(PropTypes.string).isRequired,
isDateFilter: PropTypes.bool.isRequired,
isInstantFilter: PropTypes.bool.isRequired,
columns: PropTypes.object,
labels: PropTypes.object,
scopes: PropTypes.object,
});
export const dashboardStatePropShape = PropTypes.shape({
sliceIds: PropTypes.arrayOf(PropTypes.number).isRequired,
expandedSlices: PropTypes.object,
editMode: PropTypes.bool,
isPublished: PropTypes.bool.isRequired,
colorNamespace: PropTypes.string,
colorScheme: PropTypes.string,
updatedColorScheme: PropTypes.bool,
hasUnsavedChanges: PropTypes.bool,
});
export const dashboardInfoPropShape = PropTypes.shape({
id: PropTypes.number.isRequired,
metadata: PropTypes.object,
slug: PropTypes.string,
dash_edit_perm: PropTypes.bool.isRequired,
dash_save_perm: PropTypes.bool.isRequired,
common: PropTypes.object,
userId: PropTypes.string.isRequired,
});
/* eslint-disable-next-line no-undef */
const lazyFunction = f => () => f().apply(this, arguments);
const leafType = PropTypes.shape({
value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
label: PropTypes.string.isRequired,
});
const parentShape = {
value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
label: PropTypes.string.isRequired,
children: PropTypes.arrayOf(
PropTypes.oneOfType([
PropTypes.shape(lazyFunction(() => parentShape)),
leafType,
]),
),
};
export const filterScopeSelectorTreeNodePropShape = PropTypes.oneOfType([
PropTypes.shape(parentShape),
leafType,
]);
| superset-frontend/src/dashboard/util/propShapes.jsx | 0 | https://github.com/apache/superset/commit/d28909d56c21c160a0140b87c4f268b1c4ea90f1 | [
0.0001788830995792523,
0.00017504293646197766,
0.0001674365921644494,
0.00017552300414536148,
0.0000030176704512996366
] |
{
"id": 2,
"code_window": [
" DEFAULT_SOUTH_PANE_HEIGHT_PERCENT,\n",
" ];\n",
" }\n",
" setSplitSizes(splitSizes);\n",
" }, []);\n",
"\n",
" const renderChart = useCallback(\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" setShowSplit(isOpen);\n"
],
"file_path": "superset-frontend/src/explore/components/ExploreChartPanel.jsx",
"type": "add",
"edit_start_line_idx": 227
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import PropTypes from 'prop-types';
import Split from 'react-split';
import {
css,
ensureIsArray,
styled,
SupersetClient,
t,
useTheme,
getChartMetadataRegistry,
DatasourceType,
} from '@superset-ui/core';
import { useResizeDetector } from 'react-resize-detector';
import { chartPropShape } from 'src/dashboard/util/propShapes';
import ChartContainer from 'src/components/Chart/ChartContainer';
import {
getItem,
setItem,
LocalStorageKeys,
} from 'src/utils/localStorageHelpers';
import Alert from 'src/components/Alert';
import { SaveDatasetModal } from 'src/SqlLab/components/SaveDatasetModal';
import { getDatasourceAsSaveableDataset } from 'src/utils/datasourceUtils';
import { DataTablesPane } from './DataTablesPane';
import { buildV1ChartDataPayload } from '../exploreUtils';
import { ChartPills } from './ChartPills';
import { ExploreAlert } from './ExploreAlert';
import { getChartRequiredFieldsMissingMessage } from '../../utils/getChartRequiredFieldsMissingMessage';
const propTypes = {
actions: PropTypes.object.isRequired,
onQuery: PropTypes.func,
can_overwrite: PropTypes.bool.isRequired,
can_download: PropTypes.bool.isRequired,
datasource: PropTypes.object,
dashboardId: PropTypes.number,
column_formats: PropTypes.object,
containerId: PropTypes.string.isRequired,
isStarred: PropTypes.bool.isRequired,
slice: PropTypes.object,
sliceName: PropTypes.string,
table_name: PropTypes.string,
vizType: PropTypes.string.isRequired,
form_data: PropTypes.object,
ownState: PropTypes.object,
standalone: PropTypes.bool,
force: PropTypes.bool,
timeout: PropTypes.number,
chartIsStale: PropTypes.bool,
chart: chartPropShape,
errorMessage: PropTypes.node,
triggerRender: PropTypes.bool,
};
const GUTTER_SIZE_FACTOR = 1.25;
const INITIAL_SIZES = [100, 0];
const MIN_SIZES = [300, 65];
const DEFAULT_SOUTH_PANE_HEIGHT_PERCENT = 40;
const Styles = styled.div`
display: flex;
flex-direction: column;
align-items: stretch;
align-content: stretch;
overflow: auto;
box-shadow: none;
height: 100%;
& > div {
height: 100%;
}
.gutter {
border-top: 1px solid ${({ theme }) => theme.colors.grayscale.light2};
border-bottom: 1px solid ${({ theme }) => theme.colors.grayscale.light2};
width: ${({ theme }) => theme.gridUnit * 9}px;
margin: ${({ theme }) => theme.gridUnit * GUTTER_SIZE_FACTOR}px auto;
}
.gutter.gutter-vertical {
cursor: row-resize;
}
.ant-collapse {
.ant-tabs {
height: 100%;
.ant-tabs-nav {
padding-left: ${({ theme }) => theme.gridUnit * 5}px;
margin: 0;
}
.ant-tabs-content-holder {
overflow: hidden;
.ant-tabs-content {
height: 100%;
}
}
}
}
`;
const ExploreChartPanel = ({
chart,
slice,
vizType,
ownState,
triggerRender,
force,
datasource,
errorMessage,
form_data: formData,
onQuery,
actions,
timeout,
standalone,
chartIsStale,
chartAlert,
}) => {
const theme = useTheme();
const gutterMargin = theme.gridUnit * GUTTER_SIZE_FACTOR;
const gutterHeight = theme.gridUnit * GUTTER_SIZE_FACTOR;
const {
width: chartPanelWidth,
height: chartPanelHeight,
ref: chartPanelRef,
} = useResizeDetector({
refreshMode: 'debounce',
refreshRate: 300,
});
const [splitSizes, setSplitSizes] = useState(
getItem(LocalStorageKeys.chart_split_sizes, INITIAL_SIZES),
);
const [showDatasetModal, setShowDatasetModal] = useState(false);
const metaDataRegistry = getChartMetadataRegistry();
const { useLegacyApi } = metaDataRegistry.get(vizType) ?? {};
const vizTypeNeedsDataset =
useLegacyApi && datasource.type !== DatasourceType.Table;
// added boolean column to below show boolean so that the errors aren't overlapping
const showAlertBanner =
!chartAlert &&
chartIsStale &&
!vizTypeNeedsDataset &&
chart.chartStatus !== 'failed' &&
ensureIsArray(chart.queriesResponse).length > 0;
const updateQueryContext = useCallback(
async function fetchChartData() {
if (slice && slice.query_context === null) {
const queryContext = buildV1ChartDataPayload({
formData: slice.form_data,
force,
resultFormat: 'json',
resultType: 'full',
setDataMask: null,
ownState: null,
});
await SupersetClient.put({
endpoint: `/api/v1/chart/${slice.slice_id}`,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query_context: JSON.stringify(queryContext),
query_context_generation: true,
}),
});
}
},
[slice],
);
useEffect(() => {
updateQueryContext();
}, [updateQueryContext]);
useEffect(() => {
setItem(LocalStorageKeys.chart_split_sizes, splitSizes);
}, [splitSizes]);
const onDragEnd = useCallback(sizes => {
setSplitSizes(sizes);
}, []);
const refreshCachedQuery = useCallback(() => {
actions.setForceQuery(true);
actions.postChartFormData(
formData,
true,
timeout,
chart.id,
undefined,
ownState,
);
actions.updateQueryFormData(formData, chart.id);
}, [actions, chart.id, formData, ownState, timeout]);
const onCollapseChange = useCallback(isOpen => {
let splitSizes;
if (!isOpen) {
splitSizes = INITIAL_SIZES;
} else {
splitSizes = [
100 - DEFAULT_SOUTH_PANE_HEIGHT_PERCENT,
DEFAULT_SOUTH_PANE_HEIGHT_PERCENT,
];
}
setSplitSizes(splitSizes);
}, []);
const renderChart = useCallback(
() => (
<div
css={css`
min-height: 0;
flex: 1;
overflow: auto;
`}
ref={chartPanelRef}
>
{chartPanelWidth && chartPanelHeight && (
<ChartContainer
width={Math.floor(chartPanelWidth)}
height={chartPanelHeight}
ownState={ownState}
annotationData={chart.annotationData}
chartAlert={chart.chartAlert}
chartStackTrace={chart.chartStackTrace}
chartId={chart.id}
chartStatus={chart.chartStatus}
triggerRender={triggerRender}
force={force}
datasource={datasource}
errorMessage={errorMessage}
formData={formData}
latestQueryFormData={chart.latestQueryFormData}
onQuery={onQuery}
queriesResponse={chart.queriesResponse}
chartIsStale={chartIsStale}
setControlValue={actions.setControlValue}
timeout={timeout}
triggerQuery={chart.triggerQuery}
vizType={vizType}
/>
)}
</div>
),
[
actions.setControlValue,
chart.annotationData,
chart.chartAlert,
chart.chartStackTrace,
chart.chartStatus,
chart.id,
chart.latestQueryFormData,
chart.queriesResponse,
chart.triggerQuery,
chartIsStale,
chartPanelHeight,
chartPanelRef,
chartPanelWidth,
datasource,
errorMessage,
force,
formData,
onQuery,
ownState,
timeout,
triggerRender,
vizType,
],
);
const panelBody = useMemo(
() => (
<div
className="panel-body"
css={css`
display: flex;
flex-direction: column;
`}
>
{vizTypeNeedsDataset && (
<Alert
message={t('Chart type requires a dataset')}
type="error"
css={theme => css`
margin: 0 0 ${theme.gridUnit * 4}px 0;
`}
description={
<>
{t(
'This chart type is not supported when using an unsaved query as a chart source. ',
)}
<span
role="button"
tabIndex={0}
onClick={() => setShowDatasetModal(true)}
css={{ textDecoration: 'underline' }}
>
{t('Create a dataset')}
</span>
{t(' to visualize your data.')}
</>
}
/>
)}
{showAlertBanner && (
<ExploreAlert
title={
errorMessage
? t('Required control values have been removed')
: t('Your chart is not up to date')
}
bodyText={
errorMessage ? (
getChartRequiredFieldsMissingMessage(false)
) : (
<span>
{t(
'You updated the values in the control panel, but the chart was not updated automatically. Run the query by clicking on the "Update chart" button or',
)}{' '}
<span role="button" tabIndex={0} onClick={onQuery}>
{t('click here')}
</span>
.
</span>
)
}
type="warning"
css={theme => css`
margin: 0 0 ${theme.gridUnit * 4}px 0;
`}
/>
)}
<ChartPills
queriesResponse={chart.queriesResponse}
chartStatus={chart.chartStatus}
chartUpdateStartTime={chart.chartUpdateStartTime}
chartUpdateEndTime={chart.chartUpdateEndTime}
refreshCachedQuery={refreshCachedQuery}
rowLimit={formData?.row_limit}
/>
{renderChart()}
</div>
),
[
showAlertBanner,
errorMessage,
onQuery,
chart.queriesResponse,
chart.chartStatus,
chart.chartUpdateStartTime,
chart.chartUpdateEndTime,
refreshCachedQuery,
formData?.row_limit,
renderChart,
],
);
const standaloneChartBody = useMemo(() => renderChart(), [renderChart]);
const [queryFormData, setQueryFormData] = useState(chart.latestQueryFormData);
useEffect(() => {
// only update when `latestQueryFormData` changes AND `triggerRender`
// is false. No update should be done when only `triggerRender` changes,
// as this can trigger a query downstream based on incomplete form data.
// (`latestQueryFormData` is only updated when a a valid request has been
// triggered).
if (!triggerRender) {
setQueryFormData(chart.latestQueryFormData);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [chart.latestQueryFormData]);
const elementStyle = useCallback(
(dimension, elementSize, gutterSize) => ({
[dimension]: `calc(${elementSize}% - ${gutterSize + gutterMargin}px)`,
}),
[gutterMargin],
);
if (standalone) {
// dom manipulation hack to get rid of the boostrap theme's body background
const standaloneClass = 'background-transparent';
const bodyClasses = document.body.className.split(' ');
if (!bodyClasses.includes(standaloneClass)) {
document.body.className += ` ${standaloneClass}`;
}
return standaloneChartBody;
}
return (
<Styles className="panel panel-default chart-container">
{vizType === 'filter_box' ? (
panelBody
) : (
<Split
sizes={splitSizes}
minSize={MIN_SIZES}
direction="vertical"
gutterSize={gutterHeight}
onDragEnd={onDragEnd}
elementStyle={elementStyle}
expandToMin
>
{panelBody}
<DataTablesPane
ownState={ownState}
queryFormData={queryFormData}
datasource={datasource}
queryForce={force}
onCollapseChange={onCollapseChange}
chartStatus={chart.chartStatus}
errorMessage={errorMessage}
actions={actions}
/>
</Split>
)}
{showDatasetModal && (
<SaveDatasetModal
visible={showDatasetModal}
onHide={() => setShowDatasetModal(false)}
buttonTextOnSave={t('Save')}
buttonTextOnOverwrite={t('Overwrite')}
datasource={getDatasourceAsSaveableDataset(datasource)}
openWindow={false}
formData={formData}
/>
)}
</Styles>
);
};
ExploreChartPanel.propTypes = propTypes;
export default ExploreChartPanel;
| superset-frontend/src/explore/components/ExploreChartPanel.jsx | 1 | https://github.com/apache/superset/commit/d28909d56c21c160a0140b87c4f268b1c4ea90f1 | [
0.9983171224594116,
0.0664203092455864,
0.00016344334289897233,
0.00017289406969211996,
0.24597860872745514
] |
{
"id": 2,
"code_window": [
" DEFAULT_SOUTH_PANE_HEIGHT_PERCENT,\n",
" ];\n",
" }\n",
" setSplitSizes(splitSizes);\n",
" }, []);\n",
"\n",
" const renderChart = useCallback(\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" setShowSplit(isOpen);\n"
],
"file_path": "superset-frontend/src/explore/components/ExploreChartPanel.jsx",
"type": "add",
"edit_start_line_idx": 227
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import AdhocFilter, {
EXPRESSION_TYPES,
CLAUSES,
} from 'src/explore/components/controls/FilterControl/AdhocFilter';
import { Operators } from 'src/explore/constants';
describe('AdhocFilter', () => {
it('sets filterOptionName in constructor', () => {
const adhocFilter = new AdhocFilter({
expressionType: EXPRESSION_TYPES.SIMPLE,
subject: 'value',
operator: '>',
comparator: '10',
clause: CLAUSES.WHERE,
});
expect(adhocFilter.filterOptionName.length).toBeGreaterThan(10);
expect(adhocFilter).toEqual({
expressionType: EXPRESSION_TYPES.SIMPLE,
subject: 'value',
operator: '>',
comparator: '10',
clause: CLAUSES.WHERE,
filterOptionName: adhocFilter.filterOptionName,
sqlExpression: null,
isExtra: false,
isNew: false,
});
});
it('can create altered duplicates', () => {
const adhocFilter1 = new AdhocFilter({
isNew: true,
expressionType: EXPRESSION_TYPES.SIMPLE,
subject: 'value',
operator: '>',
comparator: '10',
clause: CLAUSES.WHERE,
});
const adhocFilter2 = adhocFilter1.duplicateWith({ operator: '<' });
expect(adhocFilter1.subject).toBe(adhocFilter2.subject);
expect(adhocFilter1.comparator).toBe(adhocFilter2.comparator);
expect(adhocFilter1.clause).toBe(adhocFilter2.clause);
expect(adhocFilter1.expressionType).toBe(adhocFilter2.expressionType);
expect(adhocFilter1.operator).toBe('>');
expect(adhocFilter2.operator).toBe('<');
// duplicated clone should not be new
expect(adhocFilter1.isNew).toBe(true);
expect(adhocFilter2.isNew).toStrictEqual(false);
});
it('can verify equality', () => {
const adhocFilter1 = new AdhocFilter({
expressionType: EXPRESSION_TYPES.SIMPLE,
subject: 'value',
operator: '>',
comparator: '10',
clause: CLAUSES.WHERE,
});
const adhocFilter2 = adhocFilter1.duplicateWith({});
// eslint-disable-next-line no-unused-expressions
expect(adhocFilter1.equals(adhocFilter2)).toBe(true);
// eslint-disable-next-line no-unused-expressions
expect(adhocFilter1 === adhocFilter2).toBe(false);
});
it('can verify inequality', () => {
const adhocFilter1 = new AdhocFilter({
expressionType: EXPRESSION_TYPES.SIMPLE,
subject: 'value',
operator: '>',
comparator: '10',
clause: CLAUSES.WHERE,
});
const adhocFilter2 = adhocFilter1.duplicateWith({ operator: '<' });
// eslint-disable-next-line no-unused-expressions
expect(adhocFilter1.equals(adhocFilter2)).toBe(false);
const adhocFilter3 = new AdhocFilter({
expressionType: EXPRESSION_TYPES.SQL,
sqlExpression: 'value > 10',
clause: CLAUSES.WHERE,
});
const adhocFilter4 = adhocFilter3.duplicateWith({
sqlExpression: 'value = 5',
});
// eslint-disable-next-line no-unused-expressions
expect(adhocFilter3.equals(adhocFilter4)).toBe(false);
});
it('can determine if it is valid', () => {
const adhocFilter1 = new AdhocFilter({
expressionType: EXPRESSION_TYPES.SIMPLE,
subject: 'value',
operator: '>',
comparator: '10',
clause: CLAUSES.WHERE,
});
// eslint-disable-next-line no-unused-expressions
expect(adhocFilter1.isValid()).toBe(true);
const adhocFilter2 = new AdhocFilter({
expressionType: EXPRESSION_TYPES.SIMPLE,
subject: 'value',
operator: '>',
comparator: null,
clause: CLAUSES.WHERE,
});
// eslint-disable-next-line no-unused-expressions
expect(adhocFilter2.isValid()).toBe(false);
const adhocFilter3 = new AdhocFilter({
expressionType: EXPRESSION_TYPES.SQL,
sqlExpression: 'some expression',
clause: null,
});
// eslint-disable-next-line no-unused-expressions
expect(adhocFilter3.isValid()).toBe(false);
const adhocFilter4 = new AdhocFilter({
expressionType: EXPRESSION_TYPES.SIMPLE,
subject: 'value',
operator: 'IN',
comparator: [],
clause: CLAUSES.WHERE,
});
// eslint-disable-next-line no-unused-expressions
expect(adhocFilter4.isValid()).toBe(false);
const adhocFilter5 = new AdhocFilter({
expressionType: EXPRESSION_TYPES.SIMPLE,
subject: 'value',
operator: 'IN',
comparator: ['val1'],
clause: CLAUSES.WHERE,
});
// eslint-disable-next-line no-unused-expressions
expect(adhocFilter5.isValid()).toBe(true);
const adhocFilter6 = new AdhocFilter({
expressionType: EXPRESSION_TYPES.SIMPLE,
subject: 'value',
operator: '==',
comparator: 1,
clause: CLAUSES.WHERE,
});
// eslint-disable-next-line no-unused-expressions
expect(adhocFilter6.isValid()).toBe(true);
const adhocFilter7 = new AdhocFilter({
expressionType: EXPRESSION_TYPES.SIMPLE,
subject: 'value',
operator: '==',
comparator: 0,
clause: CLAUSES.WHERE,
});
// eslint-disable-next-line no-unused-expressions
expect(adhocFilter7.isValid()).toBe(true);
const adhocFilter8 = new AdhocFilter({
expressionType: EXPRESSION_TYPES.SIMPLE,
subject: 'value',
operator: '==',
comparator: null,
clause: CLAUSES.WHERE,
});
// eslint-disable-next-line no-unused-expressions
expect(adhocFilter8.isValid()).toBe(false);
const adhocFilter9 = new AdhocFilter({
expressionType: EXPRESSION_TYPES.SIMPLE,
subject: 'value',
operator: 'IS NULL',
clause: CLAUSES.WHERE,
});
expect(adhocFilter9.isValid()).toBe(true);
const adhocFilter10 = new AdhocFilter({
expressionType: EXPRESSION_TYPES.SIMPLE,
subject: 'value',
operator: 'IS NOT NULL',
clause: CLAUSES.WHERE,
});
// eslint-disable-next-line no-unused-expressions
expect(adhocFilter10.isValid()).toBe(true);
});
it('can translate from simple expressions to sql expressions', () => {
const adhocFilter1 = new AdhocFilter({
expressionType: EXPRESSION_TYPES.SIMPLE,
subject: 'value',
operator: '==',
comparator: '10',
clause: CLAUSES.WHERE,
});
expect(adhocFilter1.translateToSql()).toBe('value = 10');
const adhocFilter2 = new AdhocFilter({
expressionType: EXPRESSION_TYPES.SIMPLE,
subject: 'SUM(value)',
operator: '!=',
comparator: '5',
clause: CLAUSES.HAVING,
});
expect(adhocFilter2.translateToSql()).toBe('SUM(value) <> 5');
});
it('sets comparator to null when operator is IS_NULL', () => {
const adhocFilter2 = new AdhocFilter({
expressionType: EXPRESSION_TYPES.SIMPLE,
subject: 'SUM(value)',
operator: 'IS NULL',
operatorId: Operators.IS_NULL,
comparator: '5',
clause: CLAUSES.HAVING,
});
expect(adhocFilter2.comparator).toBe(null);
});
it('sets comparator to null when operator is IS_NOT_NULL', () => {
const adhocFilter2 = new AdhocFilter({
expressionType: EXPRESSION_TYPES.SIMPLE,
subject: 'SUM(value)',
operator: 'IS NOT NULL',
operatorId: Operators.IS_NOT_NULL,
comparator: '5',
clause: CLAUSES.HAVING,
});
expect(adhocFilter2.comparator).toBe(null);
});
});
| superset-frontend/src/explore/components/controls/FilterControl/AdhocFilter/AdhocFilter.test.js | 0 | https://github.com/apache/superset/commit/d28909d56c21c160a0140b87c4f268b1c4ea90f1 | [
0.00017935106006916612,
0.0001742599852150306,
0.00016609879094175994,
0.0001749037764966488,
0.000002387971562711755
] |
{
"id": 2,
"code_window": [
" DEFAULT_SOUTH_PANE_HEIGHT_PERCENT,\n",
" ];\n",
" }\n",
" setSplitSizes(splitSizes);\n",
" }, []);\n",
"\n",
" const renderChart = useCallback(\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" setShowSplit(isOpen);\n"
],
"file_path": "superset-frontend/src/explore/components/ExploreChartPanel.jsx",
"type": "add",
"edit_start_line_idx": 227
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import { render, screen, waitFor } from 'spec/helpers/testing-library';
import userEvent from '@testing-library/user-event';
import CertifiedBadge, {
CertifiedBadgeProps,
} from 'src/components/CertifiedBadge';
const asyncRender = (props?: CertifiedBadgeProps) =>
waitFor(() => render(<CertifiedBadge {...props} />));
test('renders with default props', async () => {
await asyncRender();
expect(screen.getByRole('img')).toBeInTheDocument();
});
test('renders a tooltip when hovered', async () => {
await asyncRender();
userEvent.hover(screen.getByRole('img'));
expect(await screen.findByRole('tooltip')).toBeInTheDocument();
});
test('renders with certified by', async () => {
const certifiedBy = 'Trusted Authority';
await asyncRender({ certifiedBy });
userEvent.hover(screen.getByRole('img'));
expect(await screen.findByRole('tooltip')).toHaveTextContent(certifiedBy);
});
test('renders with details', async () => {
const details = 'All requirements have been met.';
await asyncRender({ details });
userEvent.hover(screen.getByRole('img'));
expect(await screen.findByRole('tooltip')).toHaveTextContent(details);
});
| superset-frontend/src/components/CertifiedBadge/CertifiedBadge.test.tsx | 0 | https://github.com/apache/superset/commit/d28909d56c21c160a0140b87c4f268b1c4ea90f1 | [
0.00017490735626779497,
0.00017349561676383018,
0.00017118996765930206,
0.00017383618978783488,
0.000001393569277752249
] |
{
"id": 2,
"code_window": [
" DEFAULT_SOUTH_PANE_HEIGHT_PERCENT,\n",
" ];\n",
" }\n",
" setSplitSizes(splitSizes);\n",
" }, []);\n",
"\n",
" const renderChart = useCallback(\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" setShowSplit(isOpen);\n"
],
"file_path": "superset-frontend/src/explore/components/ExploreChartPanel.jsx",
"type": "add",
"edit_start_line_idx": 227
} | # -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from superset.utils.urls import modify_url_query
EXPLORE_CHART_LINK = "http://localhost:9000/explore/?form_data=%7B%22slice_id%22%3A+76%7D&standalone=true&force=false"
EXPLORE_DASHBOARD_LINK = "http://localhost:9000/superset/dashboard/3/?standalone=3"
def test_convert_chart_link() -> None:
test_url = modify_url_query(EXPLORE_CHART_LINK, standalone="0")
assert (
test_url
== "http://localhost:9000/explore/?form_data=%7B%22slice_id%22%3A%2076%7D&standalone=0&force=false"
)
def test_convert_dashboard_link() -> None:
test_url = modify_url_query(EXPLORE_DASHBOARD_LINK, standalone="0")
assert test_url == "http://localhost:9000/superset/dashboard/3/?standalone=0"
| tests/unit_tests/utils/urls_tests.py | 0 | https://github.com/apache/superset/commit/d28909d56c21c160a0140b87c4f268b1c4ea90f1 | [
0.0001764778862707317,
0.00017210902296938002,
0.0001658522232901305,
0.00017305299115832895,
0.0000041101516217167955
] |
{
"id": 3,
"code_window": [
" return standaloneChartBody;\n",
" }\n",
"\n",
" return (\n",
" <Styles className=\"panel panel-default chart-container\">\n",
" {vizType === 'filter_box' ? (\n",
" panelBody\n",
" ) : (\n",
" <Split\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Styles\n",
" className=\"panel panel-default chart-container\"\n",
" showSplite={showSplite}\n",
" >\n"
],
"file_path": "superset-frontend/src/explore/components/ExploreChartPanel.jsx",
"type": "replace",
"edit_start_line_idx": 413
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import PropTypes from 'prop-types';
import Split from 'react-split';
import {
css,
ensureIsArray,
styled,
SupersetClient,
t,
useTheme,
getChartMetadataRegistry,
DatasourceType,
} from '@superset-ui/core';
import { useResizeDetector } from 'react-resize-detector';
import { chartPropShape } from 'src/dashboard/util/propShapes';
import ChartContainer from 'src/components/Chart/ChartContainer';
import {
getItem,
setItem,
LocalStorageKeys,
} from 'src/utils/localStorageHelpers';
import Alert from 'src/components/Alert';
import { SaveDatasetModal } from 'src/SqlLab/components/SaveDatasetModal';
import { getDatasourceAsSaveableDataset } from 'src/utils/datasourceUtils';
import { DataTablesPane } from './DataTablesPane';
import { buildV1ChartDataPayload } from '../exploreUtils';
import { ChartPills } from './ChartPills';
import { ExploreAlert } from './ExploreAlert';
import { getChartRequiredFieldsMissingMessage } from '../../utils/getChartRequiredFieldsMissingMessage';
const propTypes = {
actions: PropTypes.object.isRequired,
onQuery: PropTypes.func,
can_overwrite: PropTypes.bool.isRequired,
can_download: PropTypes.bool.isRequired,
datasource: PropTypes.object,
dashboardId: PropTypes.number,
column_formats: PropTypes.object,
containerId: PropTypes.string.isRequired,
isStarred: PropTypes.bool.isRequired,
slice: PropTypes.object,
sliceName: PropTypes.string,
table_name: PropTypes.string,
vizType: PropTypes.string.isRequired,
form_data: PropTypes.object,
ownState: PropTypes.object,
standalone: PropTypes.bool,
force: PropTypes.bool,
timeout: PropTypes.number,
chartIsStale: PropTypes.bool,
chart: chartPropShape,
errorMessage: PropTypes.node,
triggerRender: PropTypes.bool,
};
const GUTTER_SIZE_FACTOR = 1.25;
const INITIAL_SIZES = [100, 0];
const MIN_SIZES = [300, 65];
const DEFAULT_SOUTH_PANE_HEIGHT_PERCENT = 40;
const Styles = styled.div`
display: flex;
flex-direction: column;
align-items: stretch;
align-content: stretch;
overflow: auto;
box-shadow: none;
height: 100%;
& > div {
height: 100%;
}
.gutter {
border-top: 1px solid ${({ theme }) => theme.colors.grayscale.light2};
border-bottom: 1px solid ${({ theme }) => theme.colors.grayscale.light2};
width: ${({ theme }) => theme.gridUnit * 9}px;
margin: ${({ theme }) => theme.gridUnit * GUTTER_SIZE_FACTOR}px auto;
}
.gutter.gutter-vertical {
cursor: row-resize;
}
.ant-collapse {
.ant-tabs {
height: 100%;
.ant-tabs-nav {
padding-left: ${({ theme }) => theme.gridUnit * 5}px;
margin: 0;
}
.ant-tabs-content-holder {
overflow: hidden;
.ant-tabs-content {
height: 100%;
}
}
}
}
`;
const ExploreChartPanel = ({
chart,
slice,
vizType,
ownState,
triggerRender,
force,
datasource,
errorMessage,
form_data: formData,
onQuery,
actions,
timeout,
standalone,
chartIsStale,
chartAlert,
}) => {
const theme = useTheme();
const gutterMargin = theme.gridUnit * GUTTER_SIZE_FACTOR;
const gutterHeight = theme.gridUnit * GUTTER_SIZE_FACTOR;
const {
width: chartPanelWidth,
height: chartPanelHeight,
ref: chartPanelRef,
} = useResizeDetector({
refreshMode: 'debounce',
refreshRate: 300,
});
const [splitSizes, setSplitSizes] = useState(
getItem(LocalStorageKeys.chart_split_sizes, INITIAL_SIZES),
);
const [showDatasetModal, setShowDatasetModal] = useState(false);
const metaDataRegistry = getChartMetadataRegistry();
const { useLegacyApi } = metaDataRegistry.get(vizType) ?? {};
const vizTypeNeedsDataset =
useLegacyApi && datasource.type !== DatasourceType.Table;
// added boolean column to below show boolean so that the errors aren't overlapping
const showAlertBanner =
!chartAlert &&
chartIsStale &&
!vizTypeNeedsDataset &&
chart.chartStatus !== 'failed' &&
ensureIsArray(chart.queriesResponse).length > 0;
const updateQueryContext = useCallback(
async function fetchChartData() {
if (slice && slice.query_context === null) {
const queryContext = buildV1ChartDataPayload({
formData: slice.form_data,
force,
resultFormat: 'json',
resultType: 'full',
setDataMask: null,
ownState: null,
});
await SupersetClient.put({
endpoint: `/api/v1/chart/${slice.slice_id}`,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query_context: JSON.stringify(queryContext),
query_context_generation: true,
}),
});
}
},
[slice],
);
useEffect(() => {
updateQueryContext();
}, [updateQueryContext]);
useEffect(() => {
setItem(LocalStorageKeys.chart_split_sizes, splitSizes);
}, [splitSizes]);
const onDragEnd = useCallback(sizes => {
setSplitSizes(sizes);
}, []);
const refreshCachedQuery = useCallback(() => {
actions.setForceQuery(true);
actions.postChartFormData(
formData,
true,
timeout,
chart.id,
undefined,
ownState,
);
actions.updateQueryFormData(formData, chart.id);
}, [actions, chart.id, formData, ownState, timeout]);
const onCollapseChange = useCallback(isOpen => {
let splitSizes;
if (!isOpen) {
splitSizes = INITIAL_SIZES;
} else {
splitSizes = [
100 - DEFAULT_SOUTH_PANE_HEIGHT_PERCENT,
DEFAULT_SOUTH_PANE_HEIGHT_PERCENT,
];
}
setSplitSizes(splitSizes);
}, []);
const renderChart = useCallback(
() => (
<div
css={css`
min-height: 0;
flex: 1;
overflow: auto;
`}
ref={chartPanelRef}
>
{chartPanelWidth && chartPanelHeight && (
<ChartContainer
width={Math.floor(chartPanelWidth)}
height={chartPanelHeight}
ownState={ownState}
annotationData={chart.annotationData}
chartAlert={chart.chartAlert}
chartStackTrace={chart.chartStackTrace}
chartId={chart.id}
chartStatus={chart.chartStatus}
triggerRender={triggerRender}
force={force}
datasource={datasource}
errorMessage={errorMessage}
formData={formData}
latestQueryFormData={chart.latestQueryFormData}
onQuery={onQuery}
queriesResponse={chart.queriesResponse}
chartIsStale={chartIsStale}
setControlValue={actions.setControlValue}
timeout={timeout}
triggerQuery={chart.triggerQuery}
vizType={vizType}
/>
)}
</div>
),
[
actions.setControlValue,
chart.annotationData,
chart.chartAlert,
chart.chartStackTrace,
chart.chartStatus,
chart.id,
chart.latestQueryFormData,
chart.queriesResponse,
chart.triggerQuery,
chartIsStale,
chartPanelHeight,
chartPanelRef,
chartPanelWidth,
datasource,
errorMessage,
force,
formData,
onQuery,
ownState,
timeout,
triggerRender,
vizType,
],
);
const panelBody = useMemo(
() => (
<div
className="panel-body"
css={css`
display: flex;
flex-direction: column;
`}
>
{vizTypeNeedsDataset && (
<Alert
message={t('Chart type requires a dataset')}
type="error"
css={theme => css`
margin: 0 0 ${theme.gridUnit * 4}px 0;
`}
description={
<>
{t(
'This chart type is not supported when using an unsaved query as a chart source. ',
)}
<span
role="button"
tabIndex={0}
onClick={() => setShowDatasetModal(true)}
css={{ textDecoration: 'underline' }}
>
{t('Create a dataset')}
</span>
{t(' to visualize your data.')}
</>
}
/>
)}
{showAlertBanner && (
<ExploreAlert
title={
errorMessage
? t('Required control values have been removed')
: t('Your chart is not up to date')
}
bodyText={
errorMessage ? (
getChartRequiredFieldsMissingMessage(false)
) : (
<span>
{t(
'You updated the values in the control panel, but the chart was not updated automatically. Run the query by clicking on the "Update chart" button or',
)}{' '}
<span role="button" tabIndex={0} onClick={onQuery}>
{t('click here')}
</span>
.
</span>
)
}
type="warning"
css={theme => css`
margin: 0 0 ${theme.gridUnit * 4}px 0;
`}
/>
)}
<ChartPills
queriesResponse={chart.queriesResponse}
chartStatus={chart.chartStatus}
chartUpdateStartTime={chart.chartUpdateStartTime}
chartUpdateEndTime={chart.chartUpdateEndTime}
refreshCachedQuery={refreshCachedQuery}
rowLimit={formData?.row_limit}
/>
{renderChart()}
</div>
),
[
showAlertBanner,
errorMessage,
onQuery,
chart.queriesResponse,
chart.chartStatus,
chart.chartUpdateStartTime,
chart.chartUpdateEndTime,
refreshCachedQuery,
formData?.row_limit,
renderChart,
],
);
const standaloneChartBody = useMemo(() => renderChart(), [renderChart]);
const [queryFormData, setQueryFormData] = useState(chart.latestQueryFormData);
useEffect(() => {
// only update when `latestQueryFormData` changes AND `triggerRender`
// is false. No update should be done when only `triggerRender` changes,
// as this can trigger a query downstream based on incomplete form data.
// (`latestQueryFormData` is only updated when a a valid request has been
// triggered).
if (!triggerRender) {
setQueryFormData(chart.latestQueryFormData);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [chart.latestQueryFormData]);
const elementStyle = useCallback(
(dimension, elementSize, gutterSize) => ({
[dimension]: `calc(${elementSize}% - ${gutterSize + gutterMargin}px)`,
}),
[gutterMargin],
);
if (standalone) {
// dom manipulation hack to get rid of the boostrap theme's body background
const standaloneClass = 'background-transparent';
const bodyClasses = document.body.className.split(' ');
if (!bodyClasses.includes(standaloneClass)) {
document.body.className += ` ${standaloneClass}`;
}
return standaloneChartBody;
}
return (
<Styles className="panel panel-default chart-container">
{vizType === 'filter_box' ? (
panelBody
) : (
<Split
sizes={splitSizes}
minSize={MIN_SIZES}
direction="vertical"
gutterSize={gutterHeight}
onDragEnd={onDragEnd}
elementStyle={elementStyle}
expandToMin
>
{panelBody}
<DataTablesPane
ownState={ownState}
queryFormData={queryFormData}
datasource={datasource}
queryForce={force}
onCollapseChange={onCollapseChange}
chartStatus={chart.chartStatus}
errorMessage={errorMessage}
actions={actions}
/>
</Split>
)}
{showDatasetModal && (
<SaveDatasetModal
visible={showDatasetModal}
onHide={() => setShowDatasetModal(false)}
buttonTextOnSave={t('Save')}
buttonTextOnOverwrite={t('Overwrite')}
datasource={getDatasourceAsSaveableDataset(datasource)}
openWindow={false}
formData={formData}
/>
)}
</Styles>
);
};
ExploreChartPanel.propTypes = propTypes;
export default ExploreChartPanel;
| superset-frontend/src/explore/components/ExploreChartPanel.jsx | 1 | https://github.com/apache/superset/commit/d28909d56c21c160a0140b87c4f268b1c4ea90f1 | [
0.9206966161727905,
0.02300029993057251,
0.00016123955720104277,
0.00017556798411533237,
0.1348683089017868
] |
{
"id": 3,
"code_window": [
" return standaloneChartBody;\n",
" }\n",
"\n",
" return (\n",
" <Styles className=\"panel panel-default chart-container\">\n",
" {vizType === 'filter_box' ? (\n",
" panelBody\n",
" ) : (\n",
" <Split\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Styles\n",
" className=\"panel panel-default chart-container\"\n",
" showSplite={showSplite}\n",
" >\n"
],
"file_path": "superset-frontend/src/explore/components/ExploreChartPanel.jsx",
"type": "replace",
"edit_start_line_idx": 413
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { FeatureFlagMap, FeatureFlag } from '@superset-ui/core';
export { FeatureFlag } from '@superset-ui/core';
export type { FeatureFlagMap } from '@superset-ui/core';
export function initFeatureFlags(featureFlags: FeatureFlagMap) {
if (!window.featureFlags) {
window.featureFlags = featureFlags || {};
}
}
export function isFeatureEnabled(feature: FeatureFlag) {
try {
return !!window.featureFlags[feature];
} catch (error) {
// eslint-disable-next-line no-console
console.error(`Failed to query feature flag ${feature} (see error below)`);
// eslint-disable-next-line no-console
console.error(error);
return false;
}
}
| superset-frontend/src/featureFlags.ts | 0 | https://github.com/apache/superset/commit/d28909d56c21c160a0140b87c4f268b1c4ea90f1 | [
0.00017803433001972735,
0.00017618264246266335,
0.0001748295035213232,
0.00017581027350388467,
0.0000011223579576835618
] |
{
"id": 3,
"code_window": [
" return standaloneChartBody;\n",
" }\n",
"\n",
" return (\n",
" <Styles className=\"panel panel-default chart-container\">\n",
" {vizType === 'filter_box' ? (\n",
" panelBody\n",
" ) : (\n",
" <Split\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Styles\n",
" className=\"panel panel-default chart-container\"\n",
" showSplite={showSplite}\n",
" >\n"
],
"file_path": "superset-frontend/src/explore/components/ExploreChartPanel.jsx",
"type": "replace",
"edit_start_line_idx": 413
} | <!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M15 7H9V7.5C9 7.77614 8.77614 8 8.5 8C8.22386 8 8 7.77614 8 7.5V7H6.5C5.67157 7 5 7.67157 5 8.5V11H19V8.5C19 7.67157 18.3284 7 17.5 7H16V7.5C16 7.77614 15.7761 8 15.5 8C15.2239 8 15 7.77614 15 7.5V7ZM16 6H17.5C18.8807 6 20 7.11929 20 8.5V16.5074C20 17.8881 18.8807 19.0074 17.5 19.0074H6.5C5.11929 19.0074 4 17.8881 4 16.5074V8.5C4 7.11929 5.11929 6 6.5 6H8V5.5C8 5.22386 8.22386 5 8.5 5C8.77614 5 9 5.22386 9 5.5V6H15V5.5C15 5.22386 15.2239 5 15.5 5C15.7761 5 16 5.22386 16 5.5V6ZM5 12V16.5074C5 17.3358 5.67157 18.0074 6.5 18.0074H17.5C18.3284 18.0074 19 17.3358 19 16.5074V12H5Z" fill="currentColor"/>
</svg>
| superset-frontend/src/assets/images/icons/field_date.svg | 0 | https://github.com/apache/superset/commit/d28909d56c21c160a0140b87c4f268b1c4ea90f1 | [
0.0002284310758113861,
0.00019553668971639127,
0.00017754474538378417,
0.00018063426250591874,
0.000023294012862606905
] |
{
"id": 3,
"code_window": [
" return standaloneChartBody;\n",
" }\n",
"\n",
" return (\n",
" <Styles className=\"panel panel-default chart-container\">\n",
" {vizType === 'filter_box' ? (\n",
" panelBody\n",
" ) : (\n",
" <Split\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Styles\n",
" className=\"panel panel-default chart-container\"\n",
" showSplite={showSplite}\n",
" >\n"
],
"file_path": "superset-frontend/src/explore/components/ExploreChartPanel.jsx",
"type": "replace",
"edit_start_line_idx": 413
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import logging
import re
from datetime import datetime
from typing import Any, Dict, List, Optional, Pattern, Tuple
from flask_babel import gettext as __
from superset.db_engine_specs.base import BaseEngineSpec, LimitMethod
from superset.errors import SupersetErrorType
from superset.utils import core as utils
logger = logging.getLogger(__name__)
# Regular expressions to catch custom errors
CONNECTION_ACCESS_DENIED_REGEX = re.compile("Adaptive Server connection failed")
CONNECTION_INVALID_HOSTNAME_REGEX = re.compile(
r"Adaptive Server is unavailable or does not exist \((?P<hostname>.*?)\)"
"(?!.*Net-Lib error).*$"
)
CONNECTION_PORT_CLOSED_REGEX = re.compile(
r"Net-Lib error during Connection refused \(61\)"
)
CONNECTION_HOST_DOWN_REGEX = re.compile(
r"Net-Lib error during Operation timed out \(60\)"
)
class MssqlEngineSpec(BaseEngineSpec):
engine = "mssql"
engine_name = "Microsoft SQL Server"
limit_method = LimitMethod.WRAP_SQL
max_column_name_length = 128
allows_cte_in_subquery = False
allow_limit_clause = False
_time_grain_expressions = {
None: "{col}",
"PT1S": "DATEADD(SECOND, DATEDIFF(SECOND, '2000-01-01', {col}), '2000-01-01')",
"PT1M": "DATEADD(MINUTE, DATEDIFF(MINUTE, 0, {col}), 0)",
"PT5M": "DATEADD(MINUTE, DATEDIFF(MINUTE, 0, {col}) / 5 * 5, 0)",
"PT10M": "DATEADD(MINUTE, DATEDIFF(MINUTE, 0, {col}) / 10 * 10, 0)",
"PT15M": "DATEADD(MINUTE, DATEDIFF(MINUTE, 0, {col}) / 15 * 15, 0)",
"PT30M": "DATEADD(MINUTE, DATEDIFF(MINUTE, 0, {col}) / 30 * 30, 0)",
"PT1H": "DATEADD(HOUR, DATEDIFF(HOUR, 0, {col}), 0)",
"P1D": "DATEADD(DAY, DATEDIFF(DAY, 0, {col}), 0)",
"P1W": "DATEADD(DAY, 1 - DATEPART(WEEKDAY, {col}),"
" DATEADD(DAY, DATEDIFF(DAY, 0, {col}), 0))",
"P1M": "DATEADD(MONTH, DATEDIFF(MONTH, 0, {col}), 0)",
"P3M": "DATEADD(QUARTER, DATEDIFF(QUARTER, 0, {col}), 0)",
"P1Y": "DATEADD(YEAR, DATEDIFF(YEAR, 0, {col}), 0)",
"1969-12-28T00:00:00Z/P1W": "DATEADD(DAY, -1,"
" DATEADD(WEEK, DATEDIFF(WEEK, 0, {col}), 0))",
"1969-12-29T00:00:00Z/P1W": "DATEADD(WEEK,"
" DATEDIFF(WEEK, 0, DATEADD(DAY, -1, {col})), 0)",
}
custom_errors: Dict[Pattern[str], Tuple[str, SupersetErrorType, Dict[str, Any]]] = {
CONNECTION_ACCESS_DENIED_REGEX: (
__(
'Either the username "%(username)s", password, '
'or database name "%(database)s" is incorrect.'
),
SupersetErrorType.CONNECTION_ACCESS_DENIED_ERROR,
{},
),
CONNECTION_INVALID_HOSTNAME_REGEX: (
__('The hostname "%(hostname)s" cannot be resolved.'),
SupersetErrorType.CONNECTION_INVALID_HOSTNAME_ERROR,
{},
),
CONNECTION_PORT_CLOSED_REGEX: (
__('Port %(port)s on hostname "%(hostname)s" refused the connection.'),
SupersetErrorType.CONNECTION_PORT_CLOSED_ERROR,
{},
),
CONNECTION_HOST_DOWN_REGEX: (
__(
'The host "%(hostname)s" might be down, and can\'t be '
"reached on port %(port)s."
),
SupersetErrorType.CONNECTION_HOST_DOWN_ERROR,
{},
),
}
@classmethod
def epoch_to_dttm(cls) -> str:
return "dateadd(S, {col}, '1970-01-01')"
@classmethod
def convert_dttm(
cls, target_type: str, dttm: datetime, db_extra: Optional[Dict[str, Any]] = None
) -> Optional[str]:
tt = target_type.upper()
if tt == utils.TemporalType.DATE:
return f"CONVERT(DATE, '{dttm.date().isoformat()}', 23)"
if tt == utils.TemporalType.DATETIME:
datetime_formatted = dttm.isoformat(timespec="milliseconds")
return f"""CONVERT(DATETIME, '{datetime_formatted}', 126)"""
if tt == utils.TemporalType.SMALLDATETIME:
datetime_formatted = dttm.isoformat(sep=" ", timespec="seconds")
return f"""CONVERT(SMALLDATETIME, '{datetime_formatted}', 20)"""
return None
@classmethod
def fetch_data(
cls, cursor: Any, limit: Optional[int] = None
) -> List[Tuple[Any, ...]]:
data = super().fetch_data(cursor, limit)
# Lists of `pyodbc.Row` need to be unpacked further
return cls.pyodbc_rows_to_tuples(data)
@classmethod
def extract_error_message(cls, ex: Exception) -> str:
if str(ex).startswith("(8155,"):
return (
f"{cls.engine} error: All your SQL functions need to "
"have an alias on MSSQL. For example: SELECT COUNT(*) AS C1 FROM TABLE1"
)
return f"{cls.engine} error: {cls._extract_error_message(ex)}"
class AzureSynapseSpec(MssqlEngineSpec):
engine = "mssql"
engine_name = "Azure Synapse"
default_driver = "pyodbc"
| superset/db_engine_specs/mssql.py | 0 | https://github.com/apache/superset/commit/d28909d56c21c160a0140b87c4f268b1c4ea90f1 | [
0.0009433944942429662,
0.000247787160333246,
0.000165743927937001,
0.000174170098034665,
0.00020542784477584064
] |
{
"id": 4,
"code_window": [
"import { render, screen } from 'spec/helpers/testing-library';\n",
"import { getChartMetadataRegistry, ChartMetadata } from '@superset-ui/core';\n",
"import ChartContainer from 'src/explore/components/ExploreChartPanel';\n",
"\n",
"const createProps = (overrides = {}) => ({\n",
" sliceName: 'Trend Line',\n",
" height: '500px',\n",
" actions: {},\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { setItem, LocalStorageKeys } from 'src/utils/localStorageHelpers';\n"
],
"file_path": "superset-frontend/src/explore/components/ExploreChartPanel.test.jsx",
"type": "add",
"edit_start_line_idx": 23
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import PropTypes from 'prop-types';
import Split from 'react-split';
import {
css,
ensureIsArray,
styled,
SupersetClient,
t,
useTheme,
getChartMetadataRegistry,
DatasourceType,
} from '@superset-ui/core';
import { useResizeDetector } from 'react-resize-detector';
import { chartPropShape } from 'src/dashboard/util/propShapes';
import ChartContainer from 'src/components/Chart/ChartContainer';
import {
getItem,
setItem,
LocalStorageKeys,
} from 'src/utils/localStorageHelpers';
import Alert from 'src/components/Alert';
import { SaveDatasetModal } from 'src/SqlLab/components/SaveDatasetModal';
import { getDatasourceAsSaveableDataset } from 'src/utils/datasourceUtils';
import { DataTablesPane } from './DataTablesPane';
import { buildV1ChartDataPayload } from '../exploreUtils';
import { ChartPills } from './ChartPills';
import { ExploreAlert } from './ExploreAlert';
import { getChartRequiredFieldsMissingMessage } from '../../utils/getChartRequiredFieldsMissingMessage';
const propTypes = {
actions: PropTypes.object.isRequired,
onQuery: PropTypes.func,
can_overwrite: PropTypes.bool.isRequired,
can_download: PropTypes.bool.isRequired,
datasource: PropTypes.object,
dashboardId: PropTypes.number,
column_formats: PropTypes.object,
containerId: PropTypes.string.isRequired,
isStarred: PropTypes.bool.isRequired,
slice: PropTypes.object,
sliceName: PropTypes.string,
table_name: PropTypes.string,
vizType: PropTypes.string.isRequired,
form_data: PropTypes.object,
ownState: PropTypes.object,
standalone: PropTypes.bool,
force: PropTypes.bool,
timeout: PropTypes.number,
chartIsStale: PropTypes.bool,
chart: chartPropShape,
errorMessage: PropTypes.node,
triggerRender: PropTypes.bool,
};
const GUTTER_SIZE_FACTOR = 1.25;
const INITIAL_SIZES = [100, 0];
const MIN_SIZES = [300, 65];
const DEFAULT_SOUTH_PANE_HEIGHT_PERCENT = 40;
const Styles = styled.div`
display: flex;
flex-direction: column;
align-items: stretch;
align-content: stretch;
overflow: auto;
box-shadow: none;
height: 100%;
& > div {
height: 100%;
}
.gutter {
border-top: 1px solid ${({ theme }) => theme.colors.grayscale.light2};
border-bottom: 1px solid ${({ theme }) => theme.colors.grayscale.light2};
width: ${({ theme }) => theme.gridUnit * 9}px;
margin: ${({ theme }) => theme.gridUnit * GUTTER_SIZE_FACTOR}px auto;
}
.gutter.gutter-vertical {
cursor: row-resize;
}
.ant-collapse {
.ant-tabs {
height: 100%;
.ant-tabs-nav {
padding-left: ${({ theme }) => theme.gridUnit * 5}px;
margin: 0;
}
.ant-tabs-content-holder {
overflow: hidden;
.ant-tabs-content {
height: 100%;
}
}
}
}
`;
const ExploreChartPanel = ({
chart,
slice,
vizType,
ownState,
triggerRender,
force,
datasource,
errorMessage,
form_data: formData,
onQuery,
actions,
timeout,
standalone,
chartIsStale,
chartAlert,
}) => {
const theme = useTheme();
const gutterMargin = theme.gridUnit * GUTTER_SIZE_FACTOR;
const gutterHeight = theme.gridUnit * GUTTER_SIZE_FACTOR;
const {
width: chartPanelWidth,
height: chartPanelHeight,
ref: chartPanelRef,
} = useResizeDetector({
refreshMode: 'debounce',
refreshRate: 300,
});
const [splitSizes, setSplitSizes] = useState(
getItem(LocalStorageKeys.chart_split_sizes, INITIAL_SIZES),
);
const [showDatasetModal, setShowDatasetModal] = useState(false);
const metaDataRegistry = getChartMetadataRegistry();
const { useLegacyApi } = metaDataRegistry.get(vizType) ?? {};
const vizTypeNeedsDataset =
useLegacyApi && datasource.type !== DatasourceType.Table;
// added boolean column to below show boolean so that the errors aren't overlapping
const showAlertBanner =
!chartAlert &&
chartIsStale &&
!vizTypeNeedsDataset &&
chart.chartStatus !== 'failed' &&
ensureIsArray(chart.queriesResponse).length > 0;
const updateQueryContext = useCallback(
async function fetchChartData() {
if (slice && slice.query_context === null) {
const queryContext = buildV1ChartDataPayload({
formData: slice.form_data,
force,
resultFormat: 'json',
resultType: 'full',
setDataMask: null,
ownState: null,
});
await SupersetClient.put({
endpoint: `/api/v1/chart/${slice.slice_id}`,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query_context: JSON.stringify(queryContext),
query_context_generation: true,
}),
});
}
},
[slice],
);
useEffect(() => {
updateQueryContext();
}, [updateQueryContext]);
useEffect(() => {
setItem(LocalStorageKeys.chart_split_sizes, splitSizes);
}, [splitSizes]);
const onDragEnd = useCallback(sizes => {
setSplitSizes(sizes);
}, []);
const refreshCachedQuery = useCallback(() => {
actions.setForceQuery(true);
actions.postChartFormData(
formData,
true,
timeout,
chart.id,
undefined,
ownState,
);
actions.updateQueryFormData(formData, chart.id);
}, [actions, chart.id, formData, ownState, timeout]);
const onCollapseChange = useCallback(isOpen => {
let splitSizes;
if (!isOpen) {
splitSizes = INITIAL_SIZES;
} else {
splitSizes = [
100 - DEFAULT_SOUTH_PANE_HEIGHT_PERCENT,
DEFAULT_SOUTH_PANE_HEIGHT_PERCENT,
];
}
setSplitSizes(splitSizes);
}, []);
const renderChart = useCallback(
() => (
<div
css={css`
min-height: 0;
flex: 1;
overflow: auto;
`}
ref={chartPanelRef}
>
{chartPanelWidth && chartPanelHeight && (
<ChartContainer
width={Math.floor(chartPanelWidth)}
height={chartPanelHeight}
ownState={ownState}
annotationData={chart.annotationData}
chartAlert={chart.chartAlert}
chartStackTrace={chart.chartStackTrace}
chartId={chart.id}
chartStatus={chart.chartStatus}
triggerRender={triggerRender}
force={force}
datasource={datasource}
errorMessage={errorMessage}
formData={formData}
latestQueryFormData={chart.latestQueryFormData}
onQuery={onQuery}
queriesResponse={chart.queriesResponse}
chartIsStale={chartIsStale}
setControlValue={actions.setControlValue}
timeout={timeout}
triggerQuery={chart.triggerQuery}
vizType={vizType}
/>
)}
</div>
),
[
actions.setControlValue,
chart.annotationData,
chart.chartAlert,
chart.chartStackTrace,
chart.chartStatus,
chart.id,
chart.latestQueryFormData,
chart.queriesResponse,
chart.triggerQuery,
chartIsStale,
chartPanelHeight,
chartPanelRef,
chartPanelWidth,
datasource,
errorMessage,
force,
formData,
onQuery,
ownState,
timeout,
triggerRender,
vizType,
],
);
const panelBody = useMemo(
() => (
<div
className="panel-body"
css={css`
display: flex;
flex-direction: column;
`}
>
{vizTypeNeedsDataset && (
<Alert
message={t('Chart type requires a dataset')}
type="error"
css={theme => css`
margin: 0 0 ${theme.gridUnit * 4}px 0;
`}
description={
<>
{t(
'This chart type is not supported when using an unsaved query as a chart source. ',
)}
<span
role="button"
tabIndex={0}
onClick={() => setShowDatasetModal(true)}
css={{ textDecoration: 'underline' }}
>
{t('Create a dataset')}
</span>
{t(' to visualize your data.')}
</>
}
/>
)}
{showAlertBanner && (
<ExploreAlert
title={
errorMessage
? t('Required control values have been removed')
: t('Your chart is not up to date')
}
bodyText={
errorMessage ? (
getChartRequiredFieldsMissingMessage(false)
) : (
<span>
{t(
'You updated the values in the control panel, but the chart was not updated automatically. Run the query by clicking on the "Update chart" button or',
)}{' '}
<span role="button" tabIndex={0} onClick={onQuery}>
{t('click here')}
</span>
.
</span>
)
}
type="warning"
css={theme => css`
margin: 0 0 ${theme.gridUnit * 4}px 0;
`}
/>
)}
<ChartPills
queriesResponse={chart.queriesResponse}
chartStatus={chart.chartStatus}
chartUpdateStartTime={chart.chartUpdateStartTime}
chartUpdateEndTime={chart.chartUpdateEndTime}
refreshCachedQuery={refreshCachedQuery}
rowLimit={formData?.row_limit}
/>
{renderChart()}
</div>
),
[
showAlertBanner,
errorMessage,
onQuery,
chart.queriesResponse,
chart.chartStatus,
chart.chartUpdateStartTime,
chart.chartUpdateEndTime,
refreshCachedQuery,
formData?.row_limit,
renderChart,
],
);
const standaloneChartBody = useMemo(() => renderChart(), [renderChart]);
const [queryFormData, setQueryFormData] = useState(chart.latestQueryFormData);
useEffect(() => {
// only update when `latestQueryFormData` changes AND `triggerRender`
// is false. No update should be done when only `triggerRender` changes,
// as this can trigger a query downstream based on incomplete form data.
// (`latestQueryFormData` is only updated when a a valid request has been
// triggered).
if (!triggerRender) {
setQueryFormData(chart.latestQueryFormData);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [chart.latestQueryFormData]);
const elementStyle = useCallback(
(dimension, elementSize, gutterSize) => ({
[dimension]: `calc(${elementSize}% - ${gutterSize + gutterMargin}px)`,
}),
[gutterMargin],
);
if (standalone) {
// dom manipulation hack to get rid of the boostrap theme's body background
const standaloneClass = 'background-transparent';
const bodyClasses = document.body.className.split(' ');
if (!bodyClasses.includes(standaloneClass)) {
document.body.className += ` ${standaloneClass}`;
}
return standaloneChartBody;
}
return (
<Styles className="panel panel-default chart-container">
{vizType === 'filter_box' ? (
panelBody
) : (
<Split
sizes={splitSizes}
minSize={MIN_SIZES}
direction="vertical"
gutterSize={gutterHeight}
onDragEnd={onDragEnd}
elementStyle={elementStyle}
expandToMin
>
{panelBody}
<DataTablesPane
ownState={ownState}
queryFormData={queryFormData}
datasource={datasource}
queryForce={force}
onCollapseChange={onCollapseChange}
chartStatus={chart.chartStatus}
errorMessage={errorMessage}
actions={actions}
/>
</Split>
)}
{showDatasetModal && (
<SaveDatasetModal
visible={showDatasetModal}
onHide={() => setShowDatasetModal(false)}
buttonTextOnSave={t('Save')}
buttonTextOnOverwrite={t('Overwrite')}
datasource={getDatasourceAsSaveableDataset(datasource)}
openWindow={false}
formData={formData}
/>
)}
</Styles>
);
};
ExploreChartPanel.propTypes = propTypes;
export default ExploreChartPanel;
| superset-frontend/src/explore/components/ExploreChartPanel.jsx | 1 | https://github.com/apache/superset/commit/d28909d56c21c160a0140b87c4f268b1c4ea90f1 | [
0.003953506704419851,
0.000378424214432016,
0.00016330703510902822,
0.00017230273806490004,
0.0007151856552809477
] |
{
"id": 4,
"code_window": [
"import { render, screen } from 'spec/helpers/testing-library';\n",
"import { getChartMetadataRegistry, ChartMetadata } from '@superset-ui/core';\n",
"import ChartContainer from 'src/explore/components/ExploreChartPanel';\n",
"\n",
"const createProps = (overrides = {}) => ({\n",
" sliceName: 'Trend Line',\n",
" height: '500px',\n",
" actions: {},\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { setItem, LocalStorageKeys } from 'src/utils/localStorageHelpers';\n"
],
"file_path": "superset-frontend/src/explore/components/ExploreChartPanel.test.jsx",
"type": "add",
"edit_start_line_idx": 23
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { NativeFilterScope } from '@superset-ui/core';
import { CHART_TYPE } from './componentTypes';
import { ChartsState, Layout } from '../types';
export function getChartIdsInFilterScope(
filterScope: NativeFilterScope,
charts: ChartsState,
layout: Layout,
) {
const layoutItems = Object.values(layout);
return Object.values(charts)
.filter(
chart =>
!filterScope.excluded.includes(chart.id) &&
layoutItems
.find(
layoutItem =>
layoutItem?.type === CHART_TYPE &&
layoutItem.meta?.chartId === chart.id,
)
?.parents?.some(elementId =>
filterScope.rootPath.includes(elementId),
),
)
.map(chart => chart.id);
}
| superset-frontend/src/dashboard/util/getChartIdsInFilterScope.ts | 0 | https://github.com/apache/superset/commit/d28909d56c21c160a0140b87c4f268b1c4ea90f1 | [
0.00017798868066165596,
0.00017306776135228574,
0.0001695618557278067,
0.00017195413238368928,
0.000003278186113675474
] |
{
"id": 4,
"code_window": [
"import { render, screen } from 'spec/helpers/testing-library';\n",
"import { getChartMetadataRegistry, ChartMetadata } from '@superset-ui/core';\n",
"import ChartContainer from 'src/explore/components/ExploreChartPanel';\n",
"\n",
"const createProps = (overrides = {}) => ({\n",
" sliceName: 'Trend Line',\n",
" height: '500px',\n",
" actions: {},\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { setItem, LocalStorageKeys } from 'src/utils/localStorageHelpers';\n"
],
"file_path": "superset-frontend/src/explore/components/ExploreChartPanel.test.jsx",
"type": "add",
"edit_start_line_idx": 23
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import logging
from typing import Type
from flask import Response
from flask_appbuilder.api import expose, protect, safe
from superset.dashboards.filter_state.commands.create import CreateFilterStateCommand
from superset.dashboards.filter_state.commands.delete import DeleteFilterStateCommand
from superset.dashboards.filter_state.commands.get import GetFilterStateCommand
from superset.dashboards.filter_state.commands.update import UpdateFilterStateCommand
from superset.extensions import event_logger
from superset.temporary_cache.api import TemporaryCacheRestApi
logger = logging.getLogger(__name__)
class DashboardFilterStateRestApi(TemporaryCacheRestApi):
class_permission_name = "DashboardFilterStateRestApi"
resource_name = "dashboard"
openapi_spec_tag = "Dashboard Filter State"
def get_create_command(self) -> Type[CreateFilterStateCommand]:
return CreateFilterStateCommand
def get_update_command(self) -> Type[UpdateFilterStateCommand]:
return UpdateFilterStateCommand
def get_get_command(self) -> Type[GetFilterStateCommand]:
return GetFilterStateCommand
def get_delete_command(self) -> Type[DeleteFilterStateCommand]:
return DeleteFilterStateCommand
@expose("/<int:pk>/filter_state", methods=["POST"])
@protect()
@safe
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.post",
log_to_statsd=False,
)
def post(self, pk: int) -> Response:
"""Stores a new value.
---
post:
description: >-
Stores a new value.
parameters:
- in: path
schema:
type: integer
name: pk
- in: query
schema:
type: integer
name: tab_id
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/TemporaryCachePostSchema'
responses:
201:
description: The value was stored successfully.
content:
application/json:
schema:
type: object
properties:
key:
type: string
description: The key to retrieve the value.
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
return super().post(pk)
@expose("/<int:pk>/filter_state/<string:key>", methods=["PUT"])
@protect()
@safe
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.put",
log_to_statsd=False,
)
def put(self, pk: int, key: str) -> Response:
"""Updates an existing value.
---
put:
description: >-
Updates an existing value.
parameters:
- in: path
schema:
type: integer
name: pk
- in: path
schema:
type: string
name: key
- in: query
schema:
type: integer
name: tab_id
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/TemporaryCachePutSchema'
responses:
200:
description: The value was stored successfully.
content:
application/json:
schema:
type: object
properties:
key:
type: string
description: The key to retrieve the value.
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
return super().put(pk, key)
@expose("/<int:pk>/filter_state/<string:key>", methods=["GET"])
@protect()
@safe
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.get",
log_to_statsd=False,
)
def get(self, pk: int, key: str) -> Response:
"""Retrives a value.
---
get:
description: >-
Retrives a value.
parameters:
- in: path
schema:
type: integer
name: pk
- in: path
schema:
type: string
name: key
responses:
200:
description: Returns the stored value.
content:
application/json:
schema:
type: object
properties:
value:
type: string
description: The stored value
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
return super().get(pk, key)
@expose("/<int:pk>/filter_state/<string:key>", methods=["DELETE"])
@protect()
@safe
@event_logger.log_this_with_context(
action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.delete",
log_to_statsd=False,
)
def delete(self, pk: int, key: str) -> Response:
"""Deletes a value.
---
delete:
description: >-
Deletes a value.
parameters:
- in: path
schema:
type: integer
name: pk
- in: path
schema:
type: string
name: key
description: The value key.
responses:
200:
description: Deleted the stored value.
content:
application/json:
schema:
type: object
properties:
message:
type: string
description: The result of the operation
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
return super().delete(pk, key)
| superset/dashboards/filter_state/api.py | 0 | https://github.com/apache/superset/commit/d28909d56c21c160a0140b87c4f268b1c4ea90f1 | [
0.00017981475684791803,
0.00017532236233819276,
0.00017166562611237168,
0.00017520597612019628,
0.000002045492237812141
] |
{
"id": 4,
"code_window": [
"import { render, screen } from 'spec/helpers/testing-library';\n",
"import { getChartMetadataRegistry, ChartMetadata } from '@superset-ui/core';\n",
"import ChartContainer from 'src/explore/components/ExploreChartPanel';\n",
"\n",
"const createProps = (overrides = {}) => ({\n",
" sliceName: 'Trend Line',\n",
" height: '500px',\n",
" actions: {},\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { setItem, LocalStorageKeys } from 'src/utils/localStorageHelpers';\n"
],
"file_path": "superset-frontend/src/explore/components/ExploreChartPanel.test.jsx",
"type": "add",
"edit_start_line_idx": 23
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from typing import TYPE_CHECKING
from superset.app import create_app
if TYPE_CHECKING:
from typing import Any
from flask.testing import FlaskClient
app = create_app()
def login(
client: "FlaskClient[Any]", username: str = "admin", password: str = "general"
):
resp = client.post(
"/login/",
data=dict(username=username, password=password),
).get_data(as_text=True)
assert "User confirmation needed" not in resp
| tests/integration_tests/test_app.py | 0 | https://github.com/apache/superset/commit/d28909d56c21c160a0140b87c4f268b1c4ea90f1 | [
0.00017927854787558317,
0.00017463054973632097,
0.0001699436834314838,
0.00017464999109506607,
0.00000454966357210651
] |
{
"id": 5,
"code_window": [
" });\n",
" render(<ChartContainer {...props} />, { useRedux: true });\n",
" expect(await screen.findByRole('timer')).toBeInTheDocument();\n",
" expect(screen.queryByText(/cached/i)).not.toBeInTheDocument();\n",
" });\n",
"});"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\n",
" it('hides gutter when collapsing data panel', async () => {\n",
" const props = createProps();\n",
" setItem(LocalStorageKeys.is_datapanel_open, true);\n",
" const { container } = render(<ChartContainer {...props} />, {\n",
" useRedux: true,\n",
" });\n",
" const gutter = container.querySelector('.gutter');\n",
" expect(window.getComputedStyle(gutter).display).toBe('block');\n",
" userEvent.click(screen.getByLabelText('Collapse data panel'));\n",
" expect(window.getComputedStyle(gutter).display).toBe('none');\n",
" });\n"
],
"file_path": "superset-frontend/src/explore/components/ExploreChartPanel.test.jsx",
"type": "add",
"edit_start_line_idx": 152
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import PropTypes from 'prop-types';
import Split from 'react-split';
import {
css,
ensureIsArray,
styled,
SupersetClient,
t,
useTheme,
getChartMetadataRegistry,
DatasourceType,
} from '@superset-ui/core';
import { useResizeDetector } from 'react-resize-detector';
import { chartPropShape } from 'src/dashboard/util/propShapes';
import ChartContainer from 'src/components/Chart/ChartContainer';
import {
getItem,
setItem,
LocalStorageKeys,
} from 'src/utils/localStorageHelpers';
import Alert from 'src/components/Alert';
import { SaveDatasetModal } from 'src/SqlLab/components/SaveDatasetModal';
import { getDatasourceAsSaveableDataset } from 'src/utils/datasourceUtils';
import { DataTablesPane } from './DataTablesPane';
import { buildV1ChartDataPayload } from '../exploreUtils';
import { ChartPills } from './ChartPills';
import { ExploreAlert } from './ExploreAlert';
import { getChartRequiredFieldsMissingMessage } from '../../utils/getChartRequiredFieldsMissingMessage';
const propTypes = {
actions: PropTypes.object.isRequired,
onQuery: PropTypes.func,
can_overwrite: PropTypes.bool.isRequired,
can_download: PropTypes.bool.isRequired,
datasource: PropTypes.object,
dashboardId: PropTypes.number,
column_formats: PropTypes.object,
containerId: PropTypes.string.isRequired,
isStarred: PropTypes.bool.isRequired,
slice: PropTypes.object,
sliceName: PropTypes.string,
table_name: PropTypes.string,
vizType: PropTypes.string.isRequired,
form_data: PropTypes.object,
ownState: PropTypes.object,
standalone: PropTypes.bool,
force: PropTypes.bool,
timeout: PropTypes.number,
chartIsStale: PropTypes.bool,
chart: chartPropShape,
errorMessage: PropTypes.node,
triggerRender: PropTypes.bool,
};
const GUTTER_SIZE_FACTOR = 1.25;
const INITIAL_SIZES = [100, 0];
const MIN_SIZES = [300, 65];
const DEFAULT_SOUTH_PANE_HEIGHT_PERCENT = 40;
const Styles = styled.div`
display: flex;
flex-direction: column;
align-items: stretch;
align-content: stretch;
overflow: auto;
box-shadow: none;
height: 100%;
& > div {
height: 100%;
}
.gutter {
border-top: 1px solid ${({ theme }) => theme.colors.grayscale.light2};
border-bottom: 1px solid ${({ theme }) => theme.colors.grayscale.light2};
width: ${({ theme }) => theme.gridUnit * 9}px;
margin: ${({ theme }) => theme.gridUnit * GUTTER_SIZE_FACTOR}px auto;
}
.gutter.gutter-vertical {
cursor: row-resize;
}
.ant-collapse {
.ant-tabs {
height: 100%;
.ant-tabs-nav {
padding-left: ${({ theme }) => theme.gridUnit * 5}px;
margin: 0;
}
.ant-tabs-content-holder {
overflow: hidden;
.ant-tabs-content {
height: 100%;
}
}
}
}
`;
const ExploreChartPanel = ({
chart,
slice,
vizType,
ownState,
triggerRender,
force,
datasource,
errorMessage,
form_data: formData,
onQuery,
actions,
timeout,
standalone,
chartIsStale,
chartAlert,
}) => {
const theme = useTheme();
const gutterMargin = theme.gridUnit * GUTTER_SIZE_FACTOR;
const gutterHeight = theme.gridUnit * GUTTER_SIZE_FACTOR;
const {
width: chartPanelWidth,
height: chartPanelHeight,
ref: chartPanelRef,
} = useResizeDetector({
refreshMode: 'debounce',
refreshRate: 300,
});
const [splitSizes, setSplitSizes] = useState(
getItem(LocalStorageKeys.chart_split_sizes, INITIAL_SIZES),
);
const [showDatasetModal, setShowDatasetModal] = useState(false);
const metaDataRegistry = getChartMetadataRegistry();
const { useLegacyApi } = metaDataRegistry.get(vizType) ?? {};
const vizTypeNeedsDataset =
useLegacyApi && datasource.type !== DatasourceType.Table;
// added boolean column to below show boolean so that the errors aren't overlapping
const showAlertBanner =
!chartAlert &&
chartIsStale &&
!vizTypeNeedsDataset &&
chart.chartStatus !== 'failed' &&
ensureIsArray(chart.queriesResponse).length > 0;
const updateQueryContext = useCallback(
async function fetchChartData() {
if (slice && slice.query_context === null) {
const queryContext = buildV1ChartDataPayload({
formData: slice.form_data,
force,
resultFormat: 'json',
resultType: 'full',
setDataMask: null,
ownState: null,
});
await SupersetClient.put({
endpoint: `/api/v1/chart/${slice.slice_id}`,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query_context: JSON.stringify(queryContext),
query_context_generation: true,
}),
});
}
},
[slice],
);
useEffect(() => {
updateQueryContext();
}, [updateQueryContext]);
useEffect(() => {
setItem(LocalStorageKeys.chart_split_sizes, splitSizes);
}, [splitSizes]);
const onDragEnd = useCallback(sizes => {
setSplitSizes(sizes);
}, []);
const refreshCachedQuery = useCallback(() => {
actions.setForceQuery(true);
actions.postChartFormData(
formData,
true,
timeout,
chart.id,
undefined,
ownState,
);
actions.updateQueryFormData(formData, chart.id);
}, [actions, chart.id, formData, ownState, timeout]);
const onCollapseChange = useCallback(isOpen => {
let splitSizes;
if (!isOpen) {
splitSizes = INITIAL_SIZES;
} else {
splitSizes = [
100 - DEFAULT_SOUTH_PANE_HEIGHT_PERCENT,
DEFAULT_SOUTH_PANE_HEIGHT_PERCENT,
];
}
setSplitSizes(splitSizes);
}, []);
const renderChart = useCallback(
() => (
<div
css={css`
min-height: 0;
flex: 1;
overflow: auto;
`}
ref={chartPanelRef}
>
{chartPanelWidth && chartPanelHeight && (
<ChartContainer
width={Math.floor(chartPanelWidth)}
height={chartPanelHeight}
ownState={ownState}
annotationData={chart.annotationData}
chartAlert={chart.chartAlert}
chartStackTrace={chart.chartStackTrace}
chartId={chart.id}
chartStatus={chart.chartStatus}
triggerRender={triggerRender}
force={force}
datasource={datasource}
errorMessage={errorMessage}
formData={formData}
latestQueryFormData={chart.latestQueryFormData}
onQuery={onQuery}
queriesResponse={chart.queriesResponse}
chartIsStale={chartIsStale}
setControlValue={actions.setControlValue}
timeout={timeout}
triggerQuery={chart.triggerQuery}
vizType={vizType}
/>
)}
</div>
),
[
actions.setControlValue,
chart.annotationData,
chart.chartAlert,
chart.chartStackTrace,
chart.chartStatus,
chart.id,
chart.latestQueryFormData,
chart.queriesResponse,
chart.triggerQuery,
chartIsStale,
chartPanelHeight,
chartPanelRef,
chartPanelWidth,
datasource,
errorMessage,
force,
formData,
onQuery,
ownState,
timeout,
triggerRender,
vizType,
],
);
const panelBody = useMemo(
() => (
<div
className="panel-body"
css={css`
display: flex;
flex-direction: column;
`}
>
{vizTypeNeedsDataset && (
<Alert
message={t('Chart type requires a dataset')}
type="error"
css={theme => css`
margin: 0 0 ${theme.gridUnit * 4}px 0;
`}
description={
<>
{t(
'This chart type is not supported when using an unsaved query as a chart source. ',
)}
<span
role="button"
tabIndex={0}
onClick={() => setShowDatasetModal(true)}
css={{ textDecoration: 'underline' }}
>
{t('Create a dataset')}
</span>
{t(' to visualize your data.')}
</>
}
/>
)}
{showAlertBanner && (
<ExploreAlert
title={
errorMessage
? t('Required control values have been removed')
: t('Your chart is not up to date')
}
bodyText={
errorMessage ? (
getChartRequiredFieldsMissingMessage(false)
) : (
<span>
{t(
'You updated the values in the control panel, but the chart was not updated automatically. Run the query by clicking on the "Update chart" button or',
)}{' '}
<span role="button" tabIndex={0} onClick={onQuery}>
{t('click here')}
</span>
.
</span>
)
}
type="warning"
css={theme => css`
margin: 0 0 ${theme.gridUnit * 4}px 0;
`}
/>
)}
<ChartPills
queriesResponse={chart.queriesResponse}
chartStatus={chart.chartStatus}
chartUpdateStartTime={chart.chartUpdateStartTime}
chartUpdateEndTime={chart.chartUpdateEndTime}
refreshCachedQuery={refreshCachedQuery}
rowLimit={formData?.row_limit}
/>
{renderChart()}
</div>
),
[
showAlertBanner,
errorMessage,
onQuery,
chart.queriesResponse,
chart.chartStatus,
chart.chartUpdateStartTime,
chart.chartUpdateEndTime,
refreshCachedQuery,
formData?.row_limit,
renderChart,
],
);
const standaloneChartBody = useMemo(() => renderChart(), [renderChart]);
const [queryFormData, setQueryFormData] = useState(chart.latestQueryFormData);
useEffect(() => {
// only update when `latestQueryFormData` changes AND `triggerRender`
// is false. No update should be done when only `triggerRender` changes,
// as this can trigger a query downstream based on incomplete form data.
// (`latestQueryFormData` is only updated when a a valid request has been
// triggered).
if (!triggerRender) {
setQueryFormData(chart.latestQueryFormData);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [chart.latestQueryFormData]);
const elementStyle = useCallback(
(dimension, elementSize, gutterSize) => ({
[dimension]: `calc(${elementSize}% - ${gutterSize + gutterMargin}px)`,
}),
[gutterMargin],
);
if (standalone) {
// dom manipulation hack to get rid of the boostrap theme's body background
const standaloneClass = 'background-transparent';
const bodyClasses = document.body.className.split(' ');
if (!bodyClasses.includes(standaloneClass)) {
document.body.className += ` ${standaloneClass}`;
}
return standaloneChartBody;
}
return (
<Styles className="panel panel-default chart-container">
{vizType === 'filter_box' ? (
panelBody
) : (
<Split
sizes={splitSizes}
minSize={MIN_SIZES}
direction="vertical"
gutterSize={gutterHeight}
onDragEnd={onDragEnd}
elementStyle={elementStyle}
expandToMin
>
{panelBody}
<DataTablesPane
ownState={ownState}
queryFormData={queryFormData}
datasource={datasource}
queryForce={force}
onCollapseChange={onCollapseChange}
chartStatus={chart.chartStatus}
errorMessage={errorMessage}
actions={actions}
/>
</Split>
)}
{showDatasetModal && (
<SaveDatasetModal
visible={showDatasetModal}
onHide={() => setShowDatasetModal(false)}
buttonTextOnSave={t('Save')}
buttonTextOnOverwrite={t('Overwrite')}
datasource={getDatasourceAsSaveableDataset(datasource)}
openWindow={false}
formData={formData}
/>
)}
</Styles>
);
};
ExploreChartPanel.propTypes = propTypes;
export default ExploreChartPanel;
| superset-frontend/src/explore/components/ExploreChartPanel.jsx | 1 | https://github.com/apache/superset/commit/d28909d56c21c160a0140b87c4f268b1c4ea90f1 | [
0.00035446693073026836,
0.00017666937492322177,
0.00016391716781072319,
0.00017265928909182549,
0.000026854579118662514
] |
{
"id": 5,
"code_window": [
" });\n",
" render(<ChartContainer {...props} />, { useRedux: true });\n",
" expect(await screen.findByRole('timer')).toBeInTheDocument();\n",
" expect(screen.queryByText(/cached/i)).not.toBeInTheDocument();\n",
" });\n",
"});"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\n",
" it('hides gutter when collapsing data panel', async () => {\n",
" const props = createProps();\n",
" setItem(LocalStorageKeys.is_datapanel_open, true);\n",
" const { container } = render(<ChartContainer {...props} />, {\n",
" useRedux: true,\n",
" });\n",
" const gutter = container.querySelector('.gutter');\n",
" expect(window.getComputedStyle(gutter).display).toBe('block');\n",
" userEvent.click(screen.getByLabelText('Collapse data panel'));\n",
" expect(window.getComputedStyle(gutter).display).toBe('none');\n",
" });\n"
],
"file_path": "superset-frontend/src/explore/components/ExploreChartPanel.test.jsx",
"type": "add",
"edit_start_line_idx": 152
} | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { createMultiFormatter } from '@superset-ui/core';
describe('createMultiFormatter()', () => {
describe('creates a multi-step formatter', () => {
const formatter = createMultiFormatter({
id: 'my_format',
useLocalTime: true,
});
it('formats millisecond', () => {
expect(formatter(new Date(2018, 10, 20, 11, 22, 33, 100))).toEqual(
'.100',
);
});
it('formats second', () => {
expect(formatter(new Date(2018, 10, 20, 11, 22, 33))).toEqual(':33');
});
it('format minutes', () => {
expect(formatter(new Date(2018, 10, 20, 11, 22))).toEqual('11:22');
});
it('format hours', () => {
expect(formatter(new Date(2018, 10, 20, 11))).toEqual('11 AM');
});
it('format first day of week', () => {
expect(formatter(new Date(2018, 10, 18))).toEqual('Nov 18');
});
it('format other day of week', () => {
expect(formatter(new Date(2018, 10, 20))).toEqual('Tue 20');
});
it('format month', () => {
expect(formatter(new Date(2018, 10))).toEqual('November');
});
it('format year', () => {
expect(formatter(new Date(2018, 0))).toEqual('2018');
});
});
});
| superset-frontend/packages/superset-ui-core/test/time-format/factories/createMultiFormatter.test.ts | 0 | https://github.com/apache/superset/commit/d28909d56c21c160a0140b87c4f268b1c4ea90f1 | [
0.00017985727754421532,
0.0001780114253051579,
0.00017641227168496698,
0.0001777229772415012,
0.0000013360856883082306
] |
{
"id": 5,
"code_window": [
" });\n",
" render(<ChartContainer {...props} />, { useRedux: true });\n",
" expect(await screen.findByRole('timer')).toBeInTheDocument();\n",
" expect(screen.queryByText(/cached/i)).not.toBeInTheDocument();\n",
" });\n",
"});"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\n",
" it('hides gutter when collapsing data panel', async () => {\n",
" const props = createProps();\n",
" setItem(LocalStorageKeys.is_datapanel_open, true);\n",
" const { container } = render(<ChartContainer {...props} />, {\n",
" useRedux: true,\n",
" });\n",
" const gutter = container.querySelector('.gutter');\n",
" expect(window.getComputedStyle(gutter).display).toBe('block');\n",
" userEvent.click(screen.getByLabelText('Collapse data panel'));\n",
" expect(window.getComputedStyle(gutter).display).toBe('none');\n",
" });\n"
],
"file_path": "superset-frontend/src/explore/components/ExploreChartPanel.test.jsx",
"type": "add",
"edit_start_line_idx": 152
} | {
"name": "@superset-ui/preset-chart-xy",
"version": "0.18.25",
"description": "Superset Chart - XY",
"sideEffects": [
"*.css"
],
"main": "lib/index.js",
"module": "esm/index.js",
"files": [
"esm",
"lib",
"types"
],
"repository": {
"type": "git",
"url": "git+https://github.com/apache-superset/superset-ui.git"
},
"keywords": [
"superset"
],
"author": "Superset",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/apache-superset/superset-ui/issues"
},
"homepage": "https://github.com/apache-superset/superset-ui#readme",
"publishConfig": {
"access": "public"
},
"dependencies": {
"@data-ui/theme": "^0.0.84",
"@data-ui/xy-chart": "^0.0.84",
"@vx/axis": "^0.0.198",
"@vx/legend": "^0.0.198",
"@vx/scale": "^0.0.197",
"csstype": "^2.6.3",
"encodable": "^0.7.6",
"lodash": "^4.17.11",
"reselect": "^4.0.0"
},
"peerDependencies": {
"@superset-ui/chart-controls": "*",
"@superset-ui/core": "*",
"react": "^16.2"
}
}
| superset-frontend/plugins/preset-chart-xy/package.json | 0 | https://github.com/apache/superset/commit/d28909d56c21c160a0140b87c4f268b1c4ea90f1 | [
0.0001779448939487338,
0.00017634115647524595,
0.00017476848734077066,
0.00017616567492950708,
0.0000011155037782373256
] |
{
"id": 5,
"code_window": [
" });\n",
" render(<ChartContainer {...props} />, { useRedux: true });\n",
" expect(await screen.findByRole('timer')).toBeInTheDocument();\n",
" expect(screen.queryByText(/cached/i)).not.toBeInTheDocument();\n",
" });\n",
"});"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\n",
" it('hides gutter when collapsing data panel', async () => {\n",
" const props = createProps();\n",
" setItem(LocalStorageKeys.is_datapanel_open, true);\n",
" const { container } = render(<ChartContainer {...props} />, {\n",
" useRedux: true,\n",
" });\n",
" const gutter = container.querySelector('.gutter');\n",
" expect(window.getComputedStyle(gutter).display).toBe('block');\n",
" userEvent.click(screen.getByLabelText('Collapse data panel'));\n",
" expect(window.getComputedStyle(gutter).display).toBe('none');\n",
" });\n"
],
"file_path": "superset-frontend/src/explore/components/ExploreChartPanel.test.jsx",
"type": "add",
"edit_start_line_idx": 152
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import { combineReducers, createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import mockState from 'spec/fixtures/mockState';
import reducerIndex from 'spec/helpers/reducerIndex';
import { screen, render } from 'spec/helpers/testing-library';
import { initialState } from 'src/SqlLab/fixtures';
import { dashboardFilters } from 'spec/fixtures/mockDashboardFilters';
import { dashboardWithFilter } from 'spec/fixtures/mockDashboardLayout';
import { buildActiveFilters } from './activeDashboardFilters';
import useFilterFocusHighlightStyles from './useFilterFocusHighlightStyles';
const TestComponent = ({ chartId }: { chartId: number }) => {
const styles = useFilterFocusHighlightStyles(chartId);
return <div data-test="test-component" style={styles} />;
};
describe('useFilterFocusHighlightStyles', () => {
const createMockStore = (customState: any = {}) =>
createStore(
combineReducers(reducerIndex),
{ ...mockState, ...(initialState as any), ...customState },
compose(applyMiddleware(thunk)),
);
const renderWrapper = (chartId: number, store = createMockStore()) =>
render(<TestComponent chartId={chartId} />, {
useRouter: true,
useDnd: true,
useRedux: true,
store,
});
it('should return no style if filter not in scope', async () => {
renderWrapper(10);
const container = screen.getByTestId('test-component');
const styles = getComputedStyle(container);
expect(styles.opacity).toBeFalsy();
});
it('should return unfocused styles if chart is not in scope of focused native filter', async () => {
const store = createMockStore({
nativeFilters: {
focusedFilterId: 'test-filter',
filters: {
otherId: {
chartsInScope: [],
},
},
},
});
renderWrapper(10, store);
const container = screen.getByTestId('test-component');
const styles = getComputedStyle(container);
expect(parseFloat(styles.opacity)).toBe(0.3);
});
it('should return focused styles if chart is in scope of focused native filter', async () => {
const chartId = 18;
const store = createMockStore({
nativeFilters: {
focusedFilterId: 'testFilter',
filters: {
testFilter: {
chartsInScope: [chartId],
},
},
},
});
renderWrapper(chartId, store);
const container = screen.getByTestId('test-component');
const styles = getComputedStyle(container);
expect(parseFloat(styles.opacity)).toBe(1);
});
it('should return unfocused styles if focusedFilterField is targeting a different chart', async () => {
const chartId = 18;
const store = createMockStore({
dashboardState: {
focusedFilterField: {
chartId: 10,
column: 'test',
},
},
dashboardFilters: {
10: {
scopes: {},
},
},
});
renderWrapper(chartId, store);
const container = screen.getByTestId('test-component');
const styles = getComputedStyle(container);
expect(parseFloat(styles.opacity)).toBe(0.3);
});
it('should return focused styles if focusedFilterField chart equals our own', async () => {
const chartId = 18;
const store = createMockStore({
dashboardState: {
focusedFilterField: {
chartId,
column: 'test',
},
},
dashboardFilters: {
[chartId]: {
scopes: {
otherColumn: {},
},
},
},
});
renderWrapper(chartId, store);
const container = screen.getByTestId('test-component');
const styles = getComputedStyle(container);
expect(parseFloat(styles.opacity)).toBe(1);
});
it('should return unfocused styles if chart is not inside filter box scope', async () => {
buildActiveFilters({
dashboardFilters,
components: dashboardWithFilter,
});
const chartId = 18;
const store = createMockStore({
dashboardState: {
focusedFilterField: {
chartId,
column: 'test',
},
},
dashboardFilters: {
[chartId]: {
scopes: {
column: {},
},
},
},
});
renderWrapper(20, store);
const container = screen.getByTestId('test-component');
const styles = getComputedStyle(container);
expect(parseFloat(styles.opacity)).toBe(0.3);
});
it('should return focused styles if chart is inside filter box scope', async () => {
buildActiveFilters({
dashboardFilters,
components: dashboardWithFilter,
});
const chartId = 18;
const store = createMockStore({
dashboardState: {
focusedFilterField: {
chartId,
column: 'test',
},
},
dashboardFilters: {
[chartId]: {
scopes: {
column: {},
},
},
},
});
renderWrapper(chartId, store);
const container = screen.getByTestId('test-component');
const styles = getComputedStyle(container);
expect(parseFloat(styles.opacity)).toBe(1);
});
});
| superset-frontend/src/dashboard/util/useFilterFocusHighlightStyles.test.tsx | 0 | https://github.com/apache/superset/commit/d28909d56c21c160a0140b87c4f268b1c4ea90f1 | [
0.0007310148212127388,
0.0002895428042393178,
0.00016672619676683098,
0.0001771147653926164,
0.00017186262994073331
] |
{
"id": 0,
"code_window": [
"import { CellKind, CellOutputKind, ExtHostNotebookShape, IMainContext, MainContext, MainThreadNotebookShape, NotebookCellOutputsSplice } from 'vs/workbench/api/common/extHost.protocol';\n",
"import { ExtHostCommands } from 'vs/workbench/api/common/extHostCommands';\n",
"import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors';\n",
"import { CellEditType, CellUri, diff, ICellEditOperation, ICellInsertEdit, IErrorOutput, INotebookDisplayOrder, INotebookEditData, IOrderedMimeType, IStreamOutput, ITransformedDisplayOutputDto, mimeTypeSupportedByCore, NotebookCellsChangedEvent, NotebookCellsSplice2, sortMimeTypes } from 'vs/workbench/contrib/notebook/common/notebookCommon';\n",
"import { Disposable as VSCodeDisposable } from './extHostTypes';\n",
"\n",
"interface IObservable<T> {\n",
"\tproxy: T;\n",
"\tonDidChange: Event<void>;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { CellEditType, CellUri, diff, ICellEditOperation, ICellInsertEdit, IErrorOutput, INotebookDisplayOrder, INotebookEditData, IOrderedMimeType, IStreamOutput, ITransformedDisplayOutputDto, mimeTypeSupportedByCore, NotebookCellsChangedEvent, NotebookCellsSplice2, sortMimeTypes, ICellDeleteEdit } from 'vs/workbench/contrib/notebook/common/notebookCommon';\n"
],
"file_path": "src/vs/workbench/api/common/extHostNotebook.ts",
"type": "replace",
"edit_start_line_idx": 15
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { readonly } from 'vs/base/common/errors';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import { ISplice } from 'vs/base/common/sequence';
import { URI, UriComponents } from 'vs/base/common/uri';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { CellKind, CellOutputKind, ExtHostNotebookShape, IMainContext, MainContext, MainThreadNotebookShape, NotebookCellOutputsSplice } from 'vs/workbench/api/common/extHost.protocol';
import { ExtHostCommands } from 'vs/workbench/api/common/extHostCommands';
import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors';
import { CellEditType, CellUri, diff, ICellEditOperation, ICellInsertEdit, IErrorOutput, INotebookDisplayOrder, INotebookEditData, IOrderedMimeType, IStreamOutput, ITransformedDisplayOutputDto, mimeTypeSupportedByCore, NotebookCellsChangedEvent, NotebookCellsSplice2, sortMimeTypes } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { Disposable as VSCodeDisposable } from './extHostTypes';
interface IObservable<T> {
proxy: T;
onDidChange: Event<void>;
}
function getObservable<T extends Object>(obj: T): IObservable<T> {
const onDidChange = new Emitter<void>();
const proxy = new Proxy(obj, {
set(target: T, p: PropertyKey, value: any, _receiver: any): boolean {
target[p as keyof T] = value;
onDidChange.fire();
return true;
}
});
return {
proxy,
onDidChange: onDidChange.event
};
}
const notebookDocumentMetadataDefaults: vscode.NotebookDocumentMetadata = {
editable: true,
cellEditable: true,
cellRunnable: true
};
export class ExtHostCell extends Disposable implements vscode.NotebookCell {
private originalSource: string[];
private _outputs: any[];
private _onDidChangeOutputs = new Emitter<ISplice<vscode.CellOutput>[]>();
onDidChangeOutputs: Event<ISplice<vscode.CellOutput>[]> = this._onDidChangeOutputs.event;
private _textDocument: vscode.TextDocument | undefined;
private _initalVersion: number = -1;
private _outputMapping = new Set<vscode.CellOutput>();
private _metadata: vscode.NotebookCellMetadata;
private _metadataChangeListener: IDisposable;
get source() {
if (this._textDocument && this._initalVersion !== this._textDocument?.version) {
return this._textDocument.getText();
} else {
return this.originalSource.join('\n');
}
}
constructor(
private viewType: string,
private documentUri: URI,
readonly handle: number,
readonly uri: URI,
private _content: string,
public readonly cellKind: CellKind,
public language: string,
outputs: any[],
_metadata: vscode.NotebookCellMetadata | undefined,
private _proxy: MainThreadNotebookShape
) {
super();
this.originalSource = this._content.split(/\r|\n|\r\n/g);
this._outputs = outputs;
const observableMetadata = getObservable(_metadata || {} as any);
this._metadata = observableMetadata.proxy;
this._metadataChangeListener = this._register(observableMetadata.onDidChange(() => {
this.updateMetadata();
}));
}
get outputs() {
return this._outputs;
}
set outputs(newOutputs: vscode.CellOutput[]) {
let diffs = diff<vscode.CellOutput>(this._outputs || [], newOutputs || [], (a) => {
return this._outputMapping.has(a);
});
diffs.forEach(diff => {
for (let i = diff.start; i < diff.start + diff.deleteCount; i++) {
this._outputMapping.delete(this._outputs[i]);
}
diff.toInsert.forEach(output => {
this._outputMapping.add(output);
});
});
this._outputs = newOutputs;
this._onDidChangeOutputs.fire(diffs);
}
get metadata() {
return this._metadata;
}
set metadata(newMetadata: vscode.NotebookCellMetadata) {
this._metadataChangeListener.dispose();
const observableMetadata = getObservable(newMetadata || {} as any); // TODO defaults
this._metadata = observableMetadata.proxy;
this._metadataChangeListener = this._register(observableMetadata.onDidChange(() => {
this.updateMetadata();
}));
this.updateMetadata();
}
private updateMetadata(): Promise<void> {
return this._proxy.$updateNotebookCellMetadata(this.viewType, this.documentUri, this.handle, this._metadata);
}
getContent(): string {
if (this._textDocument && this._initalVersion !== this._textDocument?.version) {
return this._textDocument.getText();
} else {
return this.originalSource.join('\n');
}
}
attachTextDocument(document: vscode.TextDocument) {
this._textDocument = document;
this._initalVersion = this._textDocument.version;
}
detachTextDocument() {
if (this._textDocument && this._textDocument.version !== this._initalVersion) {
this.originalSource = this._textDocument.getText().split(/\r|\n|\r\n/g);
}
this._textDocument = undefined;
this._initalVersion = -1;
}
}
export class ExtHostNotebookDocument extends Disposable implements vscode.NotebookDocument {
private static _handlePool: number = 0;
readonly handle = ExtHostNotebookDocument._handlePool++;
private _cells: ExtHostCell[] = [];
private _cellDisposableMapping = new Map<number, DisposableStore>();
get cells() {
return this._cells;
}
private _languages: string[] = [];
get languages() {
return this._languages = [];
}
set languages(newLanguages: string[]) {
this._languages = newLanguages;
this._proxy.$updateNotebookLanguages(this.viewType, this.uri, this._languages);
}
private _metadata: vscode.NotebookDocumentMetadata | undefined = notebookDocumentMetadataDefaults;
get metadata() {
return this._metadata;
}
set metadata(newMetadata: vscode.NotebookDocumentMetadata | undefined) {
this._metadata = newMetadata || notebookDocumentMetadataDefaults;
this._proxy.$updateNotebookMetadata(this.viewType, this.uri, this._metadata);
}
private _displayOrder: string[] = [];
get displayOrder() {
return this._displayOrder;
}
set displayOrder(newOrder: string[]) {
this._displayOrder = newOrder;
}
private _versionId = 0;
get versionId() {
return this._versionId;
}
constructor(
private readonly _proxy: MainThreadNotebookShape,
private _documentsAndEditors: ExtHostDocumentsAndEditors,
public viewType: string,
public uri: URI,
public renderingHandler: ExtHostNotebookOutputRenderingHandler
) {
super();
}
dispose() {
super.dispose();
this._cellDisposableMapping.forEach(cell => cell.dispose());
}
get fileName() { return this.uri.fsPath; }
get isDirty() { return false; }
accpetModelChanged(event: NotebookCellsChangedEvent) {
this.$spliceNotebookCells(event.changes);
this._versionId = event.versionId;
}
private $spliceNotebookCells(splices: NotebookCellsSplice2[]): void {
if (!splices.length) {
return;
}
splices.reverse().forEach(splice => {
let cellDtos = splice[2];
let newCells = cellDtos.map(cell => {
const extCell = new ExtHostCell(this.viewType, this.uri, cell.handle, URI.revive(cell.uri), cell.source.join('\n'), cell.cellKind, cell.language, cell.outputs, cell.metadata, this._proxy);
const document = this._documentsAndEditors.getDocument(URI.revive(cell.uri));
if (document) {
extCell.attachTextDocument(document.document);
}
if (!this._cellDisposableMapping.has(extCell.handle)) {
this._cellDisposableMapping.set(extCell.handle, new DisposableStore());
}
let store = this._cellDisposableMapping.get(extCell.handle)!;
store.add(extCell.onDidChangeOutputs((diffs) => {
this.eventuallyUpdateCellOutputs(extCell, diffs);
}));
return extCell;
});
for (let j = splice[0]; j < splice[0] + splice[1]; j++) {
this._cellDisposableMapping.get(this.cells[j].handle)?.dispose();
this._cellDisposableMapping.delete(this.cells[j].handle);
}
this.cells.splice(splice[0], splice[1], ...newCells);
});
}
eventuallyUpdateCellOutputs(cell: ExtHostCell, diffs: ISplice<vscode.CellOutput>[]) {
let renderers = new Set<number>();
let outputDtos: NotebookCellOutputsSplice[] = diffs.map(diff => {
let outputs = diff.toInsert;
let transformedOutputs = outputs.map(output => {
if (output.outputKind === CellOutputKind.Rich) {
const ret = this.transformMimeTypes(output);
if (ret.orderedMimeTypes[ret.pickedMimeTypeIndex].isResolved) {
renderers.add(ret.orderedMimeTypes[ret.pickedMimeTypeIndex].rendererId!);
}
return ret;
} else {
return output as IStreamOutput | IErrorOutput;
}
});
return [diff.start, diff.deleteCount, transformedOutputs];
});
this._proxy.$spliceNotebookCellOutputs(this.viewType, this.uri, cell.handle, outputDtos, Array.from(renderers));
}
transformMimeTypes(output: vscode.CellDisplayOutput): ITransformedDisplayOutputDto {
let mimeTypes = Object.keys(output.data);
// TODO@rebornix, the document display order might be assigned a bit later. We need to postpone sending the outputs to the core side.
let coreDisplayOrder = this.renderingHandler.outputDisplayOrder;
const sorted = sortMimeTypes(mimeTypes, coreDisplayOrder?.userOrder || [], this._displayOrder, coreDisplayOrder?.defaultOrder || []);
let orderMimeTypes: IOrderedMimeType[] = [];
sorted.forEach(mimeType => {
let handlers = this.renderingHandler.findBestMatchedRenderer(mimeType);
if (handlers.length) {
let renderedOutput = handlers[0].render(this, output, mimeType);
orderMimeTypes.push({
mimeType: mimeType,
isResolved: true,
rendererId: handlers[0].handle,
output: renderedOutput
});
for (let i = 1; i < handlers.length; i++) {
orderMimeTypes.push({
mimeType: mimeType,
isResolved: false,
rendererId: handlers[i].handle
});
}
if (mimeTypeSupportedByCore(mimeType)) {
orderMimeTypes.push({
mimeType: mimeType,
isResolved: false,
rendererId: -1
});
}
} else {
orderMimeTypes.push({
mimeType: mimeType,
isResolved: false
});
}
});
return {
outputKind: output.outputKind,
data: output.data,
orderedMimeTypes: orderMimeTypes,
pickedMimeTypeIndex: 0
};
}
getCell(cellHandle: number) {
return this.cells.find(cell => cell.handle === cellHandle);
}
attachCellTextDocument(textDocument: vscode.TextDocument) {
let cell = this.cells.find(cell => cell.uri.toString() === textDocument.uri.toString());
if (cell) {
cell.attachTextDocument(textDocument);
}
}
detachCellTextDocument(textDocument: vscode.TextDocument) {
let cell = this.cells.find(cell => cell.uri.toString() === textDocument.uri.toString());
if (cell) {
cell.detachTextDocument();
}
}
}
export class NotebookEditorCellEdit {
private _finalized: boolean = false;
private readonly _documentVersionId: number;
private _collectedEdits: ICellEditOperation[] = [];
private _renderers = new Set<number>();
constructor(
readonly editor: ExtHostNotebookEditor
) {
this._documentVersionId = editor.document.versionId;
}
finalize(): INotebookEditData {
this._finalized = true;
return {
documentVersionId: this._documentVersionId,
edits: this._collectedEdits,
renderers: Array.from(this._renderers)
};
}
private _throwIfFinalized() {
if (this._finalized) {
throw new Error('Edit is only valid while callback runs');
}
}
insert(index: number, content: string, language: string, type: CellKind, outputs: vscode.CellOutput[], metadata: vscode.NotebookCellMetadata | undefined): void {
this._throwIfFinalized();
let cell = {
source: [content],
language,
cellKind: type,
outputs: (outputs as any[]), // TODO@rebornix
metadata
};
const transformedOutputs = outputs.map(output => {
if (output.outputKind === CellOutputKind.Rich) {
const ret = this.editor.document.transformMimeTypes(output);
if (ret.orderedMimeTypes[ret.pickedMimeTypeIndex].isResolved) {
this._renderers.add(ret.orderedMimeTypes[ret.pickedMimeTypeIndex].rendererId!);
}
return ret;
} else {
return output as IStreamOutput | IErrorOutput;
}
});
cell.outputs = transformedOutputs;
this._collectedEdits.push({
editType: CellEditType.Insert,
index,
cells: [cell]
});
}
delete(index: number): void {
this._throwIfFinalized();
this._collectedEdits.push({
editType: CellEditType.Delete,
index
});
}
}
export class ExtHostNotebookEditor extends Disposable implements vscode.NotebookEditor {
private _viewColumn: vscode.ViewColumn | undefined;
onDidReceiveMessage: vscode.Event<any> = this._onDidReceiveMessage.event;
constructor(
private readonly viewType: string,
readonly id: string,
public uri: URI,
private _proxy: MainThreadNotebookShape,
private _onDidReceiveMessage: Emitter<any>,
public document: ExtHostNotebookDocument,
private _documentsAndEditors: ExtHostDocumentsAndEditors
) {
super();
this._register(this._documentsAndEditors.onDidAddDocuments(documents => {
for (const { document: textDocument } of documents) {
let data = CellUri.parse(textDocument.uri);
if (data) {
if (this.document.uri.toString() === data.notebook.toString()) {
document.attachCellTextDocument(textDocument);
}
}
}
}));
this._register(this._documentsAndEditors.onDidRemoveDocuments(documents => {
for (const { document: textDocument } of documents) {
let data = CellUri.parse(textDocument.uri);
if (data) {
if (this.document.uri.toString() === data.notebook.toString()) {
document.detachCellTextDocument(textDocument);
}
}
}
}));
}
edit(callback: (editBuilder: NotebookEditorCellEdit) => void): Thenable<boolean> {
const edit = new NotebookEditorCellEdit(this);
callback(edit);
return this._applyEdit(edit);
}
private _applyEdit(editBuilder: NotebookEditorCellEdit): Promise<boolean> {
const editData = editBuilder.finalize();
// return when there is nothing to do
if (editData.edits.length === 0) {
return Promise.resolve(true);
}
let compressedEdits: ICellEditOperation[] = [];
let compressedEditsIndex = -1;
for (let i = 0; i < editData.edits.length; i++) {
if (compressedEditsIndex < 0) {
compressedEdits.push(editData.edits[i]);
compressedEditsIndex++;
continue;
}
let prevIndex = compressedEditsIndex;
let prev = compressedEdits[prevIndex];
if (prev.editType === CellEditType.Insert && editData.edits[i].editType === CellEditType.Insert) {
if (prev.index + prev.cells.length === editData.edits[i].index) {
prev.cells.push(...(editData.edits[i] as ICellInsertEdit).cells);
continue;
}
}
compressedEdits.push(editData.edits[i]);
compressedEditsIndex++;
}
return this._proxy.$tryApplyEdits(this.viewType, this.uri, editData.documentVersionId, compressedEdits, editData.renderers);
}
get viewColumn(): vscode.ViewColumn | undefined {
return this._viewColumn;
}
set viewColumn(value) {
throw readonly('viewColumn');
}
async postMessage(message: any): Promise<boolean> {
return this._proxy.$postMessage(this.document.handle, message);
}
}
export class ExtHostNotebookOutputRenderer {
private static _handlePool: number = 0;
readonly handle = ExtHostNotebookOutputRenderer._handlePool++;
constructor(
public type: string,
public filter: vscode.NotebookOutputSelector,
public renderer: vscode.NotebookOutputRenderer
) {
}
matches(mimeType: string): boolean {
if (this.filter.subTypes) {
if (this.filter.subTypes.indexOf(mimeType) >= 0) {
return true;
}
}
return false;
}
render(document: ExtHostNotebookDocument, output: vscode.CellOutput, mimeType: string): string {
let html = this.renderer.render(document, output, mimeType);
return html;
}
}
export interface ExtHostNotebookOutputRenderingHandler {
outputDisplayOrder: INotebookDisplayOrder | undefined;
findBestMatchedRenderer(mimeType: string): ExtHostNotebookOutputRenderer[];
}
export class ExtHostNotebookController implements ExtHostNotebookShape, ExtHostNotebookOutputRenderingHandler {
private static _handlePool: number = 0;
private readonly _proxy: MainThreadNotebookShape;
private readonly _notebookProviders = new Map<string, { readonly provider: vscode.NotebookProvider, readonly extension: IExtensionDescription; }>();
private readonly _documents = new Map<string, ExtHostNotebookDocument>();
private readonly _editors = new Map<string, { editor: ExtHostNotebookEditor, onDidReceiveMessage: Emitter<any> }>();
private readonly _notebookOutputRenderers = new Map<number, ExtHostNotebookOutputRenderer>();
private _outputDisplayOrder: INotebookDisplayOrder | undefined;
get outputDisplayOrder(): INotebookDisplayOrder | undefined {
return this._outputDisplayOrder;
}
private _activeNotebookDocument: ExtHostNotebookDocument | undefined;
get activeNotebookDocument() {
return this._activeNotebookDocument;
}
constructor(mainContext: IMainContext, commands: ExtHostCommands, private _documentsAndEditors: ExtHostDocumentsAndEditors) {
this._proxy = mainContext.getProxy(MainContext.MainThreadNotebook);
commands.registerArgumentProcessor({
processArgument: arg => {
if (arg && arg.$mid === 12) {
const documentHandle = arg.notebookEditor?.notebookHandle;
const cellHandle = arg.cell.handle;
for (let value of this._editors) {
if (value[1].editor.document.handle === documentHandle) {
const cell = value[1].editor.document.getCell(cellHandle);
if (cell) {
return cell;
}
}
}
}
return arg;
}
});
}
registerNotebookOutputRenderer(
type: string,
extension: IExtensionDescription,
filter: vscode.NotebookOutputSelector,
renderer: vscode.NotebookOutputRenderer
): vscode.Disposable {
let extHostRenderer = new ExtHostNotebookOutputRenderer(type, filter, renderer);
this._notebookOutputRenderers.set(extHostRenderer.handle, extHostRenderer);
this._proxy.$registerNotebookRenderer({ id: extension.identifier, location: extension.extensionLocation }, type, filter, extHostRenderer.handle, renderer.preloads || []);
return new VSCodeDisposable(() => {
this._notebookOutputRenderers.delete(extHostRenderer.handle);
this._proxy.$unregisterNotebookRenderer(extHostRenderer.handle);
});
}
findBestMatchedRenderer(mimeType: string): ExtHostNotebookOutputRenderer[] {
let matches: ExtHostNotebookOutputRenderer[] = [];
for (let renderer of this._notebookOutputRenderers) {
if (renderer[1].matches(mimeType)) {
matches.push(renderer[1]);
}
}
return matches;
}
registerNotebookProvider(
extension: IExtensionDescription,
viewType: string,
provider: vscode.NotebookProvider,
): vscode.Disposable {
if (this._notebookProviders.has(viewType)) {
throw new Error(`Notebook provider for '${viewType}' already registered`);
}
this._notebookProviders.set(viewType, { extension, provider });
this._proxy.$registerNotebookProvider({ id: extension.identifier, location: extension.extensionLocation }, viewType);
return new VSCodeDisposable(() => {
this._notebookProviders.delete(viewType);
this._proxy.$unregisterNotebookProvider(viewType);
});
}
async $resolveNotebook(viewType: string, uri: UriComponents): Promise<number | undefined> {
let provider = this._notebookProviders.get(viewType);
if (provider) {
if (!this._documents.has(URI.revive(uri).toString())) {
let document = new ExtHostNotebookDocument(this._proxy, this._documentsAndEditors, viewType, URI.revive(uri), this);
await this._proxy.$createNotebookDocument(
document.handle,
viewType,
uri
);
this._documents.set(URI.revive(uri).toString(), document);
}
const onDidReceiveMessage = new Emitter<any>();
let editor = new ExtHostNotebookEditor(
viewType,
`${ExtHostNotebookController._handlePool++}`,
URI.revive(uri),
this._proxy,
onDidReceiveMessage,
this._documents.get(URI.revive(uri).toString())!,
this._documentsAndEditors
);
this._editors.set(URI.revive(uri).toString(), { editor, onDidReceiveMessage });
await provider.provider.resolveNotebook(editor);
// await editor.document.$updateCells();
return editor.document.handle;
}
return Promise.resolve(undefined);
}
async $executeNotebook(viewType: string, uri: UriComponents, cellHandle: number | undefined): Promise<void> {
let provider = this._notebookProviders.get(viewType);
if (!provider) {
return;
}
let document = this._documents.get(URI.revive(uri).toString());
if (!document) {
return;
}
let cell = cellHandle !== undefined ? document.getCell(cellHandle) : undefined;
return provider.provider.executeCell(document!, cell);
}
async $saveNotebook(viewType: string, uri: UriComponents): Promise<boolean> {
let provider = this._notebookProviders.get(viewType);
let document = this._documents.get(URI.revive(uri).toString());
if (provider && document) {
return await provider.provider.save(document);
}
return false;
}
async $updateActiveEditor(viewType: string, uri: UriComponents): Promise<void> {
this._activeNotebookDocument = this._documents.get(URI.revive(uri).toString());
}
async $destoryNotebookDocument(viewType: string, uri: UriComponents): Promise<boolean> {
let provider = this._notebookProviders.get(viewType);
if (!provider) {
return false;
}
let document = this._documents.get(URI.revive(uri).toString());
if (document) {
document.dispose();
this._documents.delete(URI.revive(uri).toString());
}
let editor = this._editors.get(URI.revive(uri).toString());
if (editor) {
editor.editor.dispose();
editor.onDidReceiveMessage.dispose();
this._editors.delete(URI.revive(uri).toString());
}
return true;
}
$acceptDisplayOrder(displayOrder: INotebookDisplayOrder): void {
this._outputDisplayOrder = displayOrder;
}
$onDidReceiveMessage(uri: UriComponents, message: any): void {
let editor = this._editors.get(URI.revive(uri).toString());
if (editor) {
editor.onDidReceiveMessage.fire(message);
}
}
$acceptModelChanged(uriComponents: UriComponents, event: NotebookCellsChangedEvent): void {
let editor = this._editors.get(URI.revive(uriComponents).toString());
if (editor) {
editor.editor.document.accpetModelChanged(event);
}
}
}
| src/vs/workbench/api/common/extHostNotebook.ts | 1 | https://github.com/microsoft/vscode/commit/c0efffc91f0c4cd10e70f30229f19da96a50f960 | [
0.9923253059387207,
0.019244130700826645,
0.000160606752615422,
0.00019109064305666834,
0.11802858114242554
] |
{
"id": 0,
"code_window": [
"import { CellKind, CellOutputKind, ExtHostNotebookShape, IMainContext, MainContext, MainThreadNotebookShape, NotebookCellOutputsSplice } from 'vs/workbench/api/common/extHost.protocol';\n",
"import { ExtHostCommands } from 'vs/workbench/api/common/extHostCommands';\n",
"import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors';\n",
"import { CellEditType, CellUri, diff, ICellEditOperation, ICellInsertEdit, IErrorOutput, INotebookDisplayOrder, INotebookEditData, IOrderedMimeType, IStreamOutput, ITransformedDisplayOutputDto, mimeTypeSupportedByCore, NotebookCellsChangedEvent, NotebookCellsSplice2, sortMimeTypes } from 'vs/workbench/contrib/notebook/common/notebookCommon';\n",
"import { Disposable as VSCodeDisposable } from './extHostTypes';\n",
"\n",
"interface IObservable<T> {\n",
"\tproxy: T;\n",
"\tonDidChange: Event<void>;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { CellEditType, CellUri, diff, ICellEditOperation, ICellInsertEdit, IErrorOutput, INotebookDisplayOrder, INotebookEditData, IOrderedMimeType, IStreamOutput, ITransformedDisplayOutputDto, mimeTypeSupportedByCore, NotebookCellsChangedEvent, NotebookCellsSplice2, sortMimeTypes, ICellDeleteEdit } from 'vs/workbench/contrib/notebook/common/notebookCommon';\n"
],
"file_path": "src/vs/workbench/api/common/extHostNotebook.ts",
"type": "replace",
"edit_start_line_idx": 15
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { mkdir, open, close, read, write, fdatasync, Dirent, Stats } from 'fs';
import { promisify } from 'util';
import { IDisposable, Disposable, toDisposable, dispose, combinedDisposable } from 'vs/base/common/lifecycle';
import { FileSystemProviderCapabilities, IFileChange, IWatchOptions, IStat, FileType, FileDeleteOptions, FileOverwriteOptions, FileWriteOptions, FileOpenOptions, FileSystemProviderErrorCode, createFileSystemProviderError, FileSystemProviderError, IFileSystemProviderWithFileReadWriteCapability, IFileSystemProviderWithFileReadStreamCapability, IFileSystemProviderWithOpenReadWriteCloseCapability, FileReadStreamOptions, IFileSystemProviderWithFileFolderCopyCapability } from 'vs/platform/files/common/files';
import { URI } from 'vs/base/common/uri';
import { Event, Emitter } from 'vs/base/common/event';
import { isLinux, isWindows } from 'vs/base/common/platform';
import { statLink, unlink, move, copy, readFile, truncate, rimraf, RimRafMode, exists, readdirWithFileTypes } from 'vs/base/node/pfs';
import { normalize, basename, dirname } from 'vs/base/common/path';
import { joinPath } from 'vs/base/common/resources';
import { isEqual } from 'vs/base/common/extpath';
import { retry, ThrottledDelayer } from 'vs/base/common/async';
import { ILogService, LogLevel } from 'vs/platform/log/common/log';
import { localize } from 'vs/nls';
import { IDiskFileChange, toFileChanges, ILogMessage } from 'vs/platform/files/node/watcher/watcher';
import { FileWatcher as UnixWatcherService } from 'vs/platform/files/node/watcher/unix/watcherService';
import { FileWatcher as WindowsWatcherService } from 'vs/platform/files/node/watcher/win32/watcherService';
import { FileWatcher as NsfwWatcherService } from 'vs/platform/files/node/watcher/nsfw/watcherService';
import { FileWatcher as NodeJSWatcherService } from 'vs/platform/files/node/watcher/nodejs/watcherService';
import { VSBuffer } from 'vs/base/common/buffer';
import { CancellationToken } from 'vs/base/common/cancellation';
import { ReadableStreamEvents, transform } from 'vs/base/common/stream';
import { createReadStream } from 'vs/platform/files/common/io';
export interface IWatcherOptions {
pollingInterval?: number;
usePolling: boolean;
}
export interface IDiskFileSystemProviderOptions {
bufferSize?: number;
watcher?: IWatcherOptions;
}
export class DiskFileSystemProvider extends Disposable implements
IFileSystemProviderWithFileReadWriteCapability,
IFileSystemProviderWithOpenReadWriteCloseCapability,
IFileSystemProviderWithFileReadStreamCapability,
IFileSystemProviderWithFileFolderCopyCapability {
private readonly BUFFER_SIZE = this.options?.bufferSize || 64 * 1024;
constructor(private logService: ILogService, private options?: IDiskFileSystemProviderOptions) {
super();
}
//#region File Capabilities
onDidChangeCapabilities: Event<void> = Event.None;
protected _capabilities: FileSystemProviderCapabilities | undefined;
get capabilities(): FileSystemProviderCapabilities {
if (!this._capabilities) {
this._capabilities =
FileSystemProviderCapabilities.FileReadWrite |
FileSystemProviderCapabilities.FileOpenReadWriteClose |
FileSystemProviderCapabilities.FileReadStream |
FileSystemProviderCapabilities.FileFolderCopy;
if (isLinux) {
this._capabilities |= FileSystemProviderCapabilities.PathCaseSensitive;
}
}
return this._capabilities;
}
//#endregion
//#region File Metadata Resolving
async stat(resource: URI): Promise<IStat> {
try {
const { stat, symbolicLink } = await statLink(this.toFilePath(resource)); // cannot use fs.stat() here to support links properly
return {
type: this.toType(stat, symbolicLink),
ctime: stat.birthtime.getTime(), // intentionally not using ctime here, we want the creation time
mtime: stat.mtime.getTime(),
size: stat.size
};
} catch (error) {
throw this.toFileSystemProviderError(error);
}
}
async readdir(resource: URI): Promise<[string, FileType][]> {
try {
const children = await readdirWithFileTypes(this.toFilePath(resource));
const result: [string, FileType][] = [];
await Promise.all(children.map(async child => {
try {
let type: FileType;
if (child.isSymbolicLink()) {
type = (await this.stat(joinPath(resource, child.name))).type; // always resolve target the link points to if any
} else {
type = this.toType(child);
}
result.push([child.name, type]);
} catch (error) {
this.logService.trace(error); // ignore errors for individual entries that can arise from permission denied
}
}));
return result;
} catch (error) {
throw this.toFileSystemProviderError(error);
}
}
private toType(entry: Stats | Dirent, symbolicLink?: { dangling: boolean }): FileType {
// Signal file type by checking for file / directory, except:
// - symbolic links pointing to non-existing files are FileType.Unknown
// - files that are neither file nor directory are FileType.Unknown
let type: FileType;
if (symbolicLink?.dangling) {
type = FileType.Unknown;
} else if (entry.isFile()) {
type = FileType.File;
} else if (entry.isDirectory()) {
type = FileType.Directory;
} else {
type = FileType.Unknown;
}
// Always signal symbolic link as file type additionally
if (symbolicLink) {
type |= FileType.SymbolicLink;
}
return type;
}
//#endregion
//#region File Reading/Writing
async readFile(resource: URI): Promise<Uint8Array> {
try {
const filePath = this.toFilePath(resource);
return await readFile(filePath);
} catch (error) {
throw this.toFileSystemProviderError(error);
}
}
readFileStream(resource: URI, opts: FileReadStreamOptions, token?: CancellationToken): ReadableStreamEvents<Uint8Array> {
const fileStream = createReadStream(this, resource, {
...opts,
bufferSize: this.BUFFER_SIZE
}, token);
return transform(fileStream, { data: data => data.buffer }, data => VSBuffer.concat(data.map(data => VSBuffer.wrap(data))).buffer);
}
async writeFile(resource: URI, content: Uint8Array, opts: FileWriteOptions): Promise<void> {
let handle: number | undefined = undefined;
try {
const filePath = this.toFilePath(resource);
// Validate target unless { create: true, overwrite: true }
if (!opts.create || !opts.overwrite) {
const fileExists = await exists(filePath);
if (fileExists) {
if (!opts.overwrite) {
throw createFileSystemProviderError(localize('fileExists', "File already exists"), FileSystemProviderErrorCode.FileExists);
}
} else {
if (!opts.create) {
throw createFileSystemProviderError(localize('fileNotExists', "File does not exist"), FileSystemProviderErrorCode.FileNotFound);
}
}
}
// Open
handle = await this.open(resource, { create: true });
// Write content at once
await this.write(handle, 0, content, 0, content.byteLength);
} catch (error) {
throw this.toFileSystemProviderError(error);
} finally {
if (typeof handle === 'number') {
await this.close(handle);
}
}
}
private mapHandleToPos: Map<number, number> = new Map();
private writeHandles: Set<number> = new Set();
private canFlush: boolean = true;
async open(resource: URI, opts: FileOpenOptions): Promise<number> {
try {
const filePath = this.toFilePath(resource);
let flags: string | undefined = undefined;
if (opts.create) {
if (isWindows && await exists(filePath)) {
try {
// On Windows and if the file exists, we use a different strategy of saving the file
// by first truncating the file and then writing with r+ flag. This helps to save hidden files on Windows
// (see https://github.com/Microsoft/vscode/issues/931) and prevent removing alternate data streams
// (see https://github.com/Microsoft/vscode/issues/6363)
await truncate(filePath, 0);
// After a successful truncate() the flag can be set to 'r+' which will not truncate.
flags = 'r+';
} catch (error) {
this.logService.trace(error);
}
}
// we take opts.create as a hint that the file is opened for writing
// as such we use 'w' to truncate an existing or create the
// file otherwise. we do not allow reading.
if (!flags) {
flags = 'w';
}
} else {
// otherwise we assume the file is opened for reading
// as such we use 'r' to neither truncate, nor create
// the file.
flags = 'r';
}
const handle = await promisify(open)(filePath, flags);
// remember this handle to track file position of the handle
// we init the position to 0 since the file descriptor was
// just created and the position was not moved so far (see
// also http://man7.org/linux/man-pages/man2/open.2.html -
// "The file offset is set to the beginning of the file.")
this.mapHandleToPos.set(handle, 0);
// remember that this handle was used for writing
if (opts.create) {
this.writeHandles.add(handle);
}
return handle;
} catch (error) {
throw this.toFileSystemProviderError(error);
}
}
async close(fd: number): Promise<void> {
try {
// remove this handle from map of positions
this.mapHandleToPos.delete(fd);
// if a handle is closed that was used for writing, ensure
// to flush the contents to disk if possible.
if (this.writeHandles.delete(fd) && this.canFlush) {
try {
await promisify(fdatasync)(fd);
} catch (error) {
// In some exotic setups it is well possible that node fails to sync
// In that case we disable flushing and log the error to our logger
this.canFlush = false;
this.logService.error(error);
}
}
return await promisify(close)(fd);
} catch (error) {
throw this.toFileSystemProviderError(error);
}
}
async read(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number> {
const normalizedPos = this.normalizePos(fd, pos);
let bytesRead: number | null = null;
try {
const result = await promisify(read)(fd, data, offset, length, normalizedPos);
if (typeof result === 'number') {
bytesRead = result; // node.d.ts fail
} else {
bytesRead = result.bytesRead;
}
return bytesRead;
} catch (error) {
throw this.toFileSystemProviderError(error);
} finally {
this.updatePos(fd, normalizedPos, bytesRead);
}
}
private normalizePos(fd: number, pos: number): number | null {
// when calling fs.read/write we try to avoid passing in the "pos" argument and
// rather prefer to pass in "null" because this avoids an extra seek(pos)
// call that in some cases can even fail (e.g. when opening a file over FTP -
// see https://github.com/microsoft/vscode/issues/73884).
//
// as such, we compare the passed in position argument with our last known
// position for the file descriptor and use "null" if they match.
if (pos === this.mapHandleToPos.get(fd)) {
return null;
}
return pos;
}
private updatePos(fd: number, pos: number | null, bytesLength: number | null): void {
const lastKnownPos = this.mapHandleToPos.get(fd);
if (typeof lastKnownPos === 'number') {
// pos !== null signals that previously a position was used that is
// not null. node.js documentation explains, that in this case
// the internal file pointer is not moving and as such we do not move
// our position pointer.
//
// Docs: "If position is null, data will be read from the current file position,
// and the file position will be updated. If position is an integer, the file position
// will remain unchanged."
if (typeof pos === 'number') {
// do not modify the position
}
// bytesLength = number is a signal that the read/write operation was
// successful and as such we need to advance the position in the Map
//
// Docs (http://man7.org/linux/man-pages/man2/read.2.html):
// "On files that support seeking, the read operation commences at the
// file offset, and the file offset is incremented by the number of
// bytes read."
//
// Docs (http://man7.org/linux/man-pages/man2/write.2.html):
// "For a seekable file (i.e., one to which lseek(2) may be applied, for
// example, a regular file) writing takes place at the file offset, and
// the file offset is incremented by the number of bytes actually
// written."
else if (typeof bytesLength === 'number') {
this.mapHandleToPos.set(fd, lastKnownPos + bytesLength);
}
// bytesLength = null signals an error in the read/write operation
// and as such we drop the handle from the Map because the position
// is unspecificed at this point.
else {
this.mapHandleToPos.delete(fd);
}
}
}
async write(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number> {
// we know at this point that the file to write to is truncated and thus empty
// if the write now fails, the file remains empty. as such we really try hard
// to ensure the write succeeds by retrying up to three times.
return retry(() => this.doWrite(fd, pos, data, offset, length), 100 /* ms delay */, 3 /* retries */);
}
private async doWrite(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number> {
const normalizedPos = this.normalizePos(fd, pos);
let bytesWritten: number | null = null;
try {
const result = await promisify(write)(fd, data, offset, length, normalizedPos);
if (typeof result === 'number') {
bytesWritten = result; // node.d.ts fail
} else {
bytesWritten = result.bytesWritten;
}
return bytesWritten;
} catch (error) {
throw this.toFileSystemProviderError(error);
} finally {
this.updatePos(fd, normalizedPos, bytesWritten);
}
}
//#endregion
//#region Move/Copy/Delete/Create Folder
async mkdir(resource: URI): Promise<void> {
try {
await promisify(mkdir)(this.toFilePath(resource));
} catch (error) {
throw this.toFileSystemProviderError(error);
}
}
async delete(resource: URI, opts: FileDeleteOptions): Promise<void> {
try {
const filePath = this.toFilePath(resource);
await this.doDelete(filePath, opts);
} catch (error) {
throw this.toFileSystemProviderError(error);
}
}
protected async doDelete(filePath: string, opts: FileDeleteOptions): Promise<void> {
if (opts.recursive) {
await rimraf(filePath, RimRafMode.MOVE);
} else {
await unlink(filePath);
}
}
async rename(from: URI, to: URI, opts: FileOverwriteOptions): Promise<void> {
const fromFilePath = this.toFilePath(from);
const toFilePath = this.toFilePath(to);
if (fromFilePath === toFilePath) {
return; // simulate node.js behaviour here and do a no-op if paths match
}
try {
// Ensure target does not exist
await this.validateTargetDeleted(from, to, 'move', opts.overwrite);
// Move
await move(fromFilePath, toFilePath);
} catch (error) {
// rewrite some typical errors that can happen especially around symlinks
// to something the user can better understand
if (error.code === 'EINVAL' || error.code === 'EBUSY' || error.code === 'ENAMETOOLONG') {
error = new Error(localize('moveError', "Unable to move '{0}' into '{1}' ({2}).", basename(fromFilePath), basename(dirname(toFilePath)), error.toString()));
}
throw this.toFileSystemProviderError(error);
}
}
async copy(from: URI, to: URI, opts: FileOverwriteOptions): Promise<void> {
const fromFilePath = this.toFilePath(from);
const toFilePath = this.toFilePath(to);
if (fromFilePath === toFilePath) {
return; // simulate node.js behaviour here and do a no-op if paths match
}
try {
// Ensure target does not exist
await this.validateTargetDeleted(from, to, 'copy', opts.overwrite);
// Copy
await copy(fromFilePath, toFilePath);
} catch (error) {
// rewrite some typical errors that can happen especially around symlinks
// to something the user can better understand
if (error.code === 'EINVAL' || error.code === 'EBUSY' || error.code === 'ENAMETOOLONG') {
error = new Error(localize('copyError', "Unable to copy '{0}' into '{1}' ({2}).", basename(fromFilePath), basename(dirname(toFilePath)), error.toString()));
}
throw this.toFileSystemProviderError(error);
}
}
private async validateTargetDeleted(from: URI, to: URI, mode: 'move' | 'copy', overwrite?: boolean): Promise<void> {
const isPathCaseSensitive = !!(this.capabilities & FileSystemProviderCapabilities.PathCaseSensitive);
const fromFilePath = this.toFilePath(from);
const toFilePath = this.toFilePath(to);
let isSameResourceWithDifferentPathCase = false;
if (!isPathCaseSensitive) {
isSameResourceWithDifferentPathCase = isEqual(fromFilePath, toFilePath, true /* ignore case */);
}
if (isSameResourceWithDifferentPathCase && mode === 'copy') {
throw createFileSystemProviderError(localize('fileCopyErrorPathCase', "'File cannot be copied to same path with different path case"), FileSystemProviderErrorCode.FileExists);
}
// handle existing target (unless this is a case change)
if (!isSameResourceWithDifferentPathCase && await exists(toFilePath)) {
if (!overwrite) {
throw createFileSystemProviderError(localize('fileCopyErrorExists', "File at target already exists"), FileSystemProviderErrorCode.FileExists);
}
// Delete target
await this.delete(to, { recursive: true, useTrash: false });
}
}
//#endregion
//#region File Watching
private _onDidWatchErrorOccur = this._register(new Emitter<string>());
readonly onDidErrorOccur = this._onDidWatchErrorOccur.event;
private _onDidChangeFile = this._register(new Emitter<readonly IFileChange[]>());
readonly onDidChangeFile = this._onDidChangeFile.event;
private recursiveWatcher: WindowsWatcherService | UnixWatcherService | NsfwWatcherService | undefined;
private recursiveFoldersToWatch: { path: string, excludes: string[] }[] = [];
private recursiveWatchRequestDelayer = this._register(new ThrottledDelayer<void>(0));
private recursiveWatcherLogLevelListener: IDisposable | undefined;
watch(resource: URI, opts: IWatchOptions): IDisposable {
if (opts.recursive) {
return this.watchRecursive(resource, opts.excludes);
}
return this.watchNonRecursive(resource); // TODO@ben ideally the same watcher can be used in both cases
}
private watchRecursive(resource: URI, excludes: string[]): IDisposable {
// Add to list of folders to watch recursively
const folderToWatch = { path: this.toFilePath(resource), excludes };
this.recursiveFoldersToWatch.push(folderToWatch);
// Trigger update
this.refreshRecursiveWatchers();
return toDisposable(() => {
// Remove from list of folders to watch recursively
this.recursiveFoldersToWatch.splice(this.recursiveFoldersToWatch.indexOf(folderToWatch), 1);
// Trigger update
this.refreshRecursiveWatchers();
});
}
private refreshRecursiveWatchers(): void {
// Buffer requests for recursive watching to decide on right watcher
// that supports potentially watching more than one folder at once
this.recursiveWatchRequestDelayer.trigger(() => {
this.doRefreshRecursiveWatchers();
return Promise.resolve();
});
}
private doRefreshRecursiveWatchers(): void {
// Reuse existing
if (this.recursiveWatcher instanceof NsfwWatcherService) {
this.recursiveWatcher.setFolders(this.recursiveFoldersToWatch);
}
// Create new
else {
// Dispose old
dispose(this.recursiveWatcher);
this.recursiveWatcher = undefined;
// Create new if we actually have folders to watch
if (this.recursiveFoldersToWatch.length > 0) {
let watcherImpl: {
new(
folders: { path: string, excludes: string[] }[],
onChange: (changes: IDiskFileChange[]) => void,
onLogMessage: (msg: ILogMessage) => void,
verboseLogging: boolean,
watcherOptions?: IWatcherOptions
): WindowsWatcherService | UnixWatcherService | NsfwWatcherService
};
let watcherOptions: IWatcherOptions | undefined = undefined;
// requires a polling watcher
if (this.options?.watcher?.usePolling) {
watcherImpl = UnixWatcherService;
watcherOptions = this.options?.watcher;
}
// Single Folder Watcher
else {
if (this.recursiveFoldersToWatch.length === 1) {
if (isWindows) {
watcherImpl = WindowsWatcherService;
} else {
watcherImpl = UnixWatcherService;
}
}
// Multi Folder Watcher
else {
watcherImpl = NsfwWatcherService;
}
}
// Create and start watching
this.recursiveWatcher = new watcherImpl(
this.recursiveFoldersToWatch,
event => this._onDidChangeFile.fire(toFileChanges(event)),
msg => {
if (msg.type === 'error') {
this._onDidWatchErrorOccur.fire(msg.message);
}
this.logService[msg.type](msg.message);
},
this.logService.getLevel() === LogLevel.Trace,
watcherOptions
);
if (!this.recursiveWatcherLogLevelListener) {
this.recursiveWatcherLogLevelListener = this.logService.onDidChangeLogLevel(() => {
if (this.recursiveWatcher) {
this.recursiveWatcher.setVerboseLogging(this.logService.getLevel() === LogLevel.Trace);
}
});
}
}
}
}
private watchNonRecursive(resource: URI): IDisposable {
const watcherService = new NodeJSWatcherService(
this.toFilePath(resource),
changes => this._onDidChangeFile.fire(toFileChanges(changes)),
msg => {
if (msg.type === 'error') {
this._onDidWatchErrorOccur.fire(msg.message);
}
this.logService[msg.type](msg.message);
},
this.logService.getLevel() === LogLevel.Trace
);
const logLevelListener = this.logService.onDidChangeLogLevel(() => {
watcherService.setVerboseLogging(this.logService.getLevel() === LogLevel.Trace);
});
return combinedDisposable(watcherService, logLevelListener);
}
//#endregion
//#region Helpers
protected toFilePath(resource: URI): string {
return normalize(resource.fsPath);
}
private toFileSystemProviderError(error: NodeJS.ErrnoException): FileSystemProviderError {
if (error instanceof FileSystemProviderError) {
return error; // avoid double conversion
}
let code: FileSystemProviderErrorCode;
switch (error.code) {
case 'ENOENT':
code = FileSystemProviderErrorCode.FileNotFound;
break;
case 'EISDIR':
code = FileSystemProviderErrorCode.FileIsADirectory;
break;
case 'EEXIST':
code = FileSystemProviderErrorCode.FileExists;
break;
case 'EPERM':
case 'EACCES':
code = FileSystemProviderErrorCode.NoPermissions;
break;
default:
code = FileSystemProviderErrorCode.Unknown;
}
return createFileSystemProviderError(error, code);
}
//#endregion
dispose(): void {
super.dispose();
dispose(this.recursiveWatcher);
this.recursiveWatcher = undefined;
dispose(this.recursiveWatcherLogLevelListener);
this.recursiveWatcherLogLevelListener = undefined;
}
}
| src/vs/platform/files/node/diskFileSystemProvider.ts | 0 | https://github.com/microsoft/vscode/commit/c0efffc91f0c4cd10e70f30229f19da96a50f960 | [
0.0013594790361821651,
0.000189442842383869,
0.00016175511700566858,
0.00017168675549328327,
0.00014142406871542335
] |
{
"id": 0,
"code_window": [
"import { CellKind, CellOutputKind, ExtHostNotebookShape, IMainContext, MainContext, MainThreadNotebookShape, NotebookCellOutputsSplice } from 'vs/workbench/api/common/extHost.protocol';\n",
"import { ExtHostCommands } from 'vs/workbench/api/common/extHostCommands';\n",
"import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors';\n",
"import { CellEditType, CellUri, diff, ICellEditOperation, ICellInsertEdit, IErrorOutput, INotebookDisplayOrder, INotebookEditData, IOrderedMimeType, IStreamOutput, ITransformedDisplayOutputDto, mimeTypeSupportedByCore, NotebookCellsChangedEvent, NotebookCellsSplice2, sortMimeTypes } from 'vs/workbench/contrib/notebook/common/notebookCommon';\n",
"import { Disposable as VSCodeDisposable } from './extHostTypes';\n",
"\n",
"interface IObservable<T> {\n",
"\tproxy: T;\n",
"\tonDidChange: Event<void>;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { CellEditType, CellUri, diff, ICellEditOperation, ICellInsertEdit, IErrorOutput, INotebookDisplayOrder, INotebookEditData, IOrderedMimeType, IStreamOutput, ITransformedDisplayOutputDto, mimeTypeSupportedByCore, NotebookCellsChangedEvent, NotebookCellsSplice2, sortMimeTypes, ICellDeleteEdit } from 'vs/workbench/contrib/notebook/common/notebookCommon';\n"
],
"file_path": "src/vs/workbench/api/common/extHostNotebook.ts",
"type": "replace",
"edit_start_line_idx": 15
} | package main
import (
"encoding/base64"
"fmt"
)
func main() {
dnsName := "test-vm-from-go"
storageAccount := "mystorageaccount"
c := make(chan int)
client, err := management.ClientFromPublishSettingsFile("path/to/downloaded.publishsettings", "")
if err != nil {
panic(err)
}
// create virtual machine
role := vmutils.NewVMConfiguration(dnsName, vmSize)
vmutils.ConfigureDeploymentFromPlatformImage(
&role,
vmImage,
fmt.Sprintf("http://%s.blob.core.windows.net/sdktest/%s.vhd", storageAccount, dnsName),
"")
} | extensions/go/test/colorize-fixtures/test.go | 0 | https://github.com/microsoft/vscode/commit/c0efffc91f0c4cd10e70f30229f19da96a50f960 | [
0.000172698637470603,
0.0001715220423648134,
0.00016962701920419931,
0.0001722404849715531,
0.0000013529780744647724
] |
{
"id": 0,
"code_window": [
"import { CellKind, CellOutputKind, ExtHostNotebookShape, IMainContext, MainContext, MainThreadNotebookShape, NotebookCellOutputsSplice } from 'vs/workbench/api/common/extHost.protocol';\n",
"import { ExtHostCommands } from 'vs/workbench/api/common/extHostCommands';\n",
"import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors';\n",
"import { CellEditType, CellUri, diff, ICellEditOperation, ICellInsertEdit, IErrorOutput, INotebookDisplayOrder, INotebookEditData, IOrderedMimeType, IStreamOutput, ITransformedDisplayOutputDto, mimeTypeSupportedByCore, NotebookCellsChangedEvent, NotebookCellsSplice2, sortMimeTypes } from 'vs/workbench/contrib/notebook/common/notebookCommon';\n",
"import { Disposable as VSCodeDisposable } from './extHostTypes';\n",
"\n",
"interface IObservable<T> {\n",
"\tproxy: T;\n",
"\tonDidChange: Event<void>;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { CellEditType, CellUri, diff, ICellEditOperation, ICellInsertEdit, IErrorOutput, INotebookDisplayOrder, INotebookEditData, IOrderedMimeType, IStreamOutput, ITransformedDisplayOutputDto, mimeTypeSupportedByCore, NotebookCellsChangedEvent, NotebookCellsSplice2, sortMimeTypes, ICellDeleteEdit } from 'vs/workbench/contrib/notebook/common/notebookCommon';\n"
],
"file_path": "src/vs/workbench/api/common/extHostNotebook.ts",
"type": "replace",
"edit_start_line_idx": 15
} | {
"information_for_contributors": [
"This file has been converted from https://github.com/daaain/Handlebars/blob/master/grammars/Handlebars.json",
"If you want to provide a fix or improvement, please create a pull request against the original repository.",
"Once accepted there, we are happy to receive an update request."
],
"version": "https://github.com/daaain/Handlebars/commit/85a153a6f759df4e8da7533e1b3651f007867c51",
"name": "Handlebars",
"scopeName": "text.html.handlebars",
"patterns": [
{
"include": "#yfm"
},
{
"include": "#extends"
},
{
"include": "#block_comments"
},
{
"include": "#comments"
},
{
"include": "#block_helper"
},
{
"include": "#end_block"
},
{
"include": "#else_token"
},
{
"include": "#partial_and_var"
},
{
"include": "#inline_script"
},
{
"include": "#html_tags"
},
{
"include": "text.html.basic"
}
],
"repository": {
"html_tags": {
"patterns": [
{
"begin": "(<)([a-zA-Z0-9:-]+)(?=[^>]*></\\2>)",
"beginCaptures": {
"1": {
"name": "punctuation.definition.tag.html"
},
"2": {
"name": "entity.name.tag.html"
}
},
"end": "(>(<)/)(\\2)(>)",
"endCaptures": {
"1": {
"name": "punctuation.definition.tag.html"
},
"2": {
"name": "meta.scope.between-tag-pair.html"
},
"3": {
"name": "entity.name.tag.html"
},
"4": {
"name": "punctuation.definition.tag.html"
}
},
"name": "meta.tag.any.html",
"patterns": [
{
"include": "#tag-stuff"
}
]
},
{
"begin": "(<\\?)(xml)",
"captures": {
"1": {
"name": "punctuation.definition.tag.html"
},
"2": {
"name": "entity.name.tag.xml.html"
}
},
"end": "(\\?>)",
"name": "meta.tag.preprocessor.xml.html",
"patterns": [
{
"include": "#tag_generic_attribute"
},
{
"include": "#string"
}
]
},
{
"begin": "<!--",
"captures": {
"0": {
"name": "punctuation.definition.comment.html"
}
},
"end": "--\\s*>",
"name": "comment.block.html",
"patterns": [
{
"match": "--",
"name": "invalid.illegal.bad-comments-or-CDATA.html"
}
]
},
{
"begin": "<!",
"captures": {
"0": {
"name": "punctuation.definition.tag.html"
}
},
"end": ">",
"name": "meta.tag.sgml.html",
"patterns": [
{
"begin": "(DOCTYPE|doctype)",
"captures": {
"1": {
"name": "entity.name.tag.doctype.html"
}
},
"end": "(?=>)",
"name": "meta.tag.sgml.doctype.html",
"patterns": [
{
"match": "\"[^\">]*\"",
"name": "string.quoted.double.doctype.identifiers-and-DTDs.html"
}
]
},
{
"begin": "\\[CDATA\\[",
"end": "]](?=>)",
"name": "constant.other.inline-data.html"
},
{
"match": "(\\s*)(?!--|>)\\S(\\s*)",
"name": "invalid.illegal.bad-comments-or-CDATA.html"
}
]
},
{
"begin": "(?:^\\s+)?(<)((?i:style))\\b(?![^>]*/>)",
"captures": {
"1": {
"name": "punctuation.definition.tag.html"
},
"2": {
"name": "entity.name.tag.style.html"
},
"3": {
"name": "punctuation.definition.tag.html"
}
},
"end": "(</)((?i:style))(>)(?:\\s*\\n)?",
"name": "source.css.embedded.html",
"patterns": [
{
"include": "#tag-stuff"
},
{
"begin": "(>)",
"beginCaptures": {
"1": {
"name": "punctuation.definition.tag.html"
}
},
"end": "(?=</(?i:style))",
"patterns": [
{
"include": "source.css"
}
]
}
]
},
{
"begin": "(?:^\\s+)?(<)((?i:script))\\b(?![^>]*/>)",
"beginCaptures": {
"1": {
"name": "punctuation.definition.tag.html"
},
"2": {
"name": "entity.name.tag.script.html"
}
},
"end": "(?<=</(script|SCRIPT))(>)(?:\\s*\\n)?",
"endCaptures": {
"2": {
"name": "punctuation.definition.tag.html"
}
},
"name": "source.js.embedded.html",
"patterns": [
{
"include": "#tag-stuff"
},
{
"begin": "(?<!</(?:script|SCRIPT))(>)",
"captures": {
"1": {
"name": "punctuation.definition.tag.html"
},
"2": {
"name": "entity.name.tag.script.html"
}
},
"end": "(</)((?i:script))",
"patterns": [
{
"captures": {
"1": {
"name": "punctuation.definition.comment.js"
}
},
"match": "(//).*?((?=</script)|$\\n?)",
"name": "comment.line.double-slash.js"
},
{
"begin": "/\\*",
"captures": {
"0": {
"name": "punctuation.definition.comment.js"
}
},
"end": "\\*/|(?=</script)",
"name": "comment.block.js"
},
{
"include": "source.js"
}
]
}
]
},
{
"begin": "(</?)((?i:body|head|html)\\b)",
"captures": {
"1": {
"name": "punctuation.definition.tag.html"
},
"2": {
"name": "entity.name.tag.structure.any.html"
}
},
"end": "(>)",
"name": "meta.tag.structure.any.html",
"patterns": [
{
"include": "#tag-stuff"
}
]
},
{
"begin": "(</?)((?i:address|blockquote|dd|div|header|section|footer|aside|nav|dl|dt|fieldset|form|frame|frameset|h1|h2|h3|h4|h5|h6|iframe|noframes|object|ol|p|ul|applet|center|dir|hr|menu|pre)\\b)",
"captures": {
"1": {
"name": "punctuation.definition.tag.html"
},
"2": {
"name": "entity.name.tag.block.any.html"
}
},
"end": "(>)",
"name": "meta.tag.block.any.html",
"patterns": [
{
"include": "#tag-stuff"
}
]
},
{
"begin": "(</?)((?i:a|abbr|acronym|area|b|base|basefont|bdo|big|br|button|caption|cite|code|col|colgroup|del|dfn|em|font|head|html|i|img|input|ins|isindex|kbd|label|legend|li|link|map|meta|noscript|optgroup|option|param|q|s|samp|script|select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot|th|thead|title|tr|tt|u|var)\\b)",
"captures": {
"1": {
"name": "punctuation.definition.tag.html"
},
"2": {
"name": "entity.name.tag.inline.any.html"
}
},
"end": "((?: ?/)?>)",
"name": "meta.tag.inline.any.html",
"patterns": [
{
"include": "#tag-stuff"
}
]
},
{
"begin": "(</?)([a-zA-Z0-9:-]+)",
"captures": {
"1": {
"name": "punctuation.definition.tag.html"
},
"2": {
"name": "entity.name.tag.other.html"
}
},
"end": "(>)",
"name": "meta.tag.other.html",
"patterns": [
{
"include": "#tag-stuff"
}
]
},
{
"begin": "(</?)([a-zA-Z0-9{}:-]+)",
"captures": {
"1": {
"name": "punctuation.definition.tag.html"
},
"2": {
"name": "entity.name.tag.tokenised.html"
}
},
"end": "(>)",
"name": "meta.tag.tokenised.html",
"patterns": [
{
"include": "#tag-stuff"
}
]
},
{
"include": "#entities"
},
{
"match": "<>",
"name": "invalid.illegal.incomplete.html"
},
{
"match": "<",
"name": "invalid.illegal.bad-angle-bracket.html"
}
]
},
"entities": {
"patterns": [
{
"captures": {
"1": {
"name": "punctuation.definition.entity.html"
},
"3": {
"name": "punctuation.definition.entity.html"
}
},
"name": "constant.character.entity.html",
"match": "(&)([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+)(;)"
},
{
"name": "invalid.illegal.bad-ampersand.html",
"match": "&"
}
]
},
"end_block": {
"begin": "(\\{\\{)(~?/)([a-zA-Z0-9/_\\.-]+)\\s*",
"end": "(~?\\}\\})",
"name": "meta.function.block.end.handlebars",
"endCaptures": {
"1": {
"name": "support.constant.handlebars"
}
},
"beginCaptures": {
"1": {
"name": "support.constant.handlebars"
},
"2": {
"name": "support.constant.handlebars keyword.control"
},
"3": {
"name": "support.constant.handlebars keyword.control"
}
},
"patterns": []
},
"yfm": {
"patterns": [
{
"patterns": [
{
"include": "source.yaml"
}
],
"begin": "(?<!\\s)---\\n$",
"end": "^---\\s",
"name": "markup.raw.yaml.front-matter"
}
]
},
"comments": {
"patterns": [
{
"patterns": [
{
"name": "keyword.annotation.handlebars",
"match": "@\\w*"
},
{
"include": "#comments"
}
],
"begin": "\\{\\{!",
"end": "\\}\\}",
"name": "comment.block.handlebars"
},
{
"captures": {
"0": {
"name": "punctuation.definition.comment.html"
}
},
"begin": "<!--",
"end": "-{2,3}\\s*>",
"name": "comment.block.html",
"patterns": [
{
"name": "invalid.illegal.bad-comments-or-CDATA.html",
"match": "--"
}
]
}
]
},
"block_comments": {
"patterns": [
{
"patterns": [
{
"name": "keyword.annotation.handlebars",
"match": "@\\w*"
},
{
"include": "#comments"
}
],
"begin": "\\{\\{!--",
"end": "--\\}\\}",
"name": "comment.block.handlebars"
},
{
"captures": {
"0": {
"name": "punctuation.definition.comment.html"
}
},
"begin": "<!--",
"end": "-{2,3}\\s*>",
"name": "comment.block.html",
"patterns": [
{
"name": "invalid.illegal.bad-comments-or-CDATA.html",
"match": "--"
}
]
}
]
},
"block_helper": {
"begin": "(\\{\\{)(~?\\#)([-a-zA-Z0-9_\\./>]+)\\s?(@?[-a-zA-Z0-9_\\./]+)*\\s?(@?[-a-zA-Z0-9_\\./]+)*\\s?(@?[-a-zA-Z0-9_\\./]+)*",
"end": "(~?\\}\\})",
"name": "meta.function.block.start.handlebars",
"endCaptures": {
"1": {
"name": "support.constant.handlebars"
}
},
"beginCaptures": {
"1": {
"name": "support.constant.handlebars"
},
"2": {
"name": "support.constant.handlebars keyword.control"
},
"3": {
"name": "support.constant.handlebars keyword.control"
},
"4": {
"name": "variable.parameter.handlebars"
},
"5": {
"name": "support.constant.handlebars"
},
"6": {
"name": "variable.parameter.handlebars"
},
"7": {
"name": "support.constant.handlebars"
}
},
"patterns": [
{
"include": "#string"
},
{
"include": "#handlebars_attribute"
}
]
},
"string-single-quoted": {
"begin": "'",
"end": "'",
"name": "string.quoted.single.handlebars",
"endCaptures": {
"0": {
"name": "punctuation.definition.string.end.html"
}
},
"beginCaptures": {
"0": {
"name": "punctuation.definition.string.begin.html"
}
},
"patterns": [
{
"include": "#escaped-single-quote"
},
{
"include": "#block_comments"
},
{
"include": "#comments"
},
{
"include": "#block_helper"
},
{
"include": "#else_token"
},
{
"include": "#end_block"
},
{
"include": "#partial_and_var"
}
]
},
"string": {
"patterns": [
{
"include": "#string-single-quoted"
},
{
"include": "#string-double-quoted"
}
]
},
"escaped-single-quote": {
"name": "constant.character.escape.js",
"match": "\\\\'"
},
"escaped-double-quote": {
"name": "constant.character.escape.js",
"match": "\\\\\""
},
"partial_and_var": {
"begin": "(\\{\\{~?\\{*(>|!<)*)\\s*(@?[-a-zA-Z0-9$_\\./]+)*",
"end": "(~?\\}\\}\\}*)",
"name": "meta.function.inline.other.handlebars",
"beginCaptures": {
"1": {
"name": "support.constant.handlebars"
},
"3": {
"name": "variable.parameter.handlebars"
}
},
"endCaptures": {
"1": {
"name": "support.constant.handlebars"
}
},
"patterns": [
{
"include": "#string"
},
{
"include": "#handlebars_attribute"
}
]
},
"handlebars_attribute_name": {
"begin": "\\b([-a-zA-Z0-9_\\.]+)\\b=",
"captures": {
"1": {
"name": "variable.parameter.handlebars"
}
},
"end": "(?='|\"|)",
"name": "entity.other.attribute-name.handlebars"
},
"handlebars_attribute_value": {
"begin": "([-a-zA-Z0-9_\\./]+)\\b",
"captures": {
"1": {
"name": "variable.parameter.handlebars"
}
},
"end": "('|\"|)",
"name": "entity.other.attribute-value.handlebars",
"patterns": [
{
"include": "#string"
}
]
},
"handlebars_attribute": {
"patterns": [
{
"include": "#handlebars_attribute_name"
},
{
"include": "#handlebars_attribute_value"
}
]
},
"extends": {
"patterns": [
{
"end": "(\\}\\})",
"begin": "(\\{\\{!<)\\s([-a-zA-Z0-9_\\./]+)",
"beginCaptures": {
"1": {
"name": "support.function.handlebars"
},
"2": {
"name": "support.class.handlebars"
}
},
"endCaptures": {
"1": {
"name": "support.function.handlebars"
}
},
"name": "meta.preprocessor.handlebars"
}
]
},
"else_token": {
"begin": "(\\{\\{)(~?else)(@?\\s(if)\\s([-a-zA-Z0-9_\\.\\(\\s\\)/]+))?",
"end": "(~?\\}\\}\\}*)",
"name": "meta.function.inline.else.handlebars",
"beginCaptures": {
"1": {
"name": "support.constant.handlebars"
},
"2": {
"name": "support.constant.handlebars keyword.control"
},
"3": {
"name": "support.constant.handlebars"
},
"4": {
"name": "variable.parameter.handlebars"
}
},
"endCaptures": {
"1": {
"name": "support.constant.handlebars"
}
}
},
"string-double-quoted": {
"begin": "\"",
"end": "\"",
"name": "string.quoted.double.handlebars",
"beginCaptures": {
"0": {
"name": "punctuation.definition.string.begin.html"
}
},
"endCaptures": {
"0": {
"name": "punctuation.definition.string.end.html"
}
},
"patterns": [
{
"include": "#escaped-double-quote"
},
{
"include": "#block_comments"
},
{
"include": "#comments"
},
{
"include": "#block_helper"
},
{
"include": "#else_token"
},
{
"include": "#end_block"
},
{
"include": "#partial_and_var"
}
]
},
"inline_script": {
"begin": "(?:^\\s+)?(<)((?i:script))\\b(?:.*(type)=([\"'](?:text/x-handlebars-template|text/x-handlebars|text/template|x-tmpl-handlebars)[\"']))(?![^>]*/>)",
"beginCaptures": {
"1": {
"name": "punctuation.definition.tag.html"
},
"2": {
"name": "entity.name.tag.script.html"
},
"3": {
"name": "entity.other.attribute-name.html"
},
"4": {
"name": "string.quoted.double.html"
}
},
"end": "(?<=</(script|SCRIPT))(>)(?:\\s*\\n)?",
"endCaptures": {
"2": {
"name": "punctuation.definition.tag.html"
}
},
"name": "source.handlebars.embedded.html",
"patterns": [
{
"include": "#tag-stuff"
},
{
"begin": "(?<!</(?:script|SCRIPT))(>)",
"captures": {
"1": {
"name": "punctuation.definition.tag.html"
},
"2": {
"name": "entity.name.tag.script.html"
}
},
"end": "(</)((?i:script))",
"patterns": [
{
"include": "#block_comments"
},
{
"include": "#comments"
},
{
"include": "#block_helper"
},
{
"include": "#end_block"
},
{
"include": "#else_token"
},
{
"include": "#partial_and_var"
},
{
"include": "#html_tags"
},
{
"include": "text.html.basic"
}
]
}
]
},
"tag_generic_attribute": {
"begin": "\\b([a-zA-Z0-9_-]+)\\b\\s*(=)",
"captures": {
"1": {
"name": "entity.other.attribute-name.generic.html"
},
"2": {
"name": "punctuation.separator.key-value.html"
}
},
"patterns": [
{
"include": "#string"
}
],
"name": "entity.other.attribute-name.html",
"end": "(?<='|\"|)"
},
"tag_id_attribute": {
"begin": "\\b(id)\\b\\s*(=)",
"captures": {
"1": {
"name": "entity.other.attribute-name.id.html"
},
"2": {
"name": "punctuation.separator.key-value.html"
}
},
"end": "(?<='|\"|)",
"name": "meta.attribute-with-value.id.html",
"patterns": [
{
"include": "#string"
}
]
},
"tag-stuff": {
"patterns": [
{
"include": "#tag_id_attribute"
},
{
"include": "#tag_generic_attribute"
},
{
"include": "#string"
},
{
"include": "#block_comments"
},
{
"include": "#comments"
},
{
"include": "#block_helper"
},
{
"include": "#end_block"
},
{
"include": "#else_token"
},
{
"include": "#partial_and_var"
}
]
}
}
} | extensions/handlebars/syntaxes/Handlebars.tmLanguage.json | 0 | https://github.com/microsoft/vscode/commit/c0efffc91f0c4cd10e70f30229f19da96a50f960 | [
0.0001739699364406988,
0.00017032268806360662,
0.00016676135419402272,
0.0001706588373053819,
0.0000017892282357934164
] |
{
"id": 1,
"code_window": [
"\t\tthis._throwIfFinalized();\n",
"\n",
"\t\tthis._collectedEdits.push({\n",
"\t\t\teditType: CellEditType.Delete,\n",
"\t\t\tindex\n",
"\t\t});\n",
"\t}\n",
"}\n",
"\n",
"export class ExtHostNotebookEditor extends Disposable implements vscode.NotebookEditor {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tindex,\n",
"\t\t\tcount: 1\n"
],
"file_path": "src/vs/workbench/api/common/extHostNotebook.ts",
"type": "replace",
"edit_start_line_idx": 427
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { readonly } from 'vs/base/common/errors';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import { ISplice } from 'vs/base/common/sequence';
import { URI, UriComponents } from 'vs/base/common/uri';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { CellKind, CellOutputKind, ExtHostNotebookShape, IMainContext, MainContext, MainThreadNotebookShape, NotebookCellOutputsSplice } from 'vs/workbench/api/common/extHost.protocol';
import { ExtHostCommands } from 'vs/workbench/api/common/extHostCommands';
import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors';
import { CellEditType, CellUri, diff, ICellEditOperation, ICellInsertEdit, IErrorOutput, INotebookDisplayOrder, INotebookEditData, IOrderedMimeType, IStreamOutput, ITransformedDisplayOutputDto, mimeTypeSupportedByCore, NotebookCellsChangedEvent, NotebookCellsSplice2, sortMimeTypes } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { Disposable as VSCodeDisposable } from './extHostTypes';
interface IObservable<T> {
proxy: T;
onDidChange: Event<void>;
}
function getObservable<T extends Object>(obj: T): IObservable<T> {
const onDidChange = new Emitter<void>();
const proxy = new Proxy(obj, {
set(target: T, p: PropertyKey, value: any, _receiver: any): boolean {
target[p as keyof T] = value;
onDidChange.fire();
return true;
}
});
return {
proxy,
onDidChange: onDidChange.event
};
}
const notebookDocumentMetadataDefaults: vscode.NotebookDocumentMetadata = {
editable: true,
cellEditable: true,
cellRunnable: true
};
export class ExtHostCell extends Disposable implements vscode.NotebookCell {
private originalSource: string[];
private _outputs: any[];
private _onDidChangeOutputs = new Emitter<ISplice<vscode.CellOutput>[]>();
onDidChangeOutputs: Event<ISplice<vscode.CellOutput>[]> = this._onDidChangeOutputs.event;
private _textDocument: vscode.TextDocument | undefined;
private _initalVersion: number = -1;
private _outputMapping = new Set<vscode.CellOutput>();
private _metadata: vscode.NotebookCellMetadata;
private _metadataChangeListener: IDisposable;
get source() {
if (this._textDocument && this._initalVersion !== this._textDocument?.version) {
return this._textDocument.getText();
} else {
return this.originalSource.join('\n');
}
}
constructor(
private viewType: string,
private documentUri: URI,
readonly handle: number,
readonly uri: URI,
private _content: string,
public readonly cellKind: CellKind,
public language: string,
outputs: any[],
_metadata: vscode.NotebookCellMetadata | undefined,
private _proxy: MainThreadNotebookShape
) {
super();
this.originalSource = this._content.split(/\r|\n|\r\n/g);
this._outputs = outputs;
const observableMetadata = getObservable(_metadata || {} as any);
this._metadata = observableMetadata.proxy;
this._metadataChangeListener = this._register(observableMetadata.onDidChange(() => {
this.updateMetadata();
}));
}
get outputs() {
return this._outputs;
}
set outputs(newOutputs: vscode.CellOutput[]) {
let diffs = diff<vscode.CellOutput>(this._outputs || [], newOutputs || [], (a) => {
return this._outputMapping.has(a);
});
diffs.forEach(diff => {
for (let i = diff.start; i < diff.start + diff.deleteCount; i++) {
this._outputMapping.delete(this._outputs[i]);
}
diff.toInsert.forEach(output => {
this._outputMapping.add(output);
});
});
this._outputs = newOutputs;
this._onDidChangeOutputs.fire(diffs);
}
get metadata() {
return this._metadata;
}
set metadata(newMetadata: vscode.NotebookCellMetadata) {
this._metadataChangeListener.dispose();
const observableMetadata = getObservable(newMetadata || {} as any); // TODO defaults
this._metadata = observableMetadata.proxy;
this._metadataChangeListener = this._register(observableMetadata.onDidChange(() => {
this.updateMetadata();
}));
this.updateMetadata();
}
private updateMetadata(): Promise<void> {
return this._proxy.$updateNotebookCellMetadata(this.viewType, this.documentUri, this.handle, this._metadata);
}
getContent(): string {
if (this._textDocument && this._initalVersion !== this._textDocument?.version) {
return this._textDocument.getText();
} else {
return this.originalSource.join('\n');
}
}
attachTextDocument(document: vscode.TextDocument) {
this._textDocument = document;
this._initalVersion = this._textDocument.version;
}
detachTextDocument() {
if (this._textDocument && this._textDocument.version !== this._initalVersion) {
this.originalSource = this._textDocument.getText().split(/\r|\n|\r\n/g);
}
this._textDocument = undefined;
this._initalVersion = -1;
}
}
export class ExtHostNotebookDocument extends Disposable implements vscode.NotebookDocument {
private static _handlePool: number = 0;
readonly handle = ExtHostNotebookDocument._handlePool++;
private _cells: ExtHostCell[] = [];
private _cellDisposableMapping = new Map<number, DisposableStore>();
get cells() {
return this._cells;
}
private _languages: string[] = [];
get languages() {
return this._languages = [];
}
set languages(newLanguages: string[]) {
this._languages = newLanguages;
this._proxy.$updateNotebookLanguages(this.viewType, this.uri, this._languages);
}
private _metadata: vscode.NotebookDocumentMetadata | undefined = notebookDocumentMetadataDefaults;
get metadata() {
return this._metadata;
}
set metadata(newMetadata: vscode.NotebookDocumentMetadata | undefined) {
this._metadata = newMetadata || notebookDocumentMetadataDefaults;
this._proxy.$updateNotebookMetadata(this.viewType, this.uri, this._metadata);
}
private _displayOrder: string[] = [];
get displayOrder() {
return this._displayOrder;
}
set displayOrder(newOrder: string[]) {
this._displayOrder = newOrder;
}
private _versionId = 0;
get versionId() {
return this._versionId;
}
constructor(
private readonly _proxy: MainThreadNotebookShape,
private _documentsAndEditors: ExtHostDocumentsAndEditors,
public viewType: string,
public uri: URI,
public renderingHandler: ExtHostNotebookOutputRenderingHandler
) {
super();
}
dispose() {
super.dispose();
this._cellDisposableMapping.forEach(cell => cell.dispose());
}
get fileName() { return this.uri.fsPath; }
get isDirty() { return false; }
accpetModelChanged(event: NotebookCellsChangedEvent) {
this.$spliceNotebookCells(event.changes);
this._versionId = event.versionId;
}
private $spliceNotebookCells(splices: NotebookCellsSplice2[]): void {
if (!splices.length) {
return;
}
splices.reverse().forEach(splice => {
let cellDtos = splice[2];
let newCells = cellDtos.map(cell => {
const extCell = new ExtHostCell(this.viewType, this.uri, cell.handle, URI.revive(cell.uri), cell.source.join('\n'), cell.cellKind, cell.language, cell.outputs, cell.metadata, this._proxy);
const document = this._documentsAndEditors.getDocument(URI.revive(cell.uri));
if (document) {
extCell.attachTextDocument(document.document);
}
if (!this._cellDisposableMapping.has(extCell.handle)) {
this._cellDisposableMapping.set(extCell.handle, new DisposableStore());
}
let store = this._cellDisposableMapping.get(extCell.handle)!;
store.add(extCell.onDidChangeOutputs((diffs) => {
this.eventuallyUpdateCellOutputs(extCell, diffs);
}));
return extCell;
});
for (let j = splice[0]; j < splice[0] + splice[1]; j++) {
this._cellDisposableMapping.get(this.cells[j].handle)?.dispose();
this._cellDisposableMapping.delete(this.cells[j].handle);
}
this.cells.splice(splice[0], splice[1], ...newCells);
});
}
eventuallyUpdateCellOutputs(cell: ExtHostCell, diffs: ISplice<vscode.CellOutput>[]) {
let renderers = new Set<number>();
let outputDtos: NotebookCellOutputsSplice[] = diffs.map(diff => {
let outputs = diff.toInsert;
let transformedOutputs = outputs.map(output => {
if (output.outputKind === CellOutputKind.Rich) {
const ret = this.transformMimeTypes(output);
if (ret.orderedMimeTypes[ret.pickedMimeTypeIndex].isResolved) {
renderers.add(ret.orderedMimeTypes[ret.pickedMimeTypeIndex].rendererId!);
}
return ret;
} else {
return output as IStreamOutput | IErrorOutput;
}
});
return [diff.start, diff.deleteCount, transformedOutputs];
});
this._proxy.$spliceNotebookCellOutputs(this.viewType, this.uri, cell.handle, outputDtos, Array.from(renderers));
}
transformMimeTypes(output: vscode.CellDisplayOutput): ITransformedDisplayOutputDto {
let mimeTypes = Object.keys(output.data);
// TODO@rebornix, the document display order might be assigned a bit later. We need to postpone sending the outputs to the core side.
let coreDisplayOrder = this.renderingHandler.outputDisplayOrder;
const sorted = sortMimeTypes(mimeTypes, coreDisplayOrder?.userOrder || [], this._displayOrder, coreDisplayOrder?.defaultOrder || []);
let orderMimeTypes: IOrderedMimeType[] = [];
sorted.forEach(mimeType => {
let handlers = this.renderingHandler.findBestMatchedRenderer(mimeType);
if (handlers.length) {
let renderedOutput = handlers[0].render(this, output, mimeType);
orderMimeTypes.push({
mimeType: mimeType,
isResolved: true,
rendererId: handlers[0].handle,
output: renderedOutput
});
for (let i = 1; i < handlers.length; i++) {
orderMimeTypes.push({
mimeType: mimeType,
isResolved: false,
rendererId: handlers[i].handle
});
}
if (mimeTypeSupportedByCore(mimeType)) {
orderMimeTypes.push({
mimeType: mimeType,
isResolved: false,
rendererId: -1
});
}
} else {
orderMimeTypes.push({
mimeType: mimeType,
isResolved: false
});
}
});
return {
outputKind: output.outputKind,
data: output.data,
orderedMimeTypes: orderMimeTypes,
pickedMimeTypeIndex: 0
};
}
getCell(cellHandle: number) {
return this.cells.find(cell => cell.handle === cellHandle);
}
attachCellTextDocument(textDocument: vscode.TextDocument) {
let cell = this.cells.find(cell => cell.uri.toString() === textDocument.uri.toString());
if (cell) {
cell.attachTextDocument(textDocument);
}
}
detachCellTextDocument(textDocument: vscode.TextDocument) {
let cell = this.cells.find(cell => cell.uri.toString() === textDocument.uri.toString());
if (cell) {
cell.detachTextDocument();
}
}
}
export class NotebookEditorCellEdit {
private _finalized: boolean = false;
private readonly _documentVersionId: number;
private _collectedEdits: ICellEditOperation[] = [];
private _renderers = new Set<number>();
constructor(
readonly editor: ExtHostNotebookEditor
) {
this._documentVersionId = editor.document.versionId;
}
finalize(): INotebookEditData {
this._finalized = true;
return {
documentVersionId: this._documentVersionId,
edits: this._collectedEdits,
renderers: Array.from(this._renderers)
};
}
private _throwIfFinalized() {
if (this._finalized) {
throw new Error('Edit is only valid while callback runs');
}
}
insert(index: number, content: string, language: string, type: CellKind, outputs: vscode.CellOutput[], metadata: vscode.NotebookCellMetadata | undefined): void {
this._throwIfFinalized();
let cell = {
source: [content],
language,
cellKind: type,
outputs: (outputs as any[]), // TODO@rebornix
metadata
};
const transformedOutputs = outputs.map(output => {
if (output.outputKind === CellOutputKind.Rich) {
const ret = this.editor.document.transformMimeTypes(output);
if (ret.orderedMimeTypes[ret.pickedMimeTypeIndex].isResolved) {
this._renderers.add(ret.orderedMimeTypes[ret.pickedMimeTypeIndex].rendererId!);
}
return ret;
} else {
return output as IStreamOutput | IErrorOutput;
}
});
cell.outputs = transformedOutputs;
this._collectedEdits.push({
editType: CellEditType.Insert,
index,
cells: [cell]
});
}
delete(index: number): void {
this._throwIfFinalized();
this._collectedEdits.push({
editType: CellEditType.Delete,
index
});
}
}
export class ExtHostNotebookEditor extends Disposable implements vscode.NotebookEditor {
private _viewColumn: vscode.ViewColumn | undefined;
onDidReceiveMessage: vscode.Event<any> = this._onDidReceiveMessage.event;
constructor(
private readonly viewType: string,
readonly id: string,
public uri: URI,
private _proxy: MainThreadNotebookShape,
private _onDidReceiveMessage: Emitter<any>,
public document: ExtHostNotebookDocument,
private _documentsAndEditors: ExtHostDocumentsAndEditors
) {
super();
this._register(this._documentsAndEditors.onDidAddDocuments(documents => {
for (const { document: textDocument } of documents) {
let data = CellUri.parse(textDocument.uri);
if (data) {
if (this.document.uri.toString() === data.notebook.toString()) {
document.attachCellTextDocument(textDocument);
}
}
}
}));
this._register(this._documentsAndEditors.onDidRemoveDocuments(documents => {
for (const { document: textDocument } of documents) {
let data = CellUri.parse(textDocument.uri);
if (data) {
if (this.document.uri.toString() === data.notebook.toString()) {
document.detachCellTextDocument(textDocument);
}
}
}
}));
}
edit(callback: (editBuilder: NotebookEditorCellEdit) => void): Thenable<boolean> {
const edit = new NotebookEditorCellEdit(this);
callback(edit);
return this._applyEdit(edit);
}
private _applyEdit(editBuilder: NotebookEditorCellEdit): Promise<boolean> {
const editData = editBuilder.finalize();
// return when there is nothing to do
if (editData.edits.length === 0) {
return Promise.resolve(true);
}
let compressedEdits: ICellEditOperation[] = [];
let compressedEditsIndex = -1;
for (let i = 0; i < editData.edits.length; i++) {
if (compressedEditsIndex < 0) {
compressedEdits.push(editData.edits[i]);
compressedEditsIndex++;
continue;
}
let prevIndex = compressedEditsIndex;
let prev = compressedEdits[prevIndex];
if (prev.editType === CellEditType.Insert && editData.edits[i].editType === CellEditType.Insert) {
if (prev.index + prev.cells.length === editData.edits[i].index) {
prev.cells.push(...(editData.edits[i] as ICellInsertEdit).cells);
continue;
}
}
compressedEdits.push(editData.edits[i]);
compressedEditsIndex++;
}
return this._proxy.$tryApplyEdits(this.viewType, this.uri, editData.documentVersionId, compressedEdits, editData.renderers);
}
get viewColumn(): vscode.ViewColumn | undefined {
return this._viewColumn;
}
set viewColumn(value) {
throw readonly('viewColumn');
}
async postMessage(message: any): Promise<boolean> {
return this._proxy.$postMessage(this.document.handle, message);
}
}
export class ExtHostNotebookOutputRenderer {
private static _handlePool: number = 0;
readonly handle = ExtHostNotebookOutputRenderer._handlePool++;
constructor(
public type: string,
public filter: vscode.NotebookOutputSelector,
public renderer: vscode.NotebookOutputRenderer
) {
}
matches(mimeType: string): boolean {
if (this.filter.subTypes) {
if (this.filter.subTypes.indexOf(mimeType) >= 0) {
return true;
}
}
return false;
}
render(document: ExtHostNotebookDocument, output: vscode.CellOutput, mimeType: string): string {
let html = this.renderer.render(document, output, mimeType);
return html;
}
}
export interface ExtHostNotebookOutputRenderingHandler {
outputDisplayOrder: INotebookDisplayOrder | undefined;
findBestMatchedRenderer(mimeType: string): ExtHostNotebookOutputRenderer[];
}
export class ExtHostNotebookController implements ExtHostNotebookShape, ExtHostNotebookOutputRenderingHandler {
private static _handlePool: number = 0;
private readonly _proxy: MainThreadNotebookShape;
private readonly _notebookProviders = new Map<string, { readonly provider: vscode.NotebookProvider, readonly extension: IExtensionDescription; }>();
private readonly _documents = new Map<string, ExtHostNotebookDocument>();
private readonly _editors = new Map<string, { editor: ExtHostNotebookEditor, onDidReceiveMessage: Emitter<any> }>();
private readonly _notebookOutputRenderers = new Map<number, ExtHostNotebookOutputRenderer>();
private _outputDisplayOrder: INotebookDisplayOrder | undefined;
get outputDisplayOrder(): INotebookDisplayOrder | undefined {
return this._outputDisplayOrder;
}
private _activeNotebookDocument: ExtHostNotebookDocument | undefined;
get activeNotebookDocument() {
return this._activeNotebookDocument;
}
constructor(mainContext: IMainContext, commands: ExtHostCommands, private _documentsAndEditors: ExtHostDocumentsAndEditors) {
this._proxy = mainContext.getProxy(MainContext.MainThreadNotebook);
commands.registerArgumentProcessor({
processArgument: arg => {
if (arg && arg.$mid === 12) {
const documentHandle = arg.notebookEditor?.notebookHandle;
const cellHandle = arg.cell.handle;
for (let value of this._editors) {
if (value[1].editor.document.handle === documentHandle) {
const cell = value[1].editor.document.getCell(cellHandle);
if (cell) {
return cell;
}
}
}
}
return arg;
}
});
}
registerNotebookOutputRenderer(
type: string,
extension: IExtensionDescription,
filter: vscode.NotebookOutputSelector,
renderer: vscode.NotebookOutputRenderer
): vscode.Disposable {
let extHostRenderer = new ExtHostNotebookOutputRenderer(type, filter, renderer);
this._notebookOutputRenderers.set(extHostRenderer.handle, extHostRenderer);
this._proxy.$registerNotebookRenderer({ id: extension.identifier, location: extension.extensionLocation }, type, filter, extHostRenderer.handle, renderer.preloads || []);
return new VSCodeDisposable(() => {
this._notebookOutputRenderers.delete(extHostRenderer.handle);
this._proxy.$unregisterNotebookRenderer(extHostRenderer.handle);
});
}
findBestMatchedRenderer(mimeType: string): ExtHostNotebookOutputRenderer[] {
let matches: ExtHostNotebookOutputRenderer[] = [];
for (let renderer of this._notebookOutputRenderers) {
if (renderer[1].matches(mimeType)) {
matches.push(renderer[1]);
}
}
return matches;
}
registerNotebookProvider(
extension: IExtensionDescription,
viewType: string,
provider: vscode.NotebookProvider,
): vscode.Disposable {
if (this._notebookProviders.has(viewType)) {
throw new Error(`Notebook provider for '${viewType}' already registered`);
}
this._notebookProviders.set(viewType, { extension, provider });
this._proxy.$registerNotebookProvider({ id: extension.identifier, location: extension.extensionLocation }, viewType);
return new VSCodeDisposable(() => {
this._notebookProviders.delete(viewType);
this._proxy.$unregisterNotebookProvider(viewType);
});
}
async $resolveNotebook(viewType: string, uri: UriComponents): Promise<number | undefined> {
let provider = this._notebookProviders.get(viewType);
if (provider) {
if (!this._documents.has(URI.revive(uri).toString())) {
let document = new ExtHostNotebookDocument(this._proxy, this._documentsAndEditors, viewType, URI.revive(uri), this);
await this._proxy.$createNotebookDocument(
document.handle,
viewType,
uri
);
this._documents.set(URI.revive(uri).toString(), document);
}
const onDidReceiveMessage = new Emitter<any>();
let editor = new ExtHostNotebookEditor(
viewType,
`${ExtHostNotebookController._handlePool++}`,
URI.revive(uri),
this._proxy,
onDidReceiveMessage,
this._documents.get(URI.revive(uri).toString())!,
this._documentsAndEditors
);
this._editors.set(URI.revive(uri).toString(), { editor, onDidReceiveMessage });
await provider.provider.resolveNotebook(editor);
// await editor.document.$updateCells();
return editor.document.handle;
}
return Promise.resolve(undefined);
}
async $executeNotebook(viewType: string, uri: UriComponents, cellHandle: number | undefined): Promise<void> {
let provider = this._notebookProviders.get(viewType);
if (!provider) {
return;
}
let document = this._documents.get(URI.revive(uri).toString());
if (!document) {
return;
}
let cell = cellHandle !== undefined ? document.getCell(cellHandle) : undefined;
return provider.provider.executeCell(document!, cell);
}
async $saveNotebook(viewType: string, uri: UriComponents): Promise<boolean> {
let provider = this._notebookProviders.get(viewType);
let document = this._documents.get(URI.revive(uri).toString());
if (provider && document) {
return await provider.provider.save(document);
}
return false;
}
async $updateActiveEditor(viewType: string, uri: UriComponents): Promise<void> {
this._activeNotebookDocument = this._documents.get(URI.revive(uri).toString());
}
async $destoryNotebookDocument(viewType: string, uri: UriComponents): Promise<boolean> {
let provider = this._notebookProviders.get(viewType);
if (!provider) {
return false;
}
let document = this._documents.get(URI.revive(uri).toString());
if (document) {
document.dispose();
this._documents.delete(URI.revive(uri).toString());
}
let editor = this._editors.get(URI.revive(uri).toString());
if (editor) {
editor.editor.dispose();
editor.onDidReceiveMessage.dispose();
this._editors.delete(URI.revive(uri).toString());
}
return true;
}
$acceptDisplayOrder(displayOrder: INotebookDisplayOrder): void {
this._outputDisplayOrder = displayOrder;
}
$onDidReceiveMessage(uri: UriComponents, message: any): void {
let editor = this._editors.get(URI.revive(uri).toString());
if (editor) {
editor.onDidReceiveMessage.fire(message);
}
}
$acceptModelChanged(uriComponents: UriComponents, event: NotebookCellsChangedEvent): void {
let editor = this._editors.get(URI.revive(uriComponents).toString());
if (editor) {
editor.editor.document.accpetModelChanged(event);
}
}
}
| src/vs/workbench/api/common/extHostNotebook.ts | 1 | https://github.com/microsoft/vscode/commit/c0efffc91f0c4cd10e70f30229f19da96a50f960 | [
0.99940025806427,
0.07721399515867233,
0.0001650975609663874,
0.00017332442803308368,
0.24381917715072632
] |
{
"id": 1,
"code_window": [
"\t\tthis._throwIfFinalized();\n",
"\n",
"\t\tthis._collectedEdits.push({\n",
"\t\t\teditType: CellEditType.Delete,\n",
"\t\t\tindex\n",
"\t\t});\n",
"\t}\n",
"}\n",
"\n",
"export class ExtHostNotebookEditor extends Disposable implements vscode.NotebookEditor {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tindex,\n",
"\t\t\tcount: 1\n"
],
"file_path": "src/vs/workbench/api/common/extHostNotebook.ts",
"type": "replace",
"edit_start_line_idx": 427
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as dom from 'vs/base/browser/dom';
import { Action } from 'vs/base/common/actions';
import { Disposable } from 'vs/base/common/lifecycle';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { IEditorMouseEvent, MouseTargetType } from 'vs/editor/browser/editorBrowser';
import { Range } from 'vs/editor/common/core/range';
import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget';
import { EditorOption } from 'vs/editor/common/config/editorOptions';
export interface IDiffLinesChange {
readonly originalStartLineNumber: number;
readonly originalEndLineNumber: number;
readonly modifiedStartLineNumber: number;
readonly modifiedEndLineNumber: number;
readonly originalContent: string[];
}
export class InlineDiffMargin extends Disposable {
private readonly _diffActions: HTMLElement;
private _visibility: boolean = false;
get visibility(): boolean {
return this._visibility;
}
set visibility(_visibility: boolean) {
if (this._visibility !== _visibility) {
this._visibility = _visibility;
if (_visibility) {
this._diffActions.style.visibility = 'visible';
} else {
this._diffActions.style.visibility = 'hidden';
}
}
}
constructor(
private _viewZoneId: string,
private _marginDomNode: HTMLElement,
public editor: CodeEditorWidget,
public diff: IDiffLinesChange,
private _contextMenuService: IContextMenuService,
private _clipboardService: IClipboardService
) {
super();
// make sure the diff margin shows above overlay.
this._marginDomNode.style.zIndex = '10';
this._diffActions = document.createElement('div');
this._diffActions.className = 'codicon codicon-lightbulb lightbulb-glyph';
this._diffActions.style.position = 'absolute';
const lineHeight = editor.getOption(EditorOption.lineHeight);
const lineFeed = editor.getModel()!.getEOL();
this._diffActions.style.right = '0px';
this._diffActions.style.visibility = 'hidden';
this._diffActions.style.height = `${lineHeight}px`;
this._diffActions.style.lineHeight = `${lineHeight}px`;
this._marginDomNode.appendChild(this._diffActions);
const actions: Action[] = [];
// default action
actions.push(new Action(
'diff.clipboard.copyDeletedContent',
diff.originalEndLineNumber > diff.modifiedStartLineNumber
? nls.localize('diff.clipboard.copyDeletedLinesContent.label', "Copy deleted lines")
: nls.localize('diff.clipboard.copyDeletedLinesContent.single.label', "Copy deleted line"),
undefined,
true,
async () => {
await this._clipboardService.writeText(diff.originalContent.join(lineFeed) + lineFeed);
}
));
let currentLineNumberOffset = 0;
let copyLineAction: Action | undefined = undefined;
if (diff.originalEndLineNumber > diff.modifiedStartLineNumber) {
copyLineAction = new Action(
'diff.clipboard.copyDeletedLineContent',
nls.localize('diff.clipboard.copyDeletedLineContent.label', "Copy deleted line ({0})", diff.originalStartLineNumber),
undefined,
true,
async () => {
await this._clipboardService.writeText(diff.originalContent[currentLineNumberOffset]);
}
);
actions.push(copyLineAction);
}
const readOnly = editor.getOption(EditorOption.readOnly);
if (!readOnly) {
actions.push(new Action('diff.inline.revertChange', nls.localize('diff.inline.revertChange.label', "Revert this change"), undefined, true, async () => {
if (diff.modifiedEndLineNumber === 0) {
// deletion only
const column = editor.getModel()!.getLineMaxColumn(diff.modifiedStartLineNumber);
editor.executeEdits('diffEditor', [
{
range: new Range(diff.modifiedStartLineNumber, column, diff.modifiedStartLineNumber, column),
text: lineFeed + diff.originalContent.join(lineFeed)
}
]);
} else {
const column = editor.getModel()!.getLineMaxColumn(diff.modifiedEndLineNumber);
editor.executeEdits('diffEditor', [
{
range: new Range(diff.modifiedStartLineNumber, 1, diff.modifiedEndLineNumber, column),
text: diff.originalContent.join(lineFeed)
}
]);
}
}));
}
const showContextMenu = (x: number, y: number) => {
this._contextMenuService.showContextMenu({
getAnchor: () => {
return {
x,
y
};
},
getActions: () => {
if (copyLineAction) {
copyLineAction.label = nls.localize('diff.clipboard.copyDeletedLineContent.label', "Copy deleted line ({0})", diff.originalStartLineNumber + currentLineNumberOffset);
}
return actions;
},
autoSelectFirstItem: true
});
};
this._register(dom.addStandardDisposableListener(this._diffActions, 'mousedown', e => {
const { top, height } = dom.getDomNodePagePosition(this._diffActions);
let pad = Math.floor(lineHeight / 3);
e.preventDefault();
showContextMenu(e.posx, top + height + pad);
}));
this._register(editor.onMouseMove((e: IEditorMouseEvent) => {
if (e.target.type === MouseTargetType.CONTENT_VIEW_ZONE || e.target.type === MouseTargetType.GUTTER_VIEW_ZONE) {
const viewZoneId = e.target.detail.viewZoneId;
if (viewZoneId === this._viewZoneId) {
this.visibility = true;
currentLineNumberOffset = this._updateLightBulbPosition(this._marginDomNode, e.event.browserEvent.y, lineHeight);
} else {
this.visibility = false;
}
} else {
this.visibility = false;
}
}));
this._register(editor.onMouseDown((e: IEditorMouseEvent) => {
if (!e.event.rightButton) {
return;
}
if (e.target.type === MouseTargetType.CONTENT_VIEW_ZONE || e.target.type === MouseTargetType.GUTTER_VIEW_ZONE) {
const viewZoneId = e.target.detail.viewZoneId;
if (viewZoneId === this._viewZoneId) {
e.event.preventDefault();
currentLineNumberOffset = this._updateLightBulbPosition(this._marginDomNode, e.event.browserEvent.y, lineHeight);
showContextMenu(e.event.posx, e.event.posy + lineHeight);
}
}
}));
}
private _updateLightBulbPosition(marginDomNode: HTMLElement, y: number, lineHeight: number): number {
const { top } = dom.getDomNodePagePosition(marginDomNode);
const offset = y - top;
const lineNumberOffset = Math.floor(offset / lineHeight);
const newTop = lineNumberOffset * lineHeight;
this._diffActions.style.top = `${newTop}px`;
return lineNumberOffset;
}
}
| src/vs/editor/browser/widget/inlineDiffMargin.ts | 0 | https://github.com/microsoft/vscode/commit/c0efffc91f0c4cd10e70f30229f19da96a50f960 | [
0.0001754348340909928,
0.00017174356617033482,
0.00016366557974833995,
0.000172049505636096,
0.0000028338017727946863
] |
{
"id": 1,
"code_window": [
"\t\tthis._throwIfFinalized();\n",
"\n",
"\t\tthis._collectedEdits.push({\n",
"\t\t\teditType: CellEditType.Delete,\n",
"\t\t\tindex\n",
"\t\t});\n",
"\t}\n",
"}\n",
"\n",
"export class ExtHostNotebookEditor extends Disposable implements vscode.NotebookEditor {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tindex,\n",
"\t\t\tcount: 1\n"
],
"file_path": "src/vs/workbench/api/common/extHostNotebook.ts",
"type": "replace",
"edit_start_line_idx": 427
} | /*---------------------------------------------------------------------------------------------
* 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 { IPickerQuickAccessItem, PickerQuickAccessProvider, TriggerAction } from 'vs/platform/quickinput/browser/pickerQuickAccess';
import { fuzzyScore, createMatches, FuzzyScore } from 'vs/base/common/filters';
import { stripWildcards } from 'vs/base/common/strings';
import { CancellationToken } from 'vs/base/common/cancellation';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { ThrottledDelayer } from 'vs/base/common/async';
import { getWorkspaceSymbols, IWorkspaceSymbol, IWorkspaceSymbolProvider } from 'vs/workbench/contrib/search/common/search';
import { SymbolKinds, SymbolTag, SymbolKind } from 'vs/editor/common/modes';
import { ILabelService } from 'vs/platform/label/common/label';
import { Schemas } from 'vs/base/common/network';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { IEditorService, SIDE_GROUP, ACTIVE_GROUP } from 'vs/workbench/services/editor/common/editorService';
import { Range } from 'vs/editor/common/core/range';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IWorkbenchEditorConfiguration } from 'vs/workbench/common/editor';
import { IKeyMods } from 'vs/platform/quickinput/common/quickInput';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { createResourceExcludeMatcher } from 'vs/workbench/services/search/common/search';
import { ResourceMap } from 'vs/base/common/map';
import { URI } from 'vs/base/common/uri';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import { getSelectionSearchString } from 'vs/editor/contrib/find/findController';
import { withNullAsUndefined } from 'vs/base/common/types';
interface ISymbolQuickPickItem extends IPickerQuickAccessItem {
resource: URI | undefined;
score: FuzzyScore | undefined;
symbol: IWorkspaceSymbol;
}
export class SymbolsQuickAccessProvider extends PickerQuickAccessProvider<ISymbolQuickPickItem> {
static PREFIX = '#';
private static readonly TYPING_SEARCH_DELAY = 200; // this delay accommodates for the user typing a word and then stops typing to start searching
private static TREAT_AS_GLOBAL_SYMBOL_TYPES = new Set<SymbolKind>([
SymbolKind.Class,
SymbolKind.Enum,
SymbolKind.File,
SymbolKind.Interface,
SymbolKind.Namespace,
SymbolKind.Package,
SymbolKind.Module
]);
private delayer = this._register(new ThrottledDelayer<ISymbolQuickPickItem[]>(SymbolsQuickAccessProvider.TYPING_SEARCH_DELAY));
private readonly resourceExcludeMatcher = this._register(createResourceExcludeMatcher(this.instantiationService, this.configurationService));
get defaultFilterValue(): string | undefined {
// Prefer the word under the cursor in the active editor as default filter
const editor = this.codeEditorService.getFocusedCodeEditor();
if (editor) {
return withNullAsUndefined(getSelectionSearchString(editor));
}
return undefined;
}
constructor(
@ILabelService private readonly labelService: ILabelService,
@IOpenerService private readonly openerService: IOpenerService,
@IEditorService private readonly editorService: IEditorService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@ICodeEditorService private readonly codeEditorService: ICodeEditorService
) {
super(SymbolsQuickAccessProvider.PREFIX, { canAcceptInBackground: true });
}
private get configuration() {
const editorConfig = this.configurationService.getValue<IWorkbenchEditorConfiguration>().workbench.editor;
return {
openEditorPinned: !editorConfig.enablePreviewFromQuickOpen,
openSideBySideDirection: editorConfig.openSideBySideDirection
};
}
protected getPicks(filter: string, disposables: DisposableStore, token: CancellationToken): Promise<Array<ISymbolQuickPickItem>> {
return this.getSymbolPicks(filter, undefined, token);
}
async getSymbolPicks(filter: string, options: { skipLocal?: boolean, skipSorting?: boolean, delay?: number } | undefined, token: CancellationToken): Promise<Array<ISymbolQuickPickItem>> {
return this.delayer.trigger(async () => {
if (token.isCancellationRequested) {
return [];
}
return this.doGetSymbolPicks(filter, options, token);
}, options?.delay);
}
private async doGetSymbolPicks(filter: string, options: { skipLocal?: boolean, skipSorting?: boolean } | undefined, token: CancellationToken): Promise<Array<ISymbolQuickPickItem>> {
const workspaceSymbols = await getWorkspaceSymbols(filter, token);
if (token.isCancellationRequested) {
return [];
}
const symbolPicks: Array<ISymbolQuickPickItem> = [];
// Normalize filter
const [symbolFilter, containerFilter] = stripWildcards(filter).split(' ') as [string, string | undefined];
const symbolFilterLow = symbolFilter.toLowerCase();
const containerFilterLow = containerFilter?.toLowerCase();
// Convert to symbol picks and apply filtering
const openSideBySideDirection = this.configuration.openSideBySideDirection;
const symbolsExcludedByResource = new ResourceMap<boolean>();
for (const [provider, symbols] of workspaceSymbols) {
for (const symbol of symbols) {
// Depending on the workspace symbols filter setting, skip over symbols that:
// - do not have a container
// - and are not treated explicitly as global symbols (e.g. classes)
if (options?.skipLocal && !SymbolsQuickAccessProvider.TREAT_AS_GLOBAL_SYMBOL_TYPES.has(symbol.kind) && !!symbol.containerName) {
continue;
}
// Score by symbol label
const symbolLabel = symbol.name;
const symbolScore = fuzzyScore(symbolFilter, symbolFilterLow, 0, symbolLabel, symbolLabel.toLowerCase(), 0, true);
if (!symbolScore) {
continue;
}
const symbolUri = symbol.location.uri;
let containerLabel: string | undefined = undefined;
if (symbolUri) {
const containerPath = this.labelService.getUriLabel(symbolUri, { relative: true });
if (symbol.containerName) {
containerLabel = `${symbol.containerName} • ${containerPath}`;
} else {
containerLabel = containerPath;
}
}
// Score by container if specified
let containerScore: FuzzyScore | undefined = undefined;
if (containerFilter && containerFilterLow) {
if (containerLabel) {
containerScore = fuzzyScore(containerFilter, containerFilterLow, 0, containerLabel, containerLabel.toLowerCase(), 0, true);
}
if (!containerScore) {
continue;
}
}
// Filter out symbols that match the global resource filter
if (symbolUri) {
let excludeSymbolByResource = symbolsExcludedByResource.get(symbolUri);
if (typeof excludeSymbolByResource === 'undefined') {
excludeSymbolByResource = this.resourceExcludeMatcher.matches(symbolUri);
symbolsExcludedByResource.set(symbolUri, excludeSymbolByResource);
}
if (excludeSymbolByResource) {
continue;
}
}
const symbolLabelWithIcon = `$(symbol-${SymbolKinds.toString(symbol.kind) || 'property'}) ${symbolLabel}`;
const deprecated = symbol.tags ? symbol.tags.indexOf(SymbolTag.Deprecated) >= 0 : false;
symbolPicks.push({
symbol,
resource: symbolUri,
score: symbolScore,
label: symbolLabelWithIcon,
ariaLabel: localize('symbolAriaLabel', "{0}, symbols picker", symbolLabel),
highlights: deprecated ? undefined : {
label: createMatches(symbolScore, symbolLabelWithIcon.length - symbolLabel.length /* Readjust matches to account for codicons in label */),
description: createMatches(containerScore)
},
description: containerLabel,
strikethrough: deprecated,
buttons: [
{
iconClass: openSideBySideDirection === 'right' ? 'codicon-split-horizontal' : 'codicon-split-vertical',
tooltip: openSideBySideDirection === 'right' ? localize('openToSide', "Open to the Side") : localize('openToBottom', "Open to the Bottom")
}
],
trigger: (buttonIndex, keyMods) => {
this.openSymbol(provider, symbol, token, { keyMods, forceOpenSideBySide: true });
return TriggerAction.CLOSE_PICKER;
},
accept: async (keyMods, event) => this.openSymbol(provider, symbol, token, { keyMods, preserveFocus: event.inBackground }),
});
}
}
// Sort picks (unless disabled)
if (!options?.skipSorting) {
symbolPicks.sort((symbolA, symbolB) => this.compareSymbols(symbolA, symbolB));
}
return symbolPicks;
}
private async openSymbol(provider: IWorkspaceSymbolProvider, symbol: IWorkspaceSymbol, token: CancellationToken, options: { keyMods: IKeyMods, forceOpenSideBySide?: boolean, preserveFocus?: boolean }): Promise<void> {
// Resolve actual symbol to open for providers that can resolve
let symbolToOpen = symbol;
if (typeof provider.resolveWorkspaceSymbol === 'function' && !symbol.location.range) {
symbolToOpen = await provider.resolveWorkspaceSymbol(symbol, token) || symbol;
if (token.isCancellationRequested) {
return;
}
}
// Open HTTP(s) links with opener service
if (symbolToOpen.location.uri.scheme === Schemas.http || symbolToOpen.location.uri.scheme === Schemas.https) {
await this.openerService.open(symbolToOpen.location.uri, { fromUserGesture: true });
}
// Otherwise open as editor
else {
await this.editorService.openEditor({
resource: symbolToOpen.location.uri,
options: {
preserveFocus: options?.preserveFocus,
pinned: options.keyMods.alt || this.configuration.openEditorPinned,
selection: symbolToOpen.location.range ? Range.collapseToStart(symbolToOpen.location.range) : undefined
}
}, options.keyMods.ctrlCmd || options?.forceOpenSideBySide ? SIDE_GROUP : ACTIVE_GROUP);
}
}
private compareSymbols(symbolA: ISymbolQuickPickItem, symbolB: ISymbolQuickPickItem): number {
// By score
if (symbolA.score && symbolB.score) {
if (symbolA.score[0] > symbolB.score[0]) {
return -1;
} else if (symbolA.score[0] < symbolB.score[0]) {
return 1;
}
}
// By name
const symbolAName = symbolA.symbol.name.toLowerCase();
const symbolBName = symbolB.symbol.name.toLowerCase();
const res = symbolAName.localeCompare(symbolBName);
if (res !== 0) {
return res;
}
// By kind
const symbolAKind = SymbolKinds.toCssClassName(symbolA.symbol.kind);
const symbolBKind = SymbolKinds.toCssClassName(symbolB.symbol.kind);
return symbolAKind.localeCompare(symbolBKind);
}
}
| src/vs/workbench/contrib/search/browser/symbolsQuickAccess.ts | 0 | https://github.com/microsoft/vscode/commit/c0efffc91f0c4cd10e70f30229f19da96a50f960 | [
0.00018114325939677656,
0.00017435895279049873,
0.00016742302977945656,
0.0001745039044180885,
0.0000030614526167482836
] |
{
"id": 1,
"code_window": [
"\t\tthis._throwIfFinalized();\n",
"\n",
"\t\tthis._collectedEdits.push({\n",
"\t\t\teditType: CellEditType.Delete,\n",
"\t\t\tindex\n",
"\t\t});\n",
"\t}\n",
"}\n",
"\n",
"export class ExtHostNotebookEditor extends Disposable implements vscode.NotebookEditor {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tindex,\n",
"\t\t\tcount: 1\n"
],
"file_path": "src/vs/workbench/api/common/extHostNotebook.ts",
"type": "replace",
"edit_start_line_idx": 427
} | test/**
src/**
tsconfig.json
out/**
extension.webpack.config.js
yarn.lock | extensions/extension-editing/.vscodeignore | 0 | https://github.com/microsoft/vscode/commit/c0efffc91f0c4cd10e70f30229f19da96a50f960 | [
0.00017348174878861755,
0.00017348174878861755,
0.00017348174878861755,
0.00017348174878861755,
0
] |
{
"id": 2,
"code_window": [
"\n",
"\t\t\tlet prevIndex = compressedEditsIndex;\n",
"\t\t\tlet prev = compressedEdits[prevIndex];\n",
"\n",
"\t\t\tif (prev.editType === CellEditType.Insert && editData.edits[i].editType === CellEditType.Insert) {\n",
"\t\t\t\tif (prev.index + prev.cells.length === editData.edits[i].index) {\n",
"\t\t\t\t\tprev.cells.push(...(editData.edits[i] as ICellInsertEdit).cells);\n",
"\t\t\t\t\tcontinue;\n",
"\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tif (prev.index === editData.edits[i].index) {\n"
],
"file_path": "src/vs/workbench/api/common/extHostNotebook.ts",
"type": "replace",
"edit_start_line_idx": 497
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { readonly } from 'vs/base/common/errors';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import { ISplice } from 'vs/base/common/sequence';
import { URI, UriComponents } from 'vs/base/common/uri';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { CellKind, CellOutputKind, ExtHostNotebookShape, IMainContext, MainContext, MainThreadNotebookShape, NotebookCellOutputsSplice } from 'vs/workbench/api/common/extHost.protocol';
import { ExtHostCommands } from 'vs/workbench/api/common/extHostCommands';
import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors';
import { CellEditType, CellUri, diff, ICellEditOperation, ICellInsertEdit, IErrorOutput, INotebookDisplayOrder, INotebookEditData, IOrderedMimeType, IStreamOutput, ITransformedDisplayOutputDto, mimeTypeSupportedByCore, NotebookCellsChangedEvent, NotebookCellsSplice2, sortMimeTypes } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { Disposable as VSCodeDisposable } from './extHostTypes';
interface IObservable<T> {
proxy: T;
onDidChange: Event<void>;
}
function getObservable<T extends Object>(obj: T): IObservable<T> {
const onDidChange = new Emitter<void>();
const proxy = new Proxy(obj, {
set(target: T, p: PropertyKey, value: any, _receiver: any): boolean {
target[p as keyof T] = value;
onDidChange.fire();
return true;
}
});
return {
proxy,
onDidChange: onDidChange.event
};
}
const notebookDocumentMetadataDefaults: vscode.NotebookDocumentMetadata = {
editable: true,
cellEditable: true,
cellRunnable: true
};
export class ExtHostCell extends Disposable implements vscode.NotebookCell {
private originalSource: string[];
private _outputs: any[];
private _onDidChangeOutputs = new Emitter<ISplice<vscode.CellOutput>[]>();
onDidChangeOutputs: Event<ISplice<vscode.CellOutput>[]> = this._onDidChangeOutputs.event;
private _textDocument: vscode.TextDocument | undefined;
private _initalVersion: number = -1;
private _outputMapping = new Set<vscode.CellOutput>();
private _metadata: vscode.NotebookCellMetadata;
private _metadataChangeListener: IDisposable;
get source() {
if (this._textDocument && this._initalVersion !== this._textDocument?.version) {
return this._textDocument.getText();
} else {
return this.originalSource.join('\n');
}
}
constructor(
private viewType: string,
private documentUri: URI,
readonly handle: number,
readonly uri: URI,
private _content: string,
public readonly cellKind: CellKind,
public language: string,
outputs: any[],
_metadata: vscode.NotebookCellMetadata | undefined,
private _proxy: MainThreadNotebookShape
) {
super();
this.originalSource = this._content.split(/\r|\n|\r\n/g);
this._outputs = outputs;
const observableMetadata = getObservable(_metadata || {} as any);
this._metadata = observableMetadata.proxy;
this._metadataChangeListener = this._register(observableMetadata.onDidChange(() => {
this.updateMetadata();
}));
}
get outputs() {
return this._outputs;
}
set outputs(newOutputs: vscode.CellOutput[]) {
let diffs = diff<vscode.CellOutput>(this._outputs || [], newOutputs || [], (a) => {
return this._outputMapping.has(a);
});
diffs.forEach(diff => {
for (let i = diff.start; i < diff.start + diff.deleteCount; i++) {
this._outputMapping.delete(this._outputs[i]);
}
diff.toInsert.forEach(output => {
this._outputMapping.add(output);
});
});
this._outputs = newOutputs;
this._onDidChangeOutputs.fire(diffs);
}
get metadata() {
return this._metadata;
}
set metadata(newMetadata: vscode.NotebookCellMetadata) {
this._metadataChangeListener.dispose();
const observableMetadata = getObservable(newMetadata || {} as any); // TODO defaults
this._metadata = observableMetadata.proxy;
this._metadataChangeListener = this._register(observableMetadata.onDidChange(() => {
this.updateMetadata();
}));
this.updateMetadata();
}
private updateMetadata(): Promise<void> {
return this._proxy.$updateNotebookCellMetadata(this.viewType, this.documentUri, this.handle, this._metadata);
}
getContent(): string {
if (this._textDocument && this._initalVersion !== this._textDocument?.version) {
return this._textDocument.getText();
} else {
return this.originalSource.join('\n');
}
}
attachTextDocument(document: vscode.TextDocument) {
this._textDocument = document;
this._initalVersion = this._textDocument.version;
}
detachTextDocument() {
if (this._textDocument && this._textDocument.version !== this._initalVersion) {
this.originalSource = this._textDocument.getText().split(/\r|\n|\r\n/g);
}
this._textDocument = undefined;
this._initalVersion = -1;
}
}
export class ExtHostNotebookDocument extends Disposable implements vscode.NotebookDocument {
private static _handlePool: number = 0;
readonly handle = ExtHostNotebookDocument._handlePool++;
private _cells: ExtHostCell[] = [];
private _cellDisposableMapping = new Map<number, DisposableStore>();
get cells() {
return this._cells;
}
private _languages: string[] = [];
get languages() {
return this._languages = [];
}
set languages(newLanguages: string[]) {
this._languages = newLanguages;
this._proxy.$updateNotebookLanguages(this.viewType, this.uri, this._languages);
}
private _metadata: vscode.NotebookDocumentMetadata | undefined = notebookDocumentMetadataDefaults;
get metadata() {
return this._metadata;
}
set metadata(newMetadata: vscode.NotebookDocumentMetadata | undefined) {
this._metadata = newMetadata || notebookDocumentMetadataDefaults;
this._proxy.$updateNotebookMetadata(this.viewType, this.uri, this._metadata);
}
private _displayOrder: string[] = [];
get displayOrder() {
return this._displayOrder;
}
set displayOrder(newOrder: string[]) {
this._displayOrder = newOrder;
}
private _versionId = 0;
get versionId() {
return this._versionId;
}
constructor(
private readonly _proxy: MainThreadNotebookShape,
private _documentsAndEditors: ExtHostDocumentsAndEditors,
public viewType: string,
public uri: URI,
public renderingHandler: ExtHostNotebookOutputRenderingHandler
) {
super();
}
dispose() {
super.dispose();
this._cellDisposableMapping.forEach(cell => cell.dispose());
}
get fileName() { return this.uri.fsPath; }
get isDirty() { return false; }
accpetModelChanged(event: NotebookCellsChangedEvent) {
this.$spliceNotebookCells(event.changes);
this._versionId = event.versionId;
}
private $spliceNotebookCells(splices: NotebookCellsSplice2[]): void {
if (!splices.length) {
return;
}
splices.reverse().forEach(splice => {
let cellDtos = splice[2];
let newCells = cellDtos.map(cell => {
const extCell = new ExtHostCell(this.viewType, this.uri, cell.handle, URI.revive(cell.uri), cell.source.join('\n'), cell.cellKind, cell.language, cell.outputs, cell.metadata, this._proxy);
const document = this._documentsAndEditors.getDocument(URI.revive(cell.uri));
if (document) {
extCell.attachTextDocument(document.document);
}
if (!this._cellDisposableMapping.has(extCell.handle)) {
this._cellDisposableMapping.set(extCell.handle, new DisposableStore());
}
let store = this._cellDisposableMapping.get(extCell.handle)!;
store.add(extCell.onDidChangeOutputs((diffs) => {
this.eventuallyUpdateCellOutputs(extCell, diffs);
}));
return extCell;
});
for (let j = splice[0]; j < splice[0] + splice[1]; j++) {
this._cellDisposableMapping.get(this.cells[j].handle)?.dispose();
this._cellDisposableMapping.delete(this.cells[j].handle);
}
this.cells.splice(splice[0], splice[1], ...newCells);
});
}
eventuallyUpdateCellOutputs(cell: ExtHostCell, diffs: ISplice<vscode.CellOutput>[]) {
let renderers = new Set<number>();
let outputDtos: NotebookCellOutputsSplice[] = diffs.map(diff => {
let outputs = diff.toInsert;
let transformedOutputs = outputs.map(output => {
if (output.outputKind === CellOutputKind.Rich) {
const ret = this.transformMimeTypes(output);
if (ret.orderedMimeTypes[ret.pickedMimeTypeIndex].isResolved) {
renderers.add(ret.orderedMimeTypes[ret.pickedMimeTypeIndex].rendererId!);
}
return ret;
} else {
return output as IStreamOutput | IErrorOutput;
}
});
return [diff.start, diff.deleteCount, transformedOutputs];
});
this._proxy.$spliceNotebookCellOutputs(this.viewType, this.uri, cell.handle, outputDtos, Array.from(renderers));
}
transformMimeTypes(output: vscode.CellDisplayOutput): ITransformedDisplayOutputDto {
let mimeTypes = Object.keys(output.data);
// TODO@rebornix, the document display order might be assigned a bit later. We need to postpone sending the outputs to the core side.
let coreDisplayOrder = this.renderingHandler.outputDisplayOrder;
const sorted = sortMimeTypes(mimeTypes, coreDisplayOrder?.userOrder || [], this._displayOrder, coreDisplayOrder?.defaultOrder || []);
let orderMimeTypes: IOrderedMimeType[] = [];
sorted.forEach(mimeType => {
let handlers = this.renderingHandler.findBestMatchedRenderer(mimeType);
if (handlers.length) {
let renderedOutput = handlers[0].render(this, output, mimeType);
orderMimeTypes.push({
mimeType: mimeType,
isResolved: true,
rendererId: handlers[0].handle,
output: renderedOutput
});
for (let i = 1; i < handlers.length; i++) {
orderMimeTypes.push({
mimeType: mimeType,
isResolved: false,
rendererId: handlers[i].handle
});
}
if (mimeTypeSupportedByCore(mimeType)) {
orderMimeTypes.push({
mimeType: mimeType,
isResolved: false,
rendererId: -1
});
}
} else {
orderMimeTypes.push({
mimeType: mimeType,
isResolved: false
});
}
});
return {
outputKind: output.outputKind,
data: output.data,
orderedMimeTypes: orderMimeTypes,
pickedMimeTypeIndex: 0
};
}
getCell(cellHandle: number) {
return this.cells.find(cell => cell.handle === cellHandle);
}
attachCellTextDocument(textDocument: vscode.TextDocument) {
let cell = this.cells.find(cell => cell.uri.toString() === textDocument.uri.toString());
if (cell) {
cell.attachTextDocument(textDocument);
}
}
detachCellTextDocument(textDocument: vscode.TextDocument) {
let cell = this.cells.find(cell => cell.uri.toString() === textDocument.uri.toString());
if (cell) {
cell.detachTextDocument();
}
}
}
export class NotebookEditorCellEdit {
private _finalized: boolean = false;
private readonly _documentVersionId: number;
private _collectedEdits: ICellEditOperation[] = [];
private _renderers = new Set<number>();
constructor(
readonly editor: ExtHostNotebookEditor
) {
this._documentVersionId = editor.document.versionId;
}
finalize(): INotebookEditData {
this._finalized = true;
return {
documentVersionId: this._documentVersionId,
edits: this._collectedEdits,
renderers: Array.from(this._renderers)
};
}
private _throwIfFinalized() {
if (this._finalized) {
throw new Error('Edit is only valid while callback runs');
}
}
insert(index: number, content: string, language: string, type: CellKind, outputs: vscode.CellOutput[], metadata: vscode.NotebookCellMetadata | undefined): void {
this._throwIfFinalized();
let cell = {
source: [content],
language,
cellKind: type,
outputs: (outputs as any[]), // TODO@rebornix
metadata
};
const transformedOutputs = outputs.map(output => {
if (output.outputKind === CellOutputKind.Rich) {
const ret = this.editor.document.transformMimeTypes(output);
if (ret.orderedMimeTypes[ret.pickedMimeTypeIndex].isResolved) {
this._renderers.add(ret.orderedMimeTypes[ret.pickedMimeTypeIndex].rendererId!);
}
return ret;
} else {
return output as IStreamOutput | IErrorOutput;
}
});
cell.outputs = transformedOutputs;
this._collectedEdits.push({
editType: CellEditType.Insert,
index,
cells: [cell]
});
}
delete(index: number): void {
this._throwIfFinalized();
this._collectedEdits.push({
editType: CellEditType.Delete,
index
});
}
}
export class ExtHostNotebookEditor extends Disposable implements vscode.NotebookEditor {
private _viewColumn: vscode.ViewColumn | undefined;
onDidReceiveMessage: vscode.Event<any> = this._onDidReceiveMessage.event;
constructor(
private readonly viewType: string,
readonly id: string,
public uri: URI,
private _proxy: MainThreadNotebookShape,
private _onDidReceiveMessage: Emitter<any>,
public document: ExtHostNotebookDocument,
private _documentsAndEditors: ExtHostDocumentsAndEditors
) {
super();
this._register(this._documentsAndEditors.onDidAddDocuments(documents => {
for (const { document: textDocument } of documents) {
let data = CellUri.parse(textDocument.uri);
if (data) {
if (this.document.uri.toString() === data.notebook.toString()) {
document.attachCellTextDocument(textDocument);
}
}
}
}));
this._register(this._documentsAndEditors.onDidRemoveDocuments(documents => {
for (const { document: textDocument } of documents) {
let data = CellUri.parse(textDocument.uri);
if (data) {
if (this.document.uri.toString() === data.notebook.toString()) {
document.detachCellTextDocument(textDocument);
}
}
}
}));
}
edit(callback: (editBuilder: NotebookEditorCellEdit) => void): Thenable<boolean> {
const edit = new NotebookEditorCellEdit(this);
callback(edit);
return this._applyEdit(edit);
}
private _applyEdit(editBuilder: NotebookEditorCellEdit): Promise<boolean> {
const editData = editBuilder.finalize();
// return when there is nothing to do
if (editData.edits.length === 0) {
return Promise.resolve(true);
}
let compressedEdits: ICellEditOperation[] = [];
let compressedEditsIndex = -1;
for (let i = 0; i < editData.edits.length; i++) {
if (compressedEditsIndex < 0) {
compressedEdits.push(editData.edits[i]);
compressedEditsIndex++;
continue;
}
let prevIndex = compressedEditsIndex;
let prev = compressedEdits[prevIndex];
if (prev.editType === CellEditType.Insert && editData.edits[i].editType === CellEditType.Insert) {
if (prev.index + prev.cells.length === editData.edits[i].index) {
prev.cells.push(...(editData.edits[i] as ICellInsertEdit).cells);
continue;
}
}
compressedEdits.push(editData.edits[i]);
compressedEditsIndex++;
}
return this._proxy.$tryApplyEdits(this.viewType, this.uri, editData.documentVersionId, compressedEdits, editData.renderers);
}
get viewColumn(): vscode.ViewColumn | undefined {
return this._viewColumn;
}
set viewColumn(value) {
throw readonly('viewColumn');
}
async postMessage(message: any): Promise<boolean> {
return this._proxy.$postMessage(this.document.handle, message);
}
}
export class ExtHostNotebookOutputRenderer {
private static _handlePool: number = 0;
readonly handle = ExtHostNotebookOutputRenderer._handlePool++;
constructor(
public type: string,
public filter: vscode.NotebookOutputSelector,
public renderer: vscode.NotebookOutputRenderer
) {
}
matches(mimeType: string): boolean {
if (this.filter.subTypes) {
if (this.filter.subTypes.indexOf(mimeType) >= 0) {
return true;
}
}
return false;
}
render(document: ExtHostNotebookDocument, output: vscode.CellOutput, mimeType: string): string {
let html = this.renderer.render(document, output, mimeType);
return html;
}
}
export interface ExtHostNotebookOutputRenderingHandler {
outputDisplayOrder: INotebookDisplayOrder | undefined;
findBestMatchedRenderer(mimeType: string): ExtHostNotebookOutputRenderer[];
}
export class ExtHostNotebookController implements ExtHostNotebookShape, ExtHostNotebookOutputRenderingHandler {
private static _handlePool: number = 0;
private readonly _proxy: MainThreadNotebookShape;
private readonly _notebookProviders = new Map<string, { readonly provider: vscode.NotebookProvider, readonly extension: IExtensionDescription; }>();
private readonly _documents = new Map<string, ExtHostNotebookDocument>();
private readonly _editors = new Map<string, { editor: ExtHostNotebookEditor, onDidReceiveMessage: Emitter<any> }>();
private readonly _notebookOutputRenderers = new Map<number, ExtHostNotebookOutputRenderer>();
private _outputDisplayOrder: INotebookDisplayOrder | undefined;
get outputDisplayOrder(): INotebookDisplayOrder | undefined {
return this._outputDisplayOrder;
}
private _activeNotebookDocument: ExtHostNotebookDocument | undefined;
get activeNotebookDocument() {
return this._activeNotebookDocument;
}
constructor(mainContext: IMainContext, commands: ExtHostCommands, private _documentsAndEditors: ExtHostDocumentsAndEditors) {
this._proxy = mainContext.getProxy(MainContext.MainThreadNotebook);
commands.registerArgumentProcessor({
processArgument: arg => {
if (arg && arg.$mid === 12) {
const documentHandle = arg.notebookEditor?.notebookHandle;
const cellHandle = arg.cell.handle;
for (let value of this._editors) {
if (value[1].editor.document.handle === documentHandle) {
const cell = value[1].editor.document.getCell(cellHandle);
if (cell) {
return cell;
}
}
}
}
return arg;
}
});
}
registerNotebookOutputRenderer(
type: string,
extension: IExtensionDescription,
filter: vscode.NotebookOutputSelector,
renderer: vscode.NotebookOutputRenderer
): vscode.Disposable {
let extHostRenderer = new ExtHostNotebookOutputRenderer(type, filter, renderer);
this._notebookOutputRenderers.set(extHostRenderer.handle, extHostRenderer);
this._proxy.$registerNotebookRenderer({ id: extension.identifier, location: extension.extensionLocation }, type, filter, extHostRenderer.handle, renderer.preloads || []);
return new VSCodeDisposable(() => {
this._notebookOutputRenderers.delete(extHostRenderer.handle);
this._proxy.$unregisterNotebookRenderer(extHostRenderer.handle);
});
}
findBestMatchedRenderer(mimeType: string): ExtHostNotebookOutputRenderer[] {
let matches: ExtHostNotebookOutputRenderer[] = [];
for (let renderer of this._notebookOutputRenderers) {
if (renderer[1].matches(mimeType)) {
matches.push(renderer[1]);
}
}
return matches;
}
registerNotebookProvider(
extension: IExtensionDescription,
viewType: string,
provider: vscode.NotebookProvider,
): vscode.Disposable {
if (this._notebookProviders.has(viewType)) {
throw new Error(`Notebook provider for '${viewType}' already registered`);
}
this._notebookProviders.set(viewType, { extension, provider });
this._proxy.$registerNotebookProvider({ id: extension.identifier, location: extension.extensionLocation }, viewType);
return new VSCodeDisposable(() => {
this._notebookProviders.delete(viewType);
this._proxy.$unregisterNotebookProvider(viewType);
});
}
async $resolveNotebook(viewType: string, uri: UriComponents): Promise<number | undefined> {
let provider = this._notebookProviders.get(viewType);
if (provider) {
if (!this._documents.has(URI.revive(uri).toString())) {
let document = new ExtHostNotebookDocument(this._proxy, this._documentsAndEditors, viewType, URI.revive(uri), this);
await this._proxy.$createNotebookDocument(
document.handle,
viewType,
uri
);
this._documents.set(URI.revive(uri).toString(), document);
}
const onDidReceiveMessage = new Emitter<any>();
let editor = new ExtHostNotebookEditor(
viewType,
`${ExtHostNotebookController._handlePool++}`,
URI.revive(uri),
this._proxy,
onDidReceiveMessage,
this._documents.get(URI.revive(uri).toString())!,
this._documentsAndEditors
);
this._editors.set(URI.revive(uri).toString(), { editor, onDidReceiveMessage });
await provider.provider.resolveNotebook(editor);
// await editor.document.$updateCells();
return editor.document.handle;
}
return Promise.resolve(undefined);
}
async $executeNotebook(viewType: string, uri: UriComponents, cellHandle: number | undefined): Promise<void> {
let provider = this._notebookProviders.get(viewType);
if (!provider) {
return;
}
let document = this._documents.get(URI.revive(uri).toString());
if (!document) {
return;
}
let cell = cellHandle !== undefined ? document.getCell(cellHandle) : undefined;
return provider.provider.executeCell(document!, cell);
}
async $saveNotebook(viewType: string, uri: UriComponents): Promise<boolean> {
let provider = this._notebookProviders.get(viewType);
let document = this._documents.get(URI.revive(uri).toString());
if (provider && document) {
return await provider.provider.save(document);
}
return false;
}
async $updateActiveEditor(viewType: string, uri: UriComponents): Promise<void> {
this._activeNotebookDocument = this._documents.get(URI.revive(uri).toString());
}
async $destoryNotebookDocument(viewType: string, uri: UriComponents): Promise<boolean> {
let provider = this._notebookProviders.get(viewType);
if (!provider) {
return false;
}
let document = this._documents.get(URI.revive(uri).toString());
if (document) {
document.dispose();
this._documents.delete(URI.revive(uri).toString());
}
let editor = this._editors.get(URI.revive(uri).toString());
if (editor) {
editor.editor.dispose();
editor.onDidReceiveMessage.dispose();
this._editors.delete(URI.revive(uri).toString());
}
return true;
}
$acceptDisplayOrder(displayOrder: INotebookDisplayOrder): void {
this._outputDisplayOrder = displayOrder;
}
$onDidReceiveMessage(uri: UriComponents, message: any): void {
let editor = this._editors.get(URI.revive(uri).toString());
if (editor) {
editor.onDidReceiveMessage.fire(message);
}
}
$acceptModelChanged(uriComponents: UriComponents, event: NotebookCellsChangedEvent): void {
let editor = this._editors.get(URI.revive(uriComponents).toString());
if (editor) {
editor.editor.document.accpetModelChanged(event);
}
}
}
| src/vs/workbench/api/common/extHostNotebook.ts | 1 | https://github.com/microsoft/vscode/commit/c0efffc91f0c4cd10e70f30229f19da96a50f960 | [
0.9985962510108948,
0.013496928848326206,
0.00015697276103310287,
0.0001723585301078856,
0.1137525662779808
] |
{
"id": 2,
"code_window": [
"\n",
"\t\t\tlet prevIndex = compressedEditsIndex;\n",
"\t\t\tlet prev = compressedEdits[prevIndex];\n",
"\n",
"\t\t\tif (prev.editType === CellEditType.Insert && editData.edits[i].editType === CellEditType.Insert) {\n",
"\t\t\t\tif (prev.index + prev.cells.length === editData.edits[i].index) {\n",
"\t\t\t\t\tprev.cells.push(...(editData.edits[i] as ICellInsertEdit).cells);\n",
"\t\t\t\t\tcontinue;\n",
"\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tif (prev.index === editData.edits[i].index) {\n"
],
"file_path": "src/vs/workbench/api/common/extHostNotebook.ts",
"type": "replace",
"edit_start_line_idx": 497
} | [
{
"c": ":",
"t": "source.css.scss entity.other.attribute-name.pseudo-class.css punctuation.definition.entity.css",
"r": {
"dark_plus": "entity.other.attribute-name.pseudo-class.css: #D7BA7D",
"light_plus": "entity.other.attribute-name.pseudo-class.css: #800000",
"dark_vs": "entity.other.attribute-name.pseudo-class.css: #D7BA7D",
"light_vs": "entity.other.attribute-name.pseudo-class.css: #800000",
"hc_black": "entity.other.attribute-name.pseudo-class.css: #D7BA7D"
}
},
{
"c": "root",
"t": "source.css.scss entity.other.attribute-name.pseudo-class.css",
"r": {
"dark_plus": "entity.other.attribute-name.pseudo-class.css: #D7BA7D",
"light_plus": "entity.other.attribute-name.pseudo-class.css: #800000",
"dark_vs": "entity.other.attribute-name.pseudo-class.css: #D7BA7D",
"light_vs": "entity.other.attribute-name.pseudo-class.css: #800000",
"hc_black": "entity.other.attribute-name.pseudo-class.css: #D7BA7D"
}
},
{
"c": " ",
"t": "source.css.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "{",
"t": "source.css.scss meta.property-list.scss punctuation.section.property-list.begin.bracket.curly.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.css.scss meta.property-list.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "--spacing-unit",
"t": "source.css.scss meta.property-list.scss variable.scss",
"r": {
"dark_plus": "variable.scss: #9CDCFE",
"light_plus": "variable.scss: #FF0000",
"dark_vs": "variable.scss: #9CDCFE",
"light_vs": "variable.scss: #FF0000",
"hc_black": "variable.scss: #D4D4D4"
}
},
{
"c": ":",
"t": "source.css.scss meta.property-list.scss punctuation.separator.key-value.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.css.scss meta.property-list.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "6",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss constant.numeric.css",
"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"
}
},
{
"c": "px",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss constant.numeric.css keyword.other.unit.px.css",
"r": {
"dark_plus": "keyword.other.unit: #B5CEA8",
"light_plus": "keyword.other.unit: #098658",
"dark_vs": "keyword.other.unit: #B5CEA8",
"light_vs": "keyword.other.unit: #098658",
"hc_black": "keyword.other.unit: #B5CEA8"
}
},
{
"c": ";",
"t": "source.css.scss meta.property-list.scss punctuation.terminator.rule.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.css.scss meta.property-list.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "--cell-padding",
"t": "source.css.scss meta.property-list.scss variable.scss",
"r": {
"dark_plus": "variable.scss: #9CDCFE",
"light_plus": "variable.scss: #FF0000",
"dark_vs": "variable.scss: #9CDCFE",
"light_vs": "variable.scss: #FF0000",
"hc_black": "variable.scss: #D4D4D4"
}
},
{
"c": ":",
"t": "source.css.scss meta.property-list.scss punctuation.separator.key-value.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.css.scss meta.property-list.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "(",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss punctuation.definition.begin.bracket.round.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "4",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss constant.numeric.css",
"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"
}
},
{
"c": " ",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "*",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss keyword.operator.css",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": " ",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "var",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss support.function.misc.scss",
"r": {
"dark_plus": "support.function: #DCDCAA",
"light_plus": "support.function: #795E26",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "support.function: #DCDCAA"
}
},
{
"c": "(",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss punctuation.section.function.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "--spacing-unit",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss variable.scss",
"r": {
"dark_plus": "variable.scss: #9CDCFE",
"light_plus": "variable.scss: #FF0000",
"dark_vs": "variable.scss: #9CDCFE",
"light_vs": "variable.scss: #FF0000",
"hc_black": "variable.scss: #D4D4D4"
}
},
{
"c": ")",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss punctuation.section.function.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": ")",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss punctuation.definition.end.bracket.round.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": ";",
"t": "source.css.scss meta.property-list.scss punctuation.terminator.rule.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "}",
"t": "source.css.scss meta.property-list.scss punctuation.section.property-list.end.bracket.curly.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "body",
"t": "source.css.scss entity.name.tag.css",
"r": {
"dark_plus": "entity.name.tag.css: #D7BA7D",
"light_plus": "entity.name.tag: #800000",
"dark_vs": "entity.name.tag.css: #D7BA7D",
"light_vs": "entity.name.tag: #800000",
"hc_black": "entity.name.tag.css: #D7BA7D"
}
},
{
"c": " ",
"t": "source.css.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "{",
"t": "source.css.scss meta.property-list.scss punctuation.section.property-list.begin.bracket.curly.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.css.scss meta.property-list.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "padding-left",
"t": "source.css.scss meta.property-list.scss meta.property-name.scss support.type.property-name.css",
"r": {
"dark_plus": "support.type.property-name: #9CDCFE",
"light_plus": "support.type.property-name: #FF0000",
"dark_vs": "support.type.property-name: #9CDCFE",
"light_vs": "support.type.property-name: #FF0000",
"hc_black": "support.type.property-name: #D4D4D4"
}
},
{
"c": ":",
"t": "source.css.scss meta.property-list.scss punctuation.separator.key-value.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.css.scss meta.property-list.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "calc",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss support.function.misc.scss",
"r": {
"dark_plus": "support.function: #DCDCAA",
"light_plus": "support.function: #795E26",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "support.function: #DCDCAA"
}
},
{
"c": "(",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss punctuation.section.function.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "4",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss constant.numeric.css",
"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"
}
},
{
"c": " ",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "*",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss keyword.operator.css",
"r": {
"dark_plus": "keyword.operator: #D4D4D4",
"light_plus": "keyword.operator: #000000",
"dark_vs": "keyword.operator: #D4D4D4",
"light_vs": "keyword.operator: #000000",
"hc_black": "keyword.operator: #D4D4D4"
}
},
{
"c": " ",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "var",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss support.function.misc.scss",
"r": {
"dark_plus": "support.function: #DCDCAA",
"light_plus": "support.function: #795E26",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "support.function: #DCDCAA"
}
},
{
"c": "(",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss punctuation.section.function.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "--spacing-unit",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss variable.scss",
"r": {
"dark_plus": "variable.scss: #9CDCFE",
"light_plus": "variable.scss: #FF0000",
"dark_vs": "variable.scss: #9CDCFE",
"light_vs": "variable.scss: #FF0000",
"hc_black": "variable.scss: #D4D4D4"
}
},
{
"c": ",",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss punctuation.separator.delimiter.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": " ",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "5",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss constant.numeric.css",
"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"
}
},
{
"c": "px",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss constant.numeric.css keyword.other.unit.px.css",
"r": {
"dark_plus": "keyword.other.unit: #B5CEA8",
"light_plus": "keyword.other.unit: #098658",
"dark_vs": "keyword.other.unit: #B5CEA8",
"light_vs": "keyword.other.unit: #098658",
"hc_black": "keyword.other.unit: #B5CEA8"
}
},
{
"c": "))",
"t": "source.css.scss meta.property-list.scss meta.property-value.scss punctuation.section.function.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": ";",
"t": "source.css.scss meta.property-list.scss punctuation.terminator.rule.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
},
{
"c": "}",
"t": "source.css.scss meta.property-list.scss punctuation.section.property-list.end.bracket.curly.scss",
"r": {
"dark_plus": "default: #D4D4D4",
"light_plus": "default: #000000",
"dark_vs": "default: #D4D4D4",
"light_vs": "default: #000000",
"hc_black": "default: #FFFFFF"
}
}
]
| extensions/scss/test/colorize-results/test-cssvariables_scss.json | 0 | https://github.com/microsoft/vscode/commit/c0efffc91f0c4cd10e70f30229f19da96a50f960 | [
0.00017797391046769917,
0.00017498804663773626,
0.00017197182751260698,
0.00017475683125667274,
0.0000013098097042529844
] |
{
"id": 2,
"code_window": [
"\n",
"\t\t\tlet prevIndex = compressedEditsIndex;\n",
"\t\t\tlet prev = compressedEdits[prevIndex];\n",
"\n",
"\t\t\tif (prev.editType === CellEditType.Insert && editData.edits[i].editType === CellEditType.Insert) {\n",
"\t\t\t\tif (prev.index + prev.cells.length === editData.edits[i].index) {\n",
"\t\t\t\t\tprev.cells.push(...(editData.edits[i] as ICellInsertEdit).cells);\n",
"\t\t\t\t\tcontinue;\n",
"\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tif (prev.index === editData.edits[i].index) {\n"
],
"file_path": "src/vs/workbench/api/common/extHostNotebook.ts",
"type": "replace",
"edit_start_line_idx": 497
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export interface PreviewSettings {
readonly source: string;
readonly line: number;
readonly lineCount: number;
readonly scrollPreviewWithEditor?: boolean;
readonly scrollEditorWithPreview: boolean;
readonly disableSecurityWarnings: boolean;
readonly doubleClickToSwitchToEditor: boolean;
readonly webviewResourceRoot: string;
}
let cachedSettings: PreviewSettings | undefined = undefined;
export function getData<T = {}>(key: string): T {
const element = document.getElementById('vscode-markdown-preview-data');
if (element) {
const data = element.getAttribute(key);
if (data) {
return JSON.parse(data);
}
}
throw new Error(`Could not load data for ${key}`);
}
export function getSettings(): PreviewSettings {
if (cachedSettings) {
return cachedSettings;
}
cachedSettings = getData('data-settings');
if (cachedSettings) {
return cachedSettings;
}
throw new Error('Could not load settings');
}
| extensions/markdown-language-features/preview-src/settings.ts | 0 | https://github.com/microsoft/vscode/commit/c0efffc91f0c4cd10e70f30229f19da96a50f960 | [
0.00017885274428408593,
0.00017398146155755967,
0.00016526230319868773,
0.0001749040384311229,
0.000004598437953973189
] |
{
"id": 2,
"code_window": [
"\n",
"\t\t\tlet prevIndex = compressedEditsIndex;\n",
"\t\t\tlet prev = compressedEdits[prevIndex];\n",
"\n",
"\t\t\tif (prev.editType === CellEditType.Insert && editData.edits[i].editType === CellEditType.Insert) {\n",
"\t\t\t\tif (prev.index + prev.cells.length === editData.edits[i].index) {\n",
"\t\t\t\t\tprev.cells.push(...(editData.edits[i] as ICellInsertEdit).cells);\n",
"\t\t\t\t\tcontinue;\n",
"\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tif (prev.index === editData.edits[i].index) {\n"
],
"file_path": "src/vs/workbench/api/common/extHostNotebook.ts",
"type": "replace",
"edit_start_line_idx": 497
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Range } from 'vs/editor/common/core/range';
import { IModelDecoration, TrackedRangeStickiness, TrackedRangeStickiness as ActualTrackedRangeStickiness } from 'vs/editor/common/model';
import { ModelDecorationOptions } from 'vs/editor/common/model/textModel';
//
// The red-black tree is based on the "Introduction to Algorithms" by Cormen, Leiserson and Rivest.
//
export const enum ClassName {
EditorHintDecoration = 'squiggly-hint',
EditorInfoDecoration = 'squiggly-info',
EditorWarningDecoration = 'squiggly-warning',
EditorErrorDecoration = 'squiggly-error',
EditorUnnecessaryDecoration = 'squiggly-unnecessary',
EditorUnnecessaryInlineDecoration = 'squiggly-inline-unnecessary',
EditorDeprecatedInlineDecoration = 'squiggly-inline-deprecated'
}
export const enum NodeColor {
Black = 0,
Red = 1,
}
const enum Constants {
ColorMask = 0b00000001,
ColorMaskInverse = 0b11111110,
ColorOffset = 0,
IsVisitedMask = 0b00000010,
IsVisitedMaskInverse = 0b11111101,
IsVisitedOffset = 1,
IsForValidationMask = 0b00000100,
IsForValidationMaskInverse = 0b11111011,
IsForValidationOffset = 2,
IsInOverviewRulerMask = 0b00001000,
IsInOverviewRulerMaskInverse = 0b11110111,
IsInOverviewRulerOffset = 3,
StickinessMask = 0b00110000,
StickinessMaskInverse = 0b11001111,
StickinessOffset = 4,
CollapseOnReplaceEditMask = 0b01000000,
CollapseOnReplaceEditMaskInverse = 0b10111111,
CollapseOnReplaceEditOffset = 6,
/**
* Due to how deletion works (in order to avoid always walking the right subtree of the deleted node),
* the deltas for nodes can grow and shrink dramatically. It has been observed, in practice, that unless
* the deltas are corrected, integer overflow will occur.
*
* The integer overflow occurs when 53 bits are used in the numbers, but we will try to avoid it as
* a node's delta gets below a negative 30 bits number.
*
* MIN SMI (SMall Integer) as defined in v8.
* one bit is lost for boxing/unboxing flag.
* one bit is lost for sign flag.
* See https://thibaultlaurens.github.io/javascript/2013/04/29/how-the-v8-engine-works/#tagged-values
*/
MIN_SAFE_DELTA = -(1 << 30),
/**
* MAX SMI (SMall Integer) as defined in v8.
* one bit is lost for boxing/unboxing flag.
* one bit is lost for sign flag.
* See https://thibaultlaurens.github.io/javascript/2013/04/29/how-the-v8-engine-works/#tagged-values
*/
MAX_SAFE_DELTA = 1 << 30,
}
export function getNodeColor(node: IntervalNode): NodeColor {
return ((node.metadata & Constants.ColorMask) >>> Constants.ColorOffset);
}
function setNodeColor(node: IntervalNode, color: NodeColor): void {
node.metadata = (
(node.metadata & Constants.ColorMaskInverse) | (color << Constants.ColorOffset)
);
}
function getNodeIsVisited(node: IntervalNode): boolean {
return ((node.metadata & Constants.IsVisitedMask) >>> Constants.IsVisitedOffset) === 1;
}
function setNodeIsVisited(node: IntervalNode, value: boolean): void {
node.metadata = (
(node.metadata & Constants.IsVisitedMaskInverse) | ((value ? 1 : 0) << Constants.IsVisitedOffset)
);
}
function getNodeIsForValidation(node: IntervalNode): boolean {
return ((node.metadata & Constants.IsForValidationMask) >>> Constants.IsForValidationOffset) === 1;
}
function setNodeIsForValidation(node: IntervalNode, value: boolean): void {
node.metadata = (
(node.metadata & Constants.IsForValidationMaskInverse) | ((value ? 1 : 0) << Constants.IsForValidationOffset)
);
}
export function getNodeIsInOverviewRuler(node: IntervalNode): boolean {
return ((node.metadata & Constants.IsInOverviewRulerMask) >>> Constants.IsInOverviewRulerOffset) === 1;
}
function setNodeIsInOverviewRuler(node: IntervalNode, value: boolean): void {
node.metadata = (
(node.metadata & Constants.IsInOverviewRulerMaskInverse) | ((value ? 1 : 0) << Constants.IsInOverviewRulerOffset)
);
}
function getNodeStickiness(node: IntervalNode): TrackedRangeStickiness {
return ((node.metadata & Constants.StickinessMask) >>> Constants.StickinessOffset);
}
function _setNodeStickiness(node: IntervalNode, stickiness: TrackedRangeStickiness): void {
node.metadata = (
(node.metadata & Constants.StickinessMaskInverse) | (stickiness << Constants.StickinessOffset)
);
}
function getCollapseOnReplaceEdit(node: IntervalNode): boolean {
return ((node.metadata & Constants.CollapseOnReplaceEditMask) >>> Constants.CollapseOnReplaceEditOffset) === 1;
}
function setCollapseOnReplaceEdit(node: IntervalNode, value: boolean): void {
node.metadata = (
(node.metadata & Constants.CollapseOnReplaceEditMaskInverse) | ((value ? 1 : 0) << Constants.CollapseOnReplaceEditOffset)
);
}
export function setNodeStickiness(node: IntervalNode, stickiness: ActualTrackedRangeStickiness): void {
_setNodeStickiness(node, <number>stickiness);
}
export class IntervalNode implements IModelDecoration {
/**
* contains binary encoded information for color, visited, isForValidation and stickiness.
*/
public metadata: number;
public parent: IntervalNode;
public left: IntervalNode;
public right: IntervalNode;
public start: number;
public end: number;
public delta: number;
public maxEnd: number;
public id: string;
public ownerId: number;
public options: ModelDecorationOptions;
public cachedVersionId: number;
public cachedAbsoluteStart: number;
public cachedAbsoluteEnd: number;
public range: Range;
constructor(id: string, start: number, end: number) {
this.metadata = 0;
this.parent = this;
this.left = this;
this.right = this;
setNodeColor(this, NodeColor.Red);
this.start = start;
this.end = end;
// FORCE_OVERFLOWING_TEST: this.delta = start;
this.delta = 0;
this.maxEnd = end;
this.id = id;
this.ownerId = 0;
this.options = null!;
setNodeIsForValidation(this, false);
_setNodeStickiness(this, TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges);
setNodeIsInOverviewRuler(this, false);
setCollapseOnReplaceEdit(this, false);
this.cachedVersionId = 0;
this.cachedAbsoluteStart = start;
this.cachedAbsoluteEnd = end;
this.range = null!;
setNodeIsVisited(this, false);
}
public reset(versionId: number, start: number, end: number, range: Range): void {
this.start = start;
this.end = end;
this.maxEnd = end;
this.cachedVersionId = versionId;
this.cachedAbsoluteStart = start;
this.cachedAbsoluteEnd = end;
this.range = range;
}
public setOptions(options: ModelDecorationOptions) {
this.options = options;
let className = this.options.className;
setNodeIsForValidation(this, (
className === ClassName.EditorErrorDecoration
|| className === ClassName.EditorWarningDecoration
|| className === ClassName.EditorInfoDecoration
));
_setNodeStickiness(this, <number>this.options.stickiness);
setNodeIsInOverviewRuler(this, (this.options.overviewRuler && this.options.overviewRuler.color) ? true : false);
setCollapseOnReplaceEdit(this, this.options.collapseOnReplaceEdit);
}
public setCachedOffsets(absoluteStart: number, absoluteEnd: number, cachedVersionId: number): void {
if (this.cachedVersionId !== cachedVersionId) {
this.range = null!;
}
this.cachedVersionId = cachedVersionId;
this.cachedAbsoluteStart = absoluteStart;
this.cachedAbsoluteEnd = absoluteEnd;
}
public detach(): void {
this.parent = null!;
this.left = null!;
this.right = null!;
}
}
export const SENTINEL: IntervalNode = new IntervalNode(null!, 0, 0);
SENTINEL.parent = SENTINEL;
SENTINEL.left = SENTINEL;
SENTINEL.right = SENTINEL;
setNodeColor(SENTINEL, NodeColor.Black);
export class IntervalTree {
public root: IntervalNode;
public requestNormalizeDelta: boolean;
constructor() {
this.root = SENTINEL;
this.requestNormalizeDelta = false;
}
public intervalSearch(start: number, end: number, filterOwnerId: number, filterOutValidation: boolean, cachedVersionId: number): IntervalNode[] {
if (this.root === SENTINEL) {
return [];
}
return intervalSearch(this, start, end, filterOwnerId, filterOutValidation, cachedVersionId);
}
public search(filterOwnerId: number, filterOutValidation: boolean, cachedVersionId: number): IntervalNode[] {
if (this.root === SENTINEL) {
return [];
}
return search(this, filterOwnerId, filterOutValidation, cachedVersionId);
}
/**
* Will not set `cachedAbsoluteStart` nor `cachedAbsoluteEnd` on the returned nodes!
*/
public collectNodesFromOwner(ownerId: number): IntervalNode[] {
return collectNodesFromOwner(this, ownerId);
}
/**
* Will not set `cachedAbsoluteStart` nor `cachedAbsoluteEnd` on the returned nodes!
*/
public collectNodesPostOrder(): IntervalNode[] {
return collectNodesPostOrder(this);
}
public insert(node: IntervalNode): void {
rbTreeInsert(this, node);
this._normalizeDeltaIfNecessary();
}
public delete(node: IntervalNode): void {
rbTreeDelete(this, node);
this._normalizeDeltaIfNecessary();
}
public resolveNode(node: IntervalNode, cachedVersionId: number): void {
const initialNode = node;
let delta = 0;
while (node !== this.root) {
if (node === node.parent.right) {
delta += node.parent.delta;
}
node = node.parent;
}
const nodeStart = initialNode.start + delta;
const nodeEnd = initialNode.end + delta;
initialNode.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId);
}
public acceptReplace(offset: number, length: number, textLength: number, forceMoveMarkers: boolean): void {
// Our strategy is to remove all directly impacted nodes, and then add them back to the tree.
// (1) collect all nodes that are intersecting this edit as nodes of interest
const nodesOfInterest = searchForEditing(this, offset, offset + length);
// (2) remove all nodes that are intersecting this edit
for (let i = 0, len = nodesOfInterest.length; i < len; i++) {
const node = nodesOfInterest[i];
rbTreeDelete(this, node);
}
this._normalizeDeltaIfNecessary();
// (3) edit all tree nodes except the nodes of interest
noOverlapReplace(this, offset, offset + length, textLength);
this._normalizeDeltaIfNecessary();
// (4) edit the nodes of interest and insert them back in the tree
for (let i = 0, len = nodesOfInterest.length; i < len; i++) {
const node = nodesOfInterest[i];
node.start = node.cachedAbsoluteStart;
node.end = node.cachedAbsoluteEnd;
nodeAcceptEdit(node, offset, (offset + length), textLength, forceMoveMarkers);
node.maxEnd = node.end;
rbTreeInsert(this, node);
}
this._normalizeDeltaIfNecessary();
}
public getAllInOrder(): IntervalNode[] {
return search(this, 0, false, 0);
}
private _normalizeDeltaIfNecessary(): void {
if (!this.requestNormalizeDelta) {
return;
}
this.requestNormalizeDelta = false;
normalizeDelta(this);
}
}
//#region Delta Normalization
function normalizeDelta(T: IntervalTree): void {
let node = T.root;
let delta = 0;
while (node !== SENTINEL) {
if (node.left !== SENTINEL && !getNodeIsVisited(node.left)) {
// go left
node = node.left;
continue;
}
if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {
// go right
delta += node.delta;
node = node.right;
continue;
}
// handle current node
node.start = delta + node.start;
node.end = delta + node.end;
node.delta = 0;
recomputeMaxEnd(node);
setNodeIsVisited(node, true);
// going up from this node
setNodeIsVisited(node.left, false);
setNodeIsVisited(node.right, false);
if (node === node.parent.right) {
delta -= node.parent.delta;
}
node = node.parent;
}
setNodeIsVisited(T.root, false);
}
//#endregion
//#region Editing
const enum MarkerMoveSemantics {
MarkerDefined = 0,
ForceMove = 1,
ForceStay = 2
}
function adjustMarkerBeforeColumn(markerOffset: number, markerStickToPreviousCharacter: boolean, checkOffset: number, moveSemantics: MarkerMoveSemantics): boolean {
if (markerOffset < checkOffset) {
return true;
}
if (markerOffset > checkOffset) {
return false;
}
if (moveSemantics === MarkerMoveSemantics.ForceMove) {
return false;
}
if (moveSemantics === MarkerMoveSemantics.ForceStay) {
return true;
}
return markerStickToPreviousCharacter;
}
/**
* This is a lot more complicated than strictly necessary to maintain the same behaviour
* as when decorations were implemented using two markers.
*/
export function nodeAcceptEdit(node: IntervalNode, start: number, end: number, textLength: number, forceMoveMarkers: boolean): void {
const nodeStickiness = getNodeStickiness(node);
const startStickToPreviousCharacter = (
nodeStickiness === TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges
|| nodeStickiness === TrackedRangeStickiness.GrowsOnlyWhenTypingBefore
);
const endStickToPreviousCharacter = (
nodeStickiness === TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges
|| nodeStickiness === TrackedRangeStickiness.GrowsOnlyWhenTypingBefore
);
const deletingCnt = (end - start);
const insertingCnt = textLength;
const commonLength = Math.min(deletingCnt, insertingCnt);
const nodeStart = node.start;
let startDone = false;
const nodeEnd = node.end;
let endDone = false;
if (start <= nodeStart && nodeEnd <= end && getCollapseOnReplaceEdit(node)) {
// This edit encompasses the entire decoration range
// and the decoration has asked to become collapsed
node.start = start;
startDone = true;
node.end = start;
endDone = true;
}
{
const moveSemantics = forceMoveMarkers ? MarkerMoveSemantics.ForceMove : (deletingCnt > 0 ? MarkerMoveSemantics.ForceStay : MarkerMoveSemantics.MarkerDefined);
if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, start, moveSemantics)) {
startDone = true;
}
if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, start, moveSemantics)) {
endDone = true;
}
}
if (commonLength > 0 && !forceMoveMarkers) {
const moveSemantics = (deletingCnt > insertingCnt ? MarkerMoveSemantics.ForceStay : MarkerMoveSemantics.MarkerDefined);
if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, start + commonLength, moveSemantics)) {
startDone = true;
}
if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, start + commonLength, moveSemantics)) {
endDone = true;
}
}
{
const moveSemantics = forceMoveMarkers ? MarkerMoveSemantics.ForceMove : MarkerMoveSemantics.MarkerDefined;
if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, end, moveSemantics)) {
node.start = start + insertingCnt;
startDone = true;
}
if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, end, moveSemantics)) {
node.end = start + insertingCnt;
endDone = true;
}
}
// Finish
const deltaColumn = (insertingCnt - deletingCnt);
if (!startDone) {
node.start = Math.max(0, nodeStart + deltaColumn);
}
if (!endDone) {
node.end = Math.max(0, nodeEnd + deltaColumn);
}
if (node.start > node.end) {
node.end = node.start;
}
}
function searchForEditing(T: IntervalTree, start: number, end: number): IntervalNode[] {
// https://en.wikipedia.org/wiki/Interval_tree#Augmented_tree
// Now, it is known that two intervals A and B overlap only when both
// A.low <= B.high and A.high >= B.low. When searching the trees for
// nodes overlapping with a given interval, you can immediately skip:
// a) all nodes to the right of nodes whose low value is past the end of the given interval.
// b) all nodes that have their maximum 'high' value below the start of the given interval.
let node = T.root;
let delta = 0;
let nodeMaxEnd = 0;
let nodeStart = 0;
let nodeEnd = 0;
let result: IntervalNode[] = [];
let resultLen = 0;
while (node !== SENTINEL) {
if (getNodeIsVisited(node)) {
// going up from this node
setNodeIsVisited(node.left, false);
setNodeIsVisited(node.right, false);
if (node === node.parent.right) {
delta -= node.parent.delta;
}
node = node.parent;
continue;
}
if (!getNodeIsVisited(node.left)) {
// first time seeing this node
nodeMaxEnd = delta + node.maxEnd;
if (nodeMaxEnd < start) {
// cover case b) from above
// there is no need to search this node or its children
setNodeIsVisited(node, true);
continue;
}
if (node.left !== SENTINEL) {
// go left
node = node.left;
continue;
}
}
// handle current node
nodeStart = delta + node.start;
if (nodeStart > end) {
// cover case a) from above
// there is no need to search this node or its right subtree
setNodeIsVisited(node, true);
continue;
}
nodeEnd = delta + node.end;
if (nodeEnd >= start) {
node.setCachedOffsets(nodeStart, nodeEnd, 0);
result[resultLen++] = node;
}
setNodeIsVisited(node, true);
if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {
// go right
delta += node.delta;
node = node.right;
continue;
}
}
setNodeIsVisited(T.root, false);
return result;
}
function noOverlapReplace(T: IntervalTree, start: number, end: number, textLength: number): void {
// https://en.wikipedia.org/wiki/Interval_tree#Augmented_tree
// Now, it is known that two intervals A and B overlap only when both
// A.low <= B.high and A.high >= B.low. When searching the trees for
// nodes overlapping with a given interval, you can immediately skip:
// a) all nodes to the right of nodes whose low value is past the end of the given interval.
// b) all nodes that have their maximum 'high' value below the start of the given interval.
let node = T.root;
let delta = 0;
let nodeMaxEnd = 0;
let nodeStart = 0;
const editDelta = (textLength - (end - start));
while (node !== SENTINEL) {
if (getNodeIsVisited(node)) {
// going up from this node
setNodeIsVisited(node.left, false);
setNodeIsVisited(node.right, false);
if (node === node.parent.right) {
delta -= node.parent.delta;
}
recomputeMaxEnd(node);
node = node.parent;
continue;
}
if (!getNodeIsVisited(node.left)) {
// first time seeing this node
nodeMaxEnd = delta + node.maxEnd;
if (nodeMaxEnd < start) {
// cover case b) from above
// there is no need to search this node or its children
setNodeIsVisited(node, true);
continue;
}
if (node.left !== SENTINEL) {
// go left
node = node.left;
continue;
}
}
// handle current node
nodeStart = delta + node.start;
if (nodeStart > end) {
node.start += editDelta;
node.end += editDelta;
node.delta += editDelta;
if (node.delta < Constants.MIN_SAFE_DELTA || node.delta > Constants.MAX_SAFE_DELTA) {
T.requestNormalizeDelta = true;
}
// cover case a) from above
// there is no need to search this node or its right subtree
setNodeIsVisited(node, true);
continue;
}
setNodeIsVisited(node, true);
if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {
// go right
delta += node.delta;
node = node.right;
continue;
}
}
setNodeIsVisited(T.root, false);
}
//#endregion
//#region Searching
function collectNodesFromOwner(T: IntervalTree, ownerId: number): IntervalNode[] {
let node = T.root;
let result: IntervalNode[] = [];
let resultLen = 0;
while (node !== SENTINEL) {
if (getNodeIsVisited(node)) {
// going up from this node
setNodeIsVisited(node.left, false);
setNodeIsVisited(node.right, false);
node = node.parent;
continue;
}
if (node.left !== SENTINEL && !getNodeIsVisited(node.left)) {
// go left
node = node.left;
continue;
}
// handle current node
if (node.ownerId === ownerId) {
result[resultLen++] = node;
}
setNodeIsVisited(node, true);
if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {
// go right
node = node.right;
continue;
}
}
setNodeIsVisited(T.root, false);
return result;
}
function collectNodesPostOrder(T: IntervalTree): IntervalNode[] {
let node = T.root;
let result: IntervalNode[] = [];
let resultLen = 0;
while (node !== SENTINEL) {
if (getNodeIsVisited(node)) {
// going up from this node
setNodeIsVisited(node.left, false);
setNodeIsVisited(node.right, false);
node = node.parent;
continue;
}
if (node.left !== SENTINEL && !getNodeIsVisited(node.left)) {
// go left
node = node.left;
continue;
}
if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {
// go right
node = node.right;
continue;
}
// handle current node
result[resultLen++] = node;
setNodeIsVisited(node, true);
}
setNodeIsVisited(T.root, false);
return result;
}
function search(T: IntervalTree, filterOwnerId: number, filterOutValidation: boolean, cachedVersionId: number): IntervalNode[] {
let node = T.root;
let delta = 0;
let nodeStart = 0;
let nodeEnd = 0;
let result: IntervalNode[] = [];
let resultLen = 0;
while (node !== SENTINEL) {
if (getNodeIsVisited(node)) {
// going up from this node
setNodeIsVisited(node.left, false);
setNodeIsVisited(node.right, false);
if (node === node.parent.right) {
delta -= node.parent.delta;
}
node = node.parent;
continue;
}
if (node.left !== SENTINEL && !getNodeIsVisited(node.left)) {
// go left
node = node.left;
continue;
}
// handle current node
nodeStart = delta + node.start;
nodeEnd = delta + node.end;
node.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId);
let include = true;
if (filterOwnerId && node.ownerId && node.ownerId !== filterOwnerId) {
include = false;
}
if (filterOutValidation && getNodeIsForValidation(node)) {
include = false;
}
if (include) {
result[resultLen++] = node;
}
setNodeIsVisited(node, true);
if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {
// go right
delta += node.delta;
node = node.right;
continue;
}
}
setNodeIsVisited(T.root, false);
return result;
}
function intervalSearch(T: IntervalTree, intervalStart: number, intervalEnd: number, filterOwnerId: number, filterOutValidation: boolean, cachedVersionId: number): IntervalNode[] {
// https://en.wikipedia.org/wiki/Interval_tree#Augmented_tree
// Now, it is known that two intervals A and B overlap only when both
// A.low <= B.high and A.high >= B.low. When searching the trees for
// nodes overlapping with a given interval, you can immediately skip:
// a) all nodes to the right of nodes whose low value is past the end of the given interval.
// b) all nodes that have their maximum 'high' value below the start of the given interval.
let node = T.root;
let delta = 0;
let nodeMaxEnd = 0;
let nodeStart = 0;
let nodeEnd = 0;
let result: IntervalNode[] = [];
let resultLen = 0;
while (node !== SENTINEL) {
if (getNodeIsVisited(node)) {
// going up from this node
setNodeIsVisited(node.left, false);
setNodeIsVisited(node.right, false);
if (node === node.parent.right) {
delta -= node.parent.delta;
}
node = node.parent;
continue;
}
if (!getNodeIsVisited(node.left)) {
// first time seeing this node
nodeMaxEnd = delta + node.maxEnd;
if (nodeMaxEnd < intervalStart) {
// cover case b) from above
// there is no need to search this node or its children
setNodeIsVisited(node, true);
continue;
}
if (node.left !== SENTINEL) {
// go left
node = node.left;
continue;
}
}
// handle current node
nodeStart = delta + node.start;
if (nodeStart > intervalEnd) {
// cover case a) from above
// there is no need to search this node or its right subtree
setNodeIsVisited(node, true);
continue;
}
nodeEnd = delta + node.end;
if (nodeEnd >= intervalStart) {
// There is overlap
node.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId);
let include = true;
if (filterOwnerId && node.ownerId && node.ownerId !== filterOwnerId) {
include = false;
}
if (filterOutValidation && getNodeIsForValidation(node)) {
include = false;
}
if (include) {
result[resultLen++] = node;
}
}
setNodeIsVisited(node, true);
if (node.right !== SENTINEL && !getNodeIsVisited(node.right)) {
// go right
delta += node.delta;
node = node.right;
continue;
}
}
setNodeIsVisited(T.root, false);
return result;
}
//#endregion
//#region Insertion
function rbTreeInsert(T: IntervalTree, newNode: IntervalNode): IntervalNode {
if (T.root === SENTINEL) {
newNode.parent = SENTINEL;
newNode.left = SENTINEL;
newNode.right = SENTINEL;
setNodeColor(newNode, NodeColor.Black);
T.root = newNode;
return T.root;
}
treeInsert(T, newNode);
recomputeMaxEndWalkToRoot(newNode.parent);
// repair tree
let x = newNode;
while (x !== T.root && getNodeColor(x.parent) === NodeColor.Red) {
if (x.parent === x.parent.parent.left) {
const y = x.parent.parent.right;
if (getNodeColor(y) === NodeColor.Red) {
setNodeColor(x.parent, NodeColor.Black);
setNodeColor(y, NodeColor.Black);
setNodeColor(x.parent.parent, NodeColor.Red);
x = x.parent.parent;
} else {
if (x === x.parent.right) {
x = x.parent;
leftRotate(T, x);
}
setNodeColor(x.parent, NodeColor.Black);
setNodeColor(x.parent.parent, NodeColor.Red);
rightRotate(T, x.parent.parent);
}
} else {
const y = x.parent.parent.left;
if (getNodeColor(y) === NodeColor.Red) {
setNodeColor(x.parent, NodeColor.Black);
setNodeColor(y, NodeColor.Black);
setNodeColor(x.parent.parent, NodeColor.Red);
x = x.parent.parent;
} else {
if (x === x.parent.left) {
x = x.parent;
rightRotate(T, x);
}
setNodeColor(x.parent, NodeColor.Black);
setNodeColor(x.parent.parent, NodeColor.Red);
leftRotate(T, x.parent.parent);
}
}
}
setNodeColor(T.root, NodeColor.Black);
return newNode;
}
function treeInsert(T: IntervalTree, z: IntervalNode): void {
let delta: number = 0;
let x = T.root;
const zAbsoluteStart = z.start;
const zAbsoluteEnd = z.end;
while (true) {
const cmp = intervalCompare(zAbsoluteStart, zAbsoluteEnd, x.start + delta, x.end + delta);
if (cmp < 0) {
// this node should be inserted to the left
// => it is not affected by the node's delta
if (x.left === SENTINEL) {
z.start -= delta;
z.end -= delta;
z.maxEnd -= delta;
x.left = z;
break;
} else {
x = x.left;
}
} else {
// this node should be inserted to the right
// => it is not affected by the node's delta
if (x.right === SENTINEL) {
z.start -= (delta + x.delta);
z.end -= (delta + x.delta);
z.maxEnd -= (delta + x.delta);
x.right = z;
break;
} else {
delta += x.delta;
x = x.right;
}
}
}
z.parent = x;
z.left = SENTINEL;
z.right = SENTINEL;
setNodeColor(z, NodeColor.Red);
}
//#endregion
//#region Deletion
function rbTreeDelete(T: IntervalTree, z: IntervalNode): void {
let x: IntervalNode;
let y: IntervalNode;
// RB-DELETE except we don't swap z and y in case c)
// i.e. we always delete what's pointed at by z.
if (z.left === SENTINEL) {
x = z.right;
y = z;
// x's delta is no longer influenced by z's delta
x.delta += z.delta;
if (x.delta < Constants.MIN_SAFE_DELTA || x.delta > Constants.MAX_SAFE_DELTA) {
T.requestNormalizeDelta = true;
}
x.start += z.delta;
x.end += z.delta;
} else if (z.right === SENTINEL) {
x = z.left;
y = z;
} else {
y = leftest(z.right);
x = y.right;
// y's delta is no longer influenced by z's delta,
// but we don't want to walk the entire right-hand-side subtree of x.
// we therefore maintain z's delta in y, and adjust only x
x.start += y.delta;
x.end += y.delta;
x.delta += y.delta;
if (x.delta < Constants.MIN_SAFE_DELTA || x.delta > Constants.MAX_SAFE_DELTA) {
T.requestNormalizeDelta = true;
}
y.start += z.delta;
y.end += z.delta;
y.delta = z.delta;
if (y.delta < Constants.MIN_SAFE_DELTA || y.delta > Constants.MAX_SAFE_DELTA) {
T.requestNormalizeDelta = true;
}
}
if (y === T.root) {
T.root = x;
setNodeColor(x, NodeColor.Black);
z.detach();
resetSentinel();
recomputeMaxEnd(x);
T.root.parent = SENTINEL;
return;
}
let yWasRed = (getNodeColor(y) === NodeColor.Red);
if (y === y.parent.left) {
y.parent.left = x;
} else {
y.parent.right = x;
}
if (y === z) {
x.parent = y.parent;
} else {
if (y.parent === z) {
x.parent = y;
} else {
x.parent = y.parent;
}
y.left = z.left;
y.right = z.right;
y.parent = z.parent;
setNodeColor(y, getNodeColor(z));
if (z === T.root) {
T.root = y;
} else {
if (z === z.parent.left) {
z.parent.left = y;
} else {
z.parent.right = y;
}
}
if (y.left !== SENTINEL) {
y.left.parent = y;
}
if (y.right !== SENTINEL) {
y.right.parent = y;
}
}
z.detach();
if (yWasRed) {
recomputeMaxEndWalkToRoot(x.parent);
if (y !== z) {
recomputeMaxEndWalkToRoot(y);
recomputeMaxEndWalkToRoot(y.parent);
}
resetSentinel();
return;
}
recomputeMaxEndWalkToRoot(x);
recomputeMaxEndWalkToRoot(x.parent);
if (y !== z) {
recomputeMaxEndWalkToRoot(y);
recomputeMaxEndWalkToRoot(y.parent);
}
// RB-DELETE-FIXUP
let w: IntervalNode;
while (x !== T.root && getNodeColor(x) === NodeColor.Black) {
if (x === x.parent.left) {
w = x.parent.right;
if (getNodeColor(w) === NodeColor.Red) {
setNodeColor(w, NodeColor.Black);
setNodeColor(x.parent, NodeColor.Red);
leftRotate(T, x.parent);
w = x.parent.right;
}
if (getNodeColor(w.left) === NodeColor.Black && getNodeColor(w.right) === NodeColor.Black) {
setNodeColor(w, NodeColor.Red);
x = x.parent;
} else {
if (getNodeColor(w.right) === NodeColor.Black) {
setNodeColor(w.left, NodeColor.Black);
setNodeColor(w, NodeColor.Red);
rightRotate(T, w);
w = x.parent.right;
}
setNodeColor(w, getNodeColor(x.parent));
setNodeColor(x.parent, NodeColor.Black);
setNodeColor(w.right, NodeColor.Black);
leftRotate(T, x.parent);
x = T.root;
}
} else {
w = x.parent.left;
if (getNodeColor(w) === NodeColor.Red) {
setNodeColor(w, NodeColor.Black);
setNodeColor(x.parent, NodeColor.Red);
rightRotate(T, x.parent);
w = x.parent.left;
}
if (getNodeColor(w.left) === NodeColor.Black && getNodeColor(w.right) === NodeColor.Black) {
setNodeColor(w, NodeColor.Red);
x = x.parent;
} else {
if (getNodeColor(w.left) === NodeColor.Black) {
setNodeColor(w.right, NodeColor.Black);
setNodeColor(w, NodeColor.Red);
leftRotate(T, w);
w = x.parent.left;
}
setNodeColor(w, getNodeColor(x.parent));
setNodeColor(x.parent, NodeColor.Black);
setNodeColor(w.left, NodeColor.Black);
rightRotate(T, x.parent);
x = T.root;
}
}
}
setNodeColor(x, NodeColor.Black);
resetSentinel();
}
function leftest(node: IntervalNode): IntervalNode {
while (node.left !== SENTINEL) {
node = node.left;
}
return node;
}
function resetSentinel(): void {
SENTINEL.parent = SENTINEL;
SENTINEL.delta = 0; // optional
SENTINEL.start = 0; // optional
SENTINEL.end = 0; // optional
}
//#endregion
//#region Rotations
function leftRotate(T: IntervalTree, x: IntervalNode): void {
const y = x.right; // set y.
y.delta += x.delta; // y's delta is no longer influenced by x's delta
if (y.delta < Constants.MIN_SAFE_DELTA || y.delta > Constants.MAX_SAFE_DELTA) {
T.requestNormalizeDelta = true;
}
y.start += x.delta;
y.end += x.delta;
x.right = y.left; // turn y's left subtree into x's right subtree.
if (y.left !== SENTINEL) {
y.left.parent = x;
}
y.parent = x.parent; // link x's parent to y.
if (x.parent === SENTINEL) {
T.root = y;
} else if (x === x.parent.left) {
x.parent.left = y;
} else {
x.parent.right = y;
}
y.left = x; // put x on y's left.
x.parent = y;
recomputeMaxEnd(x);
recomputeMaxEnd(y);
}
function rightRotate(T: IntervalTree, y: IntervalNode): void {
const x = y.left;
y.delta -= x.delta;
if (y.delta < Constants.MIN_SAFE_DELTA || y.delta > Constants.MAX_SAFE_DELTA) {
T.requestNormalizeDelta = true;
}
y.start -= x.delta;
y.end -= x.delta;
y.left = x.right;
if (x.right !== SENTINEL) {
x.right.parent = y;
}
x.parent = y.parent;
if (y.parent === SENTINEL) {
T.root = x;
} else if (y === y.parent.right) {
y.parent.right = x;
} else {
y.parent.left = x;
}
x.right = y;
y.parent = x;
recomputeMaxEnd(y);
recomputeMaxEnd(x);
}
//#endregion
//#region max end computation
function computeMaxEnd(node: IntervalNode): number {
let maxEnd = node.end;
if (node.left !== SENTINEL) {
const leftMaxEnd = node.left.maxEnd;
if (leftMaxEnd > maxEnd) {
maxEnd = leftMaxEnd;
}
}
if (node.right !== SENTINEL) {
const rightMaxEnd = node.right.maxEnd + node.delta;
if (rightMaxEnd > maxEnd) {
maxEnd = rightMaxEnd;
}
}
return maxEnd;
}
export function recomputeMaxEnd(node: IntervalNode): void {
node.maxEnd = computeMaxEnd(node);
}
function recomputeMaxEndWalkToRoot(node: IntervalNode): void {
while (node !== SENTINEL) {
const maxEnd = computeMaxEnd(node);
if (node.maxEnd === maxEnd) {
// no need to go further
return;
}
node.maxEnd = maxEnd;
node = node.parent;
}
}
//#endregion
//#region utils
export function intervalCompare(aStart: number, aEnd: number, bStart: number, bEnd: number): number {
if (aStart === bStart) {
return aEnd - bEnd;
}
return aStart - bStart;
}
//#endregion
| src/vs/editor/common/model/intervalTree.ts | 0 | https://github.com/microsoft/vscode/commit/c0efffc91f0c4cd10e70f30229f19da96a50f960 | [
0.0002236011205241084,
0.00017242769536096603,
0.00015992259432096034,
0.00017291918629780412,
0.0000058551809161144774
] |
{
"id": 3,
"code_window": [
"\t\t\t\t\tcontinue;\n",
"\t\t\t\t}\n",
"\t\t\t}\n",
"\n",
"\t\t\tcompressedEdits.push(editData.edits[i]);\n",
"\t\t\tcompressedEditsIndex++;\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tif (prev.editType === CellEditType.Delete && editData.edits[i].editType === CellEditType.Delete) {\n",
"\t\t\t\tif (prev.index === editData.edits[i].index) {\n",
"\t\t\t\t\tprev.count += (editData.edits[i] as ICellDeleteEdit).count;\n",
"\t\t\t\t\tcontinue;\n",
"\t\t\t\t}\n",
"\t\t\t}\n",
"\n"
],
"file_path": "src/vs/workbench/api/common/extHostNotebook.ts",
"type": "add",
"edit_start_line_idx": 503
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { readonly } from 'vs/base/common/errors';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import { ISplice } from 'vs/base/common/sequence';
import { URI, UriComponents } from 'vs/base/common/uri';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { CellKind, CellOutputKind, ExtHostNotebookShape, IMainContext, MainContext, MainThreadNotebookShape, NotebookCellOutputsSplice } from 'vs/workbench/api/common/extHost.protocol';
import { ExtHostCommands } from 'vs/workbench/api/common/extHostCommands';
import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors';
import { CellEditType, CellUri, diff, ICellEditOperation, ICellInsertEdit, IErrorOutput, INotebookDisplayOrder, INotebookEditData, IOrderedMimeType, IStreamOutput, ITransformedDisplayOutputDto, mimeTypeSupportedByCore, NotebookCellsChangedEvent, NotebookCellsSplice2, sortMimeTypes } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { Disposable as VSCodeDisposable } from './extHostTypes';
interface IObservable<T> {
proxy: T;
onDidChange: Event<void>;
}
function getObservable<T extends Object>(obj: T): IObservable<T> {
const onDidChange = new Emitter<void>();
const proxy = new Proxy(obj, {
set(target: T, p: PropertyKey, value: any, _receiver: any): boolean {
target[p as keyof T] = value;
onDidChange.fire();
return true;
}
});
return {
proxy,
onDidChange: onDidChange.event
};
}
const notebookDocumentMetadataDefaults: vscode.NotebookDocumentMetadata = {
editable: true,
cellEditable: true,
cellRunnable: true
};
export class ExtHostCell extends Disposable implements vscode.NotebookCell {
private originalSource: string[];
private _outputs: any[];
private _onDidChangeOutputs = new Emitter<ISplice<vscode.CellOutput>[]>();
onDidChangeOutputs: Event<ISplice<vscode.CellOutput>[]> = this._onDidChangeOutputs.event;
private _textDocument: vscode.TextDocument | undefined;
private _initalVersion: number = -1;
private _outputMapping = new Set<vscode.CellOutput>();
private _metadata: vscode.NotebookCellMetadata;
private _metadataChangeListener: IDisposable;
get source() {
if (this._textDocument && this._initalVersion !== this._textDocument?.version) {
return this._textDocument.getText();
} else {
return this.originalSource.join('\n');
}
}
constructor(
private viewType: string,
private documentUri: URI,
readonly handle: number,
readonly uri: URI,
private _content: string,
public readonly cellKind: CellKind,
public language: string,
outputs: any[],
_metadata: vscode.NotebookCellMetadata | undefined,
private _proxy: MainThreadNotebookShape
) {
super();
this.originalSource = this._content.split(/\r|\n|\r\n/g);
this._outputs = outputs;
const observableMetadata = getObservable(_metadata || {} as any);
this._metadata = observableMetadata.proxy;
this._metadataChangeListener = this._register(observableMetadata.onDidChange(() => {
this.updateMetadata();
}));
}
get outputs() {
return this._outputs;
}
set outputs(newOutputs: vscode.CellOutput[]) {
let diffs = diff<vscode.CellOutput>(this._outputs || [], newOutputs || [], (a) => {
return this._outputMapping.has(a);
});
diffs.forEach(diff => {
for (let i = diff.start; i < diff.start + diff.deleteCount; i++) {
this._outputMapping.delete(this._outputs[i]);
}
diff.toInsert.forEach(output => {
this._outputMapping.add(output);
});
});
this._outputs = newOutputs;
this._onDidChangeOutputs.fire(diffs);
}
get metadata() {
return this._metadata;
}
set metadata(newMetadata: vscode.NotebookCellMetadata) {
this._metadataChangeListener.dispose();
const observableMetadata = getObservable(newMetadata || {} as any); // TODO defaults
this._metadata = observableMetadata.proxy;
this._metadataChangeListener = this._register(observableMetadata.onDidChange(() => {
this.updateMetadata();
}));
this.updateMetadata();
}
private updateMetadata(): Promise<void> {
return this._proxy.$updateNotebookCellMetadata(this.viewType, this.documentUri, this.handle, this._metadata);
}
getContent(): string {
if (this._textDocument && this._initalVersion !== this._textDocument?.version) {
return this._textDocument.getText();
} else {
return this.originalSource.join('\n');
}
}
attachTextDocument(document: vscode.TextDocument) {
this._textDocument = document;
this._initalVersion = this._textDocument.version;
}
detachTextDocument() {
if (this._textDocument && this._textDocument.version !== this._initalVersion) {
this.originalSource = this._textDocument.getText().split(/\r|\n|\r\n/g);
}
this._textDocument = undefined;
this._initalVersion = -1;
}
}
export class ExtHostNotebookDocument extends Disposable implements vscode.NotebookDocument {
private static _handlePool: number = 0;
readonly handle = ExtHostNotebookDocument._handlePool++;
private _cells: ExtHostCell[] = [];
private _cellDisposableMapping = new Map<number, DisposableStore>();
get cells() {
return this._cells;
}
private _languages: string[] = [];
get languages() {
return this._languages = [];
}
set languages(newLanguages: string[]) {
this._languages = newLanguages;
this._proxy.$updateNotebookLanguages(this.viewType, this.uri, this._languages);
}
private _metadata: vscode.NotebookDocumentMetadata | undefined = notebookDocumentMetadataDefaults;
get metadata() {
return this._metadata;
}
set metadata(newMetadata: vscode.NotebookDocumentMetadata | undefined) {
this._metadata = newMetadata || notebookDocumentMetadataDefaults;
this._proxy.$updateNotebookMetadata(this.viewType, this.uri, this._metadata);
}
private _displayOrder: string[] = [];
get displayOrder() {
return this._displayOrder;
}
set displayOrder(newOrder: string[]) {
this._displayOrder = newOrder;
}
private _versionId = 0;
get versionId() {
return this._versionId;
}
constructor(
private readonly _proxy: MainThreadNotebookShape,
private _documentsAndEditors: ExtHostDocumentsAndEditors,
public viewType: string,
public uri: URI,
public renderingHandler: ExtHostNotebookOutputRenderingHandler
) {
super();
}
dispose() {
super.dispose();
this._cellDisposableMapping.forEach(cell => cell.dispose());
}
get fileName() { return this.uri.fsPath; }
get isDirty() { return false; }
accpetModelChanged(event: NotebookCellsChangedEvent) {
this.$spliceNotebookCells(event.changes);
this._versionId = event.versionId;
}
private $spliceNotebookCells(splices: NotebookCellsSplice2[]): void {
if (!splices.length) {
return;
}
splices.reverse().forEach(splice => {
let cellDtos = splice[2];
let newCells = cellDtos.map(cell => {
const extCell = new ExtHostCell(this.viewType, this.uri, cell.handle, URI.revive(cell.uri), cell.source.join('\n'), cell.cellKind, cell.language, cell.outputs, cell.metadata, this._proxy);
const document = this._documentsAndEditors.getDocument(URI.revive(cell.uri));
if (document) {
extCell.attachTextDocument(document.document);
}
if (!this._cellDisposableMapping.has(extCell.handle)) {
this._cellDisposableMapping.set(extCell.handle, new DisposableStore());
}
let store = this._cellDisposableMapping.get(extCell.handle)!;
store.add(extCell.onDidChangeOutputs((diffs) => {
this.eventuallyUpdateCellOutputs(extCell, diffs);
}));
return extCell;
});
for (let j = splice[0]; j < splice[0] + splice[1]; j++) {
this._cellDisposableMapping.get(this.cells[j].handle)?.dispose();
this._cellDisposableMapping.delete(this.cells[j].handle);
}
this.cells.splice(splice[0], splice[1], ...newCells);
});
}
eventuallyUpdateCellOutputs(cell: ExtHostCell, diffs: ISplice<vscode.CellOutput>[]) {
let renderers = new Set<number>();
let outputDtos: NotebookCellOutputsSplice[] = diffs.map(diff => {
let outputs = diff.toInsert;
let transformedOutputs = outputs.map(output => {
if (output.outputKind === CellOutputKind.Rich) {
const ret = this.transformMimeTypes(output);
if (ret.orderedMimeTypes[ret.pickedMimeTypeIndex].isResolved) {
renderers.add(ret.orderedMimeTypes[ret.pickedMimeTypeIndex].rendererId!);
}
return ret;
} else {
return output as IStreamOutput | IErrorOutput;
}
});
return [diff.start, diff.deleteCount, transformedOutputs];
});
this._proxy.$spliceNotebookCellOutputs(this.viewType, this.uri, cell.handle, outputDtos, Array.from(renderers));
}
transformMimeTypes(output: vscode.CellDisplayOutput): ITransformedDisplayOutputDto {
let mimeTypes = Object.keys(output.data);
// TODO@rebornix, the document display order might be assigned a bit later. We need to postpone sending the outputs to the core side.
let coreDisplayOrder = this.renderingHandler.outputDisplayOrder;
const sorted = sortMimeTypes(mimeTypes, coreDisplayOrder?.userOrder || [], this._displayOrder, coreDisplayOrder?.defaultOrder || []);
let orderMimeTypes: IOrderedMimeType[] = [];
sorted.forEach(mimeType => {
let handlers = this.renderingHandler.findBestMatchedRenderer(mimeType);
if (handlers.length) {
let renderedOutput = handlers[0].render(this, output, mimeType);
orderMimeTypes.push({
mimeType: mimeType,
isResolved: true,
rendererId: handlers[0].handle,
output: renderedOutput
});
for (let i = 1; i < handlers.length; i++) {
orderMimeTypes.push({
mimeType: mimeType,
isResolved: false,
rendererId: handlers[i].handle
});
}
if (mimeTypeSupportedByCore(mimeType)) {
orderMimeTypes.push({
mimeType: mimeType,
isResolved: false,
rendererId: -1
});
}
} else {
orderMimeTypes.push({
mimeType: mimeType,
isResolved: false
});
}
});
return {
outputKind: output.outputKind,
data: output.data,
orderedMimeTypes: orderMimeTypes,
pickedMimeTypeIndex: 0
};
}
getCell(cellHandle: number) {
return this.cells.find(cell => cell.handle === cellHandle);
}
attachCellTextDocument(textDocument: vscode.TextDocument) {
let cell = this.cells.find(cell => cell.uri.toString() === textDocument.uri.toString());
if (cell) {
cell.attachTextDocument(textDocument);
}
}
detachCellTextDocument(textDocument: vscode.TextDocument) {
let cell = this.cells.find(cell => cell.uri.toString() === textDocument.uri.toString());
if (cell) {
cell.detachTextDocument();
}
}
}
export class NotebookEditorCellEdit {
private _finalized: boolean = false;
private readonly _documentVersionId: number;
private _collectedEdits: ICellEditOperation[] = [];
private _renderers = new Set<number>();
constructor(
readonly editor: ExtHostNotebookEditor
) {
this._documentVersionId = editor.document.versionId;
}
finalize(): INotebookEditData {
this._finalized = true;
return {
documentVersionId: this._documentVersionId,
edits: this._collectedEdits,
renderers: Array.from(this._renderers)
};
}
private _throwIfFinalized() {
if (this._finalized) {
throw new Error('Edit is only valid while callback runs');
}
}
insert(index: number, content: string, language: string, type: CellKind, outputs: vscode.CellOutput[], metadata: vscode.NotebookCellMetadata | undefined): void {
this._throwIfFinalized();
let cell = {
source: [content],
language,
cellKind: type,
outputs: (outputs as any[]), // TODO@rebornix
metadata
};
const transformedOutputs = outputs.map(output => {
if (output.outputKind === CellOutputKind.Rich) {
const ret = this.editor.document.transformMimeTypes(output);
if (ret.orderedMimeTypes[ret.pickedMimeTypeIndex].isResolved) {
this._renderers.add(ret.orderedMimeTypes[ret.pickedMimeTypeIndex].rendererId!);
}
return ret;
} else {
return output as IStreamOutput | IErrorOutput;
}
});
cell.outputs = transformedOutputs;
this._collectedEdits.push({
editType: CellEditType.Insert,
index,
cells: [cell]
});
}
delete(index: number): void {
this._throwIfFinalized();
this._collectedEdits.push({
editType: CellEditType.Delete,
index
});
}
}
export class ExtHostNotebookEditor extends Disposable implements vscode.NotebookEditor {
private _viewColumn: vscode.ViewColumn | undefined;
onDidReceiveMessage: vscode.Event<any> = this._onDidReceiveMessage.event;
constructor(
private readonly viewType: string,
readonly id: string,
public uri: URI,
private _proxy: MainThreadNotebookShape,
private _onDidReceiveMessage: Emitter<any>,
public document: ExtHostNotebookDocument,
private _documentsAndEditors: ExtHostDocumentsAndEditors
) {
super();
this._register(this._documentsAndEditors.onDidAddDocuments(documents => {
for (const { document: textDocument } of documents) {
let data = CellUri.parse(textDocument.uri);
if (data) {
if (this.document.uri.toString() === data.notebook.toString()) {
document.attachCellTextDocument(textDocument);
}
}
}
}));
this._register(this._documentsAndEditors.onDidRemoveDocuments(documents => {
for (const { document: textDocument } of documents) {
let data = CellUri.parse(textDocument.uri);
if (data) {
if (this.document.uri.toString() === data.notebook.toString()) {
document.detachCellTextDocument(textDocument);
}
}
}
}));
}
edit(callback: (editBuilder: NotebookEditorCellEdit) => void): Thenable<boolean> {
const edit = new NotebookEditorCellEdit(this);
callback(edit);
return this._applyEdit(edit);
}
private _applyEdit(editBuilder: NotebookEditorCellEdit): Promise<boolean> {
const editData = editBuilder.finalize();
// return when there is nothing to do
if (editData.edits.length === 0) {
return Promise.resolve(true);
}
let compressedEdits: ICellEditOperation[] = [];
let compressedEditsIndex = -1;
for (let i = 0; i < editData.edits.length; i++) {
if (compressedEditsIndex < 0) {
compressedEdits.push(editData.edits[i]);
compressedEditsIndex++;
continue;
}
let prevIndex = compressedEditsIndex;
let prev = compressedEdits[prevIndex];
if (prev.editType === CellEditType.Insert && editData.edits[i].editType === CellEditType.Insert) {
if (prev.index + prev.cells.length === editData.edits[i].index) {
prev.cells.push(...(editData.edits[i] as ICellInsertEdit).cells);
continue;
}
}
compressedEdits.push(editData.edits[i]);
compressedEditsIndex++;
}
return this._proxy.$tryApplyEdits(this.viewType, this.uri, editData.documentVersionId, compressedEdits, editData.renderers);
}
get viewColumn(): vscode.ViewColumn | undefined {
return this._viewColumn;
}
set viewColumn(value) {
throw readonly('viewColumn');
}
async postMessage(message: any): Promise<boolean> {
return this._proxy.$postMessage(this.document.handle, message);
}
}
export class ExtHostNotebookOutputRenderer {
private static _handlePool: number = 0;
readonly handle = ExtHostNotebookOutputRenderer._handlePool++;
constructor(
public type: string,
public filter: vscode.NotebookOutputSelector,
public renderer: vscode.NotebookOutputRenderer
) {
}
matches(mimeType: string): boolean {
if (this.filter.subTypes) {
if (this.filter.subTypes.indexOf(mimeType) >= 0) {
return true;
}
}
return false;
}
render(document: ExtHostNotebookDocument, output: vscode.CellOutput, mimeType: string): string {
let html = this.renderer.render(document, output, mimeType);
return html;
}
}
export interface ExtHostNotebookOutputRenderingHandler {
outputDisplayOrder: INotebookDisplayOrder | undefined;
findBestMatchedRenderer(mimeType: string): ExtHostNotebookOutputRenderer[];
}
export class ExtHostNotebookController implements ExtHostNotebookShape, ExtHostNotebookOutputRenderingHandler {
private static _handlePool: number = 0;
private readonly _proxy: MainThreadNotebookShape;
private readonly _notebookProviders = new Map<string, { readonly provider: vscode.NotebookProvider, readonly extension: IExtensionDescription; }>();
private readonly _documents = new Map<string, ExtHostNotebookDocument>();
private readonly _editors = new Map<string, { editor: ExtHostNotebookEditor, onDidReceiveMessage: Emitter<any> }>();
private readonly _notebookOutputRenderers = new Map<number, ExtHostNotebookOutputRenderer>();
private _outputDisplayOrder: INotebookDisplayOrder | undefined;
get outputDisplayOrder(): INotebookDisplayOrder | undefined {
return this._outputDisplayOrder;
}
private _activeNotebookDocument: ExtHostNotebookDocument | undefined;
get activeNotebookDocument() {
return this._activeNotebookDocument;
}
constructor(mainContext: IMainContext, commands: ExtHostCommands, private _documentsAndEditors: ExtHostDocumentsAndEditors) {
this._proxy = mainContext.getProxy(MainContext.MainThreadNotebook);
commands.registerArgumentProcessor({
processArgument: arg => {
if (arg && arg.$mid === 12) {
const documentHandle = arg.notebookEditor?.notebookHandle;
const cellHandle = arg.cell.handle;
for (let value of this._editors) {
if (value[1].editor.document.handle === documentHandle) {
const cell = value[1].editor.document.getCell(cellHandle);
if (cell) {
return cell;
}
}
}
}
return arg;
}
});
}
registerNotebookOutputRenderer(
type: string,
extension: IExtensionDescription,
filter: vscode.NotebookOutputSelector,
renderer: vscode.NotebookOutputRenderer
): vscode.Disposable {
let extHostRenderer = new ExtHostNotebookOutputRenderer(type, filter, renderer);
this._notebookOutputRenderers.set(extHostRenderer.handle, extHostRenderer);
this._proxy.$registerNotebookRenderer({ id: extension.identifier, location: extension.extensionLocation }, type, filter, extHostRenderer.handle, renderer.preloads || []);
return new VSCodeDisposable(() => {
this._notebookOutputRenderers.delete(extHostRenderer.handle);
this._proxy.$unregisterNotebookRenderer(extHostRenderer.handle);
});
}
findBestMatchedRenderer(mimeType: string): ExtHostNotebookOutputRenderer[] {
let matches: ExtHostNotebookOutputRenderer[] = [];
for (let renderer of this._notebookOutputRenderers) {
if (renderer[1].matches(mimeType)) {
matches.push(renderer[1]);
}
}
return matches;
}
registerNotebookProvider(
extension: IExtensionDescription,
viewType: string,
provider: vscode.NotebookProvider,
): vscode.Disposable {
if (this._notebookProviders.has(viewType)) {
throw new Error(`Notebook provider for '${viewType}' already registered`);
}
this._notebookProviders.set(viewType, { extension, provider });
this._proxy.$registerNotebookProvider({ id: extension.identifier, location: extension.extensionLocation }, viewType);
return new VSCodeDisposable(() => {
this._notebookProviders.delete(viewType);
this._proxy.$unregisterNotebookProvider(viewType);
});
}
async $resolveNotebook(viewType: string, uri: UriComponents): Promise<number | undefined> {
let provider = this._notebookProviders.get(viewType);
if (provider) {
if (!this._documents.has(URI.revive(uri).toString())) {
let document = new ExtHostNotebookDocument(this._proxy, this._documentsAndEditors, viewType, URI.revive(uri), this);
await this._proxy.$createNotebookDocument(
document.handle,
viewType,
uri
);
this._documents.set(URI.revive(uri).toString(), document);
}
const onDidReceiveMessage = new Emitter<any>();
let editor = new ExtHostNotebookEditor(
viewType,
`${ExtHostNotebookController._handlePool++}`,
URI.revive(uri),
this._proxy,
onDidReceiveMessage,
this._documents.get(URI.revive(uri).toString())!,
this._documentsAndEditors
);
this._editors.set(URI.revive(uri).toString(), { editor, onDidReceiveMessage });
await provider.provider.resolveNotebook(editor);
// await editor.document.$updateCells();
return editor.document.handle;
}
return Promise.resolve(undefined);
}
async $executeNotebook(viewType: string, uri: UriComponents, cellHandle: number | undefined): Promise<void> {
let provider = this._notebookProviders.get(viewType);
if (!provider) {
return;
}
let document = this._documents.get(URI.revive(uri).toString());
if (!document) {
return;
}
let cell = cellHandle !== undefined ? document.getCell(cellHandle) : undefined;
return provider.provider.executeCell(document!, cell);
}
async $saveNotebook(viewType: string, uri: UriComponents): Promise<boolean> {
let provider = this._notebookProviders.get(viewType);
let document = this._documents.get(URI.revive(uri).toString());
if (provider && document) {
return await provider.provider.save(document);
}
return false;
}
async $updateActiveEditor(viewType: string, uri: UriComponents): Promise<void> {
this._activeNotebookDocument = this._documents.get(URI.revive(uri).toString());
}
async $destoryNotebookDocument(viewType: string, uri: UriComponents): Promise<boolean> {
let provider = this._notebookProviders.get(viewType);
if (!provider) {
return false;
}
let document = this._documents.get(URI.revive(uri).toString());
if (document) {
document.dispose();
this._documents.delete(URI.revive(uri).toString());
}
let editor = this._editors.get(URI.revive(uri).toString());
if (editor) {
editor.editor.dispose();
editor.onDidReceiveMessage.dispose();
this._editors.delete(URI.revive(uri).toString());
}
return true;
}
$acceptDisplayOrder(displayOrder: INotebookDisplayOrder): void {
this._outputDisplayOrder = displayOrder;
}
$onDidReceiveMessage(uri: UriComponents, message: any): void {
let editor = this._editors.get(URI.revive(uri).toString());
if (editor) {
editor.onDidReceiveMessage.fire(message);
}
}
$acceptModelChanged(uriComponents: UriComponents, event: NotebookCellsChangedEvent): void {
let editor = this._editors.get(URI.revive(uriComponents).toString());
if (editor) {
editor.editor.document.accpetModelChanged(event);
}
}
}
| src/vs/workbench/api/common/extHostNotebook.ts | 1 | https://github.com/microsoft/vscode/commit/c0efffc91f0c4cd10e70f30229f19da96a50f960 | [
0.9958544969558716,
0.02657129243016243,
0.00016325317847076803,
0.00017011472664307803,
0.15932504832744598
] |
{
"id": 3,
"code_window": [
"\t\t\t\t\tcontinue;\n",
"\t\t\t\t}\n",
"\t\t\t}\n",
"\n",
"\t\t\tcompressedEdits.push(editData.edits[i]);\n",
"\t\t\tcompressedEditsIndex++;\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tif (prev.editType === CellEditType.Delete && editData.edits[i].editType === CellEditType.Delete) {\n",
"\t\t\t\tif (prev.index === editData.edits[i].index) {\n",
"\t\t\t\t\tprev.count += (editData.edits[i] as ICellDeleteEdit).count;\n",
"\t\t\t\t\tcontinue;\n",
"\t\t\t\t}\n",
"\t\t\t}\n",
"\n"
],
"file_path": "src/vs/workbench/api/common/extHostNotebook.ts",
"type": "add",
"edit_start_line_idx": 503
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as resources from 'vs/base/common/resources';
import * as dom from 'vs/base/browser/dom';
import { IAction, Action } from 'vs/base/common/actions';
import { IDebugService, IBreakpoint, CONTEXT_BREAKPOINTS_FOCUSED, State, DEBUG_SCHEME, IFunctionBreakpoint, IExceptionBreakpoint, IEnablement, BREAKPOINT_EDITOR_CONTRIBUTION_ID, IBreakpointEditorContribution, IDebugModel, IDataBreakpoint } from 'vs/workbench/contrib/debug/common/debug';
import { ExceptionBreakpoint, FunctionBreakpoint, Breakpoint, DataBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel';
import { AddFunctionBreakpointAction, ToggleBreakpointsActivatedAction, RemoveAllBreakpointsAction, RemoveBreakpointAction, EnableAllBreakpointsAction, DisableAllBreakpointsAction, ReapplyBreakpointsAction } from 'vs/workbench/contrib/debug/browser/debugActions';
import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { Constants } from 'vs/base/common/uint';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { Separator } from 'vs/base/browser/ui/actionbar/actionbar';
import { IListVirtualDelegate, IListContextMenuEvent, IListRenderer } from 'vs/base/browser/ui/list/list';
import { IEditorPane } from 'vs/workbench/common/editor';
import { InputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { KeyCode } from 'vs/base/common/keyCodes';
import { WorkbenchList } from 'vs/platform/list/browser/listService';
import { IViewletViewOptions } from 'vs/workbench/browser/parts/views/viewsViewlet';
import { attachInputBoxStyler } from 'vs/platform/theme/common/styler';
import { isCodeEditor } from 'vs/editor/browser/editorBrowser';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IEditorService, SIDE_GROUP, ACTIVE_GROUP } from 'vs/workbench/services/editor/common/editorService';
import { ViewPane } from 'vs/workbench/browser/parts/views/viewPaneContainer';
import { ILabelService } from 'vs/platform/label/common/label';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { Gesture } from 'vs/base/browser/touch';
import { IViewDescriptorService } from 'vs/workbench/common/views';
import { TextEditorSelectionRevealType } from 'vs/platform/editor/common/editor';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
const $ = dom.$;
function createCheckbox(): HTMLInputElement {
const checkbox = <HTMLInputElement>$('input');
checkbox.type = 'checkbox';
checkbox.tabIndex = -1;
Gesture.ignoreTarget(checkbox);
return checkbox;
}
const MAX_VISIBLE_BREAKPOINTS = 9;
export function getExpandedBodySize(model: IDebugModel): number {
const length = model.getBreakpoints().length + model.getExceptionBreakpoints().length + model.getFunctionBreakpoints().length + model.getDataBreakpoints().length;
return Math.min(MAX_VISIBLE_BREAKPOINTS, length) * 22;
}
export class BreakpointsView extends ViewPane {
private list!: WorkbenchList<IEnablement>;
private needsRefresh = false;
constructor(
options: IViewletViewOptions,
@IContextMenuService contextMenuService: IContextMenuService,
@IDebugService private readonly debugService: IDebugService,
@IKeybindingService keybindingService: IKeybindingService,
@IInstantiationService instantiationService: IInstantiationService,
@IThemeService themeService: IThemeService,
@IEditorService private readonly editorService: IEditorService,
@IContextViewService private readonly contextViewService: IContextViewService,
@IConfigurationService configurationService: IConfigurationService,
@IViewDescriptorService viewDescriptorService: IViewDescriptorService,
@IContextKeyService contextKeyService: IContextKeyService,
@IOpenerService openerService: IOpenerService,
@ITelemetryService telemetryService: ITelemetryService,
) {
super(options, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService);
this.minimumBodySize = this.maximumBodySize = getExpandedBodySize(this.debugService.getModel());
this._register(this.debugService.getModel().onDidChangeBreakpoints(() => this.onBreakpointsChange()));
}
public renderBody(container: HTMLElement): void {
super.renderBody(container);
dom.addClass(this.element, 'debug-pane');
dom.addClass(container, 'debug-breakpoints');
const delegate = new BreakpointsDelegate(this.debugService);
this.list = <WorkbenchList<IEnablement>>this.instantiationService.createInstance(WorkbenchList, 'Breakpoints', container, delegate, [
this.instantiationService.createInstance(BreakpointsRenderer),
new ExceptionBreakpointsRenderer(this.debugService),
this.instantiationService.createInstance(FunctionBreakpointsRenderer),
this.instantiationService.createInstance(DataBreakpointsRenderer),
new FunctionBreakpointInputRenderer(this.debugService, this.contextViewService, this.themeService)
], {
identityProvider: { getId: (element: IEnablement) => element.getId() },
multipleSelectionSupport: false,
keyboardNavigationLabelProvider: { getKeyboardNavigationLabel: (e: IEnablement) => e },
ariaProvider: {
getSetSize: (_: IEnablement, index: number, listLength: number) => listLength,
getPosInSet: (_: IEnablement, index: number) => index,
getRole: (breakpoint: IEnablement) => 'checkbox',
isChecked: (breakpoint: IEnablement) => breakpoint.enabled
},
overrideStyles: {
listBackground: this.getBackgroundColor()
}
});
CONTEXT_BREAKPOINTS_FOCUSED.bindTo(this.list.contextKeyService);
this._register(this.list.onContextMenu(this.onListContextMenu, this));
this._register(this.list.onDidOpen(async e => {
let isSingleClick = false;
let isDoubleClick = false;
let isMiddleClick = false;
let openToSide = false;
const browserEvent = e.browserEvent;
if (browserEvent instanceof MouseEvent) {
isSingleClick = browserEvent.detail === 1;
isDoubleClick = browserEvent.detail === 2;
isMiddleClick = browserEvent.button === 1;
openToSide = (browserEvent.ctrlKey || browserEvent.metaKey || browserEvent.altKey);
}
const focused = this.list.getFocusedElements();
const element = focused.length ? focused[0] : undefined;
if (isMiddleClick) {
if (element instanceof Breakpoint) {
await this.debugService.removeBreakpoints(element.getId());
} else if (element instanceof FunctionBreakpoint) {
await this.debugService.removeFunctionBreakpoints(element.getId());
} else if (element instanceof DataBreakpoint) {
await this.debugService.removeDataBreakpoints(element.getId());
}
return;
}
if (element instanceof Breakpoint) {
openBreakpointSource(element, openToSide, isSingleClick, this.debugService, this.editorService);
}
if (isDoubleClick && element instanceof FunctionBreakpoint && element !== this.debugService.getViewModel().getSelectedFunctionBreakpoint()) {
this.debugService.getViewModel().setSelectedFunctionBreakpoint(element);
this.onBreakpointsChange();
}
}));
this.list.splice(0, this.list.length, this.elements);
this._register(this.onDidChangeBodyVisibility(visible => {
if (visible && this.needsRefresh) {
this.onBreakpointsChange();
}
}));
}
public focus(): void {
super.focus();
if (this.list) {
this.list.domFocus();
}
}
protected layoutBody(height: number, width: number): void {
if (this.list) {
this.list.layout(height, width);
}
}
private onListContextMenu(e: IListContextMenuEvent<IEnablement>): void {
if (!e.element) {
return;
}
const actions: IAction[] = [];
const element = e.element;
const breakpointType = element instanceof Breakpoint && element.logMessage ? nls.localize('Logpoint', "Logpoint") : nls.localize('Breakpoint', "Breakpoint");
if (element instanceof Breakpoint || element instanceof FunctionBreakpoint) {
actions.push(new Action('workbench.action.debug.openEditorAndEditBreakpoint', nls.localize('editBreakpoint', "Edit {0}...", breakpointType), '', true, async () => {
if (element instanceof Breakpoint) {
const editor = await openBreakpointSource(element, false, false, this.debugService, this.editorService);
if (editor) {
const codeEditor = editor.getControl();
if (isCodeEditor(codeEditor)) {
codeEditor.getContribution<IBreakpointEditorContribution>(BREAKPOINT_EDITOR_CONTRIBUTION_ID).showBreakpointWidget(element.lineNumber, element.column);
}
}
} else {
this.debugService.getViewModel().setSelectedFunctionBreakpoint(element);
this.onBreakpointsChange();
}
}));
actions.push(new Separator());
}
actions.push(new RemoveBreakpointAction(RemoveBreakpointAction.ID, nls.localize('removeBreakpoint', "Remove {0}", breakpointType), this.debugService));
if (this.debugService.getModel().getBreakpoints().length + this.debugService.getModel().getFunctionBreakpoints().length > 1) {
actions.push(new RemoveAllBreakpointsAction(RemoveAllBreakpointsAction.ID, RemoveAllBreakpointsAction.LABEL, this.debugService, this.keybindingService));
actions.push(new Separator());
actions.push(new EnableAllBreakpointsAction(EnableAllBreakpointsAction.ID, EnableAllBreakpointsAction.LABEL, this.debugService, this.keybindingService));
actions.push(new DisableAllBreakpointsAction(DisableAllBreakpointsAction.ID, DisableAllBreakpointsAction.LABEL, this.debugService, this.keybindingService));
}
actions.push(new Separator());
actions.push(new ReapplyBreakpointsAction(ReapplyBreakpointsAction.ID, ReapplyBreakpointsAction.LABEL, this.debugService, this.keybindingService));
this.contextMenuService.showContextMenu({
getAnchor: () => e.anchor,
getActions: () => actions,
getActionsContext: () => element,
onHide: () => dispose(actions)
});
}
public getActions(): IAction[] {
return [
new AddFunctionBreakpointAction(AddFunctionBreakpointAction.ID, AddFunctionBreakpointAction.LABEL, this.debugService, this.keybindingService),
new ToggleBreakpointsActivatedAction(ToggleBreakpointsActivatedAction.ID, ToggleBreakpointsActivatedAction.ACTIVATE_LABEL, this.debugService, this.keybindingService),
new RemoveAllBreakpointsAction(RemoveAllBreakpointsAction.ID, RemoveAllBreakpointsAction.LABEL, this.debugService, this.keybindingService)
];
}
private onBreakpointsChange(): void {
if (this.isBodyVisible()) {
this.minimumBodySize = getExpandedBodySize(this.debugService.getModel());
if (this.maximumBodySize < Number.POSITIVE_INFINITY) {
this.maximumBodySize = this.minimumBodySize;
}
if (this.list) {
this.list.splice(0, this.list.length, this.elements);
this.needsRefresh = false;
}
} else {
this.needsRefresh = true;
}
}
private get elements(): IEnablement[] {
const model = this.debugService.getModel();
const elements = (<ReadonlyArray<IEnablement>>model.getExceptionBreakpoints()).concat(model.getFunctionBreakpoints()).concat(model.getDataBreakpoints()).concat(model.getBreakpoints());
return elements;
}
}
class BreakpointsDelegate implements IListVirtualDelegate<IEnablement> {
constructor(private debugService: IDebugService) {
// noop
}
getHeight(element: IEnablement): number {
return 22;
}
getTemplateId(element: IEnablement): string {
if (element instanceof Breakpoint) {
return BreakpointsRenderer.ID;
}
if (element instanceof FunctionBreakpoint) {
const selected = this.debugService.getViewModel().getSelectedFunctionBreakpoint();
if (!element.name || (selected && selected.getId() === element.getId())) {
return FunctionBreakpointInputRenderer.ID;
}
return FunctionBreakpointsRenderer.ID;
}
if (element instanceof ExceptionBreakpoint) {
return ExceptionBreakpointsRenderer.ID;
}
if (element instanceof DataBreakpoint) {
return DataBreakpointsRenderer.ID;
}
return '';
}
}
interface IBaseBreakpointTemplateData {
breakpoint: HTMLElement;
name: HTMLElement;
checkbox: HTMLInputElement;
context: IEnablement;
toDispose: IDisposable[];
}
interface IBaseBreakpointWithIconTemplateData extends IBaseBreakpointTemplateData {
icon: HTMLElement;
}
interface IBreakpointTemplateData extends IBaseBreakpointWithIconTemplateData {
lineNumber: HTMLElement;
filePath: HTMLElement;
}
interface IInputTemplateData {
inputBox: InputBox;
checkbox: HTMLInputElement;
icon: HTMLElement;
breakpoint: IFunctionBreakpoint;
reactedOnEvent: boolean;
toDispose: IDisposable[];
}
class BreakpointsRenderer implements IListRenderer<IBreakpoint, IBreakpointTemplateData> {
constructor(
@IDebugService private readonly debugService: IDebugService,
@ILabelService private readonly labelService: ILabelService
) {
// noop
}
static readonly ID = 'breakpoints';
get templateId() {
return BreakpointsRenderer.ID;
}
renderTemplate(container: HTMLElement): IBreakpointTemplateData {
const data: IBreakpointTemplateData = Object.create(null);
data.breakpoint = dom.append(container, $('.breakpoint'));
data.icon = $('.icon');
data.checkbox = createCheckbox();
data.toDispose = [];
data.toDispose.push(dom.addStandardDisposableListener(data.checkbox, 'change', (e) => {
this.debugService.enableOrDisableBreakpoints(!data.context.enabled, data.context);
}));
dom.append(data.breakpoint, data.icon);
dom.append(data.breakpoint, data.checkbox);
data.name = dom.append(data.breakpoint, $('span.name'));
data.filePath = dom.append(data.breakpoint, $('span.file-path'));
const lineNumberContainer = dom.append(data.breakpoint, $('.line-number-container'));
data.lineNumber = dom.append(lineNumberContainer, $('span.line-number'));
return data;
}
renderElement(breakpoint: IBreakpoint, index: number, data: IBreakpointTemplateData): void {
data.context = breakpoint;
dom.toggleClass(data.breakpoint, 'disabled', !this.debugService.getModel().areBreakpointsActivated());
data.name.textContent = resources.basenameOrAuthority(breakpoint.uri);
data.lineNumber.textContent = breakpoint.lineNumber.toString();
if (breakpoint.column) {
data.lineNumber.textContent += `:${breakpoint.column}`;
}
data.filePath.textContent = this.labelService.getUriLabel(resources.dirname(breakpoint.uri), { relative: true });
data.checkbox.checked = breakpoint.enabled;
const { message, className } = getBreakpointMessageAndClassName(this.debugService.state, this.debugService.getModel().areBreakpointsActivated(), breakpoint);
data.icon.className = `codicon ${className}`;
data.breakpoint.title = breakpoint.message || message || '';
const debugActive = this.debugService.state === State.Running || this.debugService.state === State.Stopped;
if (debugActive && !breakpoint.verified) {
dom.addClass(data.breakpoint, 'disabled');
}
}
disposeTemplate(templateData: IBreakpointTemplateData): void {
dispose(templateData.toDispose);
}
}
class ExceptionBreakpointsRenderer implements IListRenderer<IExceptionBreakpoint, IBaseBreakpointTemplateData> {
constructor(
private debugService: IDebugService
) {
// noop
}
static readonly ID = 'exceptionbreakpoints';
get templateId() {
return ExceptionBreakpointsRenderer.ID;
}
renderTemplate(container: HTMLElement): IBaseBreakpointTemplateData {
const data: IBreakpointTemplateData = Object.create(null);
data.breakpoint = dom.append(container, $('.breakpoint'));
data.checkbox = createCheckbox();
data.toDispose = [];
data.toDispose.push(dom.addStandardDisposableListener(data.checkbox, 'change', (e) => {
this.debugService.enableOrDisableBreakpoints(!data.context.enabled, data.context);
}));
dom.append(data.breakpoint, data.checkbox);
data.name = dom.append(data.breakpoint, $('span.name'));
dom.addClass(data.breakpoint, 'exception');
return data;
}
renderElement(exceptionBreakpoint: IExceptionBreakpoint, index: number, data: IBaseBreakpointTemplateData): void {
data.context = exceptionBreakpoint;
data.name.textContent = exceptionBreakpoint.label || `${exceptionBreakpoint.filter} exceptions`;
data.breakpoint.title = data.name.textContent;
data.checkbox.checked = exceptionBreakpoint.enabled;
}
disposeTemplate(templateData: IBaseBreakpointTemplateData): void {
dispose(templateData.toDispose);
}
}
class FunctionBreakpointsRenderer implements IListRenderer<FunctionBreakpoint, IBaseBreakpointWithIconTemplateData> {
constructor(
@IDebugService private readonly debugService: IDebugService
) {
// noop
}
static readonly ID = 'functionbreakpoints';
get templateId() {
return FunctionBreakpointsRenderer.ID;
}
renderTemplate(container: HTMLElement): IBaseBreakpointWithIconTemplateData {
const data: IBreakpointTemplateData = Object.create(null);
data.breakpoint = dom.append(container, $('.breakpoint'));
data.icon = $('.icon');
data.checkbox = createCheckbox();
data.toDispose = [];
data.toDispose.push(dom.addStandardDisposableListener(data.checkbox, 'change', (e) => {
this.debugService.enableOrDisableBreakpoints(!data.context.enabled, data.context);
}));
dom.append(data.breakpoint, data.icon);
dom.append(data.breakpoint, data.checkbox);
data.name = dom.append(data.breakpoint, $('span.name'));
return data;
}
renderElement(functionBreakpoint: FunctionBreakpoint, _index: number, data: IBaseBreakpointWithIconTemplateData): void {
data.context = functionBreakpoint;
data.name.textContent = functionBreakpoint.name;
const { className, message } = getBreakpointMessageAndClassName(this.debugService.state, this.debugService.getModel().areBreakpointsActivated(), functionBreakpoint);
data.icon.className = `codicon ${className}`;
data.icon.title = message ? message : '';
data.checkbox.checked = functionBreakpoint.enabled;
data.breakpoint.title = message ? message : '';
// Mark function breakpoints as disabled if deactivated or if debug type does not support them #9099
const session = this.debugService.getViewModel().focusedSession;
dom.toggleClass(data.breakpoint, 'disabled', (session && !session.capabilities.supportsFunctionBreakpoints) || !this.debugService.getModel().areBreakpointsActivated());
if (session && !session.capabilities.supportsFunctionBreakpoints) {
data.breakpoint.title = nls.localize('functionBreakpointsNotSupported', "Function breakpoints are not supported by this debug type");
}
}
disposeTemplate(templateData: IBaseBreakpointWithIconTemplateData): void {
dispose(templateData.toDispose);
}
}
class DataBreakpointsRenderer implements IListRenderer<DataBreakpoint, IBaseBreakpointWithIconTemplateData> {
constructor(
@IDebugService private readonly debugService: IDebugService
) {
// noop
}
static readonly ID = 'databreakpoints';
get templateId() {
return DataBreakpointsRenderer.ID;
}
renderTemplate(container: HTMLElement): IBaseBreakpointWithIconTemplateData {
const data: IBreakpointTemplateData = Object.create(null);
data.breakpoint = dom.append(container, $('.breakpoint'));
data.icon = $('.icon');
data.checkbox = createCheckbox();
data.toDispose = [];
data.toDispose.push(dom.addStandardDisposableListener(data.checkbox, 'change', (e) => {
this.debugService.enableOrDisableBreakpoints(!data.context.enabled, data.context);
}));
dom.append(data.breakpoint, data.icon);
dom.append(data.breakpoint, data.checkbox);
data.name = dom.append(data.breakpoint, $('span.name'));
return data;
}
renderElement(dataBreakpoint: DataBreakpoint, _index: number, data: IBaseBreakpointWithIconTemplateData): void {
data.context = dataBreakpoint;
data.name.textContent = dataBreakpoint.description;
const { className, message } = getBreakpointMessageAndClassName(this.debugService.state, this.debugService.getModel().areBreakpointsActivated(), dataBreakpoint);
data.icon.className = `codicon ${className}`;
data.icon.title = message ? message : '';
data.checkbox.checked = dataBreakpoint.enabled;
data.breakpoint.title = message ? message : '';
// Mark function breakpoints as disabled if deactivated or if debug type does not support them #9099
const session = this.debugService.getViewModel().focusedSession;
dom.toggleClass(data.breakpoint, 'disabled', (session && !session.capabilities.supportsDataBreakpoints) || !this.debugService.getModel().areBreakpointsActivated());
if (session && !session.capabilities.supportsDataBreakpoints) {
data.breakpoint.title = nls.localize('dataBreakpointsNotSupported', "Data breakpoints are not supported by this debug type");
}
}
disposeTemplate(templateData: IBaseBreakpointWithIconTemplateData): void {
dispose(templateData.toDispose);
}
}
class FunctionBreakpointInputRenderer implements IListRenderer<IFunctionBreakpoint, IInputTemplateData> {
constructor(
private debugService: IDebugService,
private contextViewService: IContextViewService,
private themeService: IThemeService
) {
// noop
}
static readonly ID = 'functionbreakpointinput';
get templateId() {
return FunctionBreakpointInputRenderer.ID;
}
renderTemplate(container: HTMLElement): IInputTemplateData {
const template: IInputTemplateData = Object.create(null);
const breakpoint = dom.append(container, $('.breakpoint'));
template.icon = $('.icon');
template.checkbox = createCheckbox();
dom.append(breakpoint, template.icon);
dom.append(breakpoint, template.checkbox);
const inputBoxContainer = dom.append(breakpoint, $('.inputBoxContainer'));
const inputBox = new InputBox(inputBoxContainer, this.contextViewService, {
placeholder: nls.localize('functionBreakpointPlaceholder', "Function to break on"),
ariaLabel: nls.localize('functionBreakPointInputAriaLabel', "Type function breakpoint")
});
const styler = attachInputBoxStyler(inputBox, this.themeService);
const toDispose: IDisposable[] = [inputBox, styler];
const wrapUp = (renamed: boolean) => {
if (!template.reactedOnEvent) {
template.reactedOnEvent = true;
this.debugService.getViewModel().setSelectedFunctionBreakpoint(undefined);
if (inputBox.value && (renamed || template.breakpoint.name)) {
this.debugService.renameFunctionBreakpoint(template.breakpoint.getId(), renamed ? inputBox.value : template.breakpoint.name);
} else {
this.debugService.removeFunctionBreakpoints(template.breakpoint.getId());
}
}
};
toDispose.push(dom.addStandardDisposableListener(inputBox.inputElement, 'keydown', (e: IKeyboardEvent) => {
const isEscape = e.equals(KeyCode.Escape);
const isEnter = e.equals(KeyCode.Enter);
if (isEscape || isEnter) {
e.preventDefault();
e.stopPropagation();
wrapUp(isEnter);
}
}));
toDispose.push(dom.addDisposableListener(inputBox.inputElement, 'blur', () => {
// Need to react with a timeout on the blur event due to possible concurent splices #56443
setTimeout(() => {
if (!template.breakpoint.name) {
wrapUp(true);
}
});
}));
template.inputBox = inputBox;
template.toDispose = toDispose;
return template;
}
renderElement(functionBreakpoint: FunctionBreakpoint, _index: number, data: IInputTemplateData): void {
data.breakpoint = functionBreakpoint;
data.reactedOnEvent = false;
const { className, message } = getBreakpointMessageAndClassName(this.debugService.state, this.debugService.getModel().areBreakpointsActivated(), functionBreakpoint);
data.icon.className = `codicon ${className}`;
data.icon.title = message ? message : '';
data.checkbox.checked = functionBreakpoint.enabled;
data.checkbox.disabled = true;
data.inputBox.value = functionBreakpoint.name || '';
setTimeout(() => {
data.inputBox.focus();
data.inputBox.select();
}, 0);
}
disposeTemplate(templateData: IInputTemplateData): void {
dispose(templateData.toDispose);
}
}
export function openBreakpointSource(breakpoint: IBreakpoint, sideBySide: boolean, preserveFocus: boolean, debugService: IDebugService, editorService: IEditorService): Promise<IEditorPane | undefined> {
if (breakpoint.uri.scheme === DEBUG_SCHEME && debugService.state === State.Inactive) {
return Promise.resolve(undefined);
}
const selection = breakpoint.endLineNumber ? {
startLineNumber: breakpoint.lineNumber,
endLineNumber: breakpoint.endLineNumber,
startColumn: breakpoint.column || 1,
endColumn: breakpoint.endColumn || Constants.MAX_SAFE_SMALL_INTEGER
} : {
startLineNumber: breakpoint.lineNumber,
startColumn: breakpoint.column || 1,
endLineNumber: breakpoint.lineNumber,
endColumn: breakpoint.column || Constants.MAX_SAFE_SMALL_INTEGER
};
return editorService.openEditor({
resource: breakpoint.uri,
options: {
preserveFocus,
selection,
revealIfOpened: true,
selectionRevealType: TextEditorSelectionRevealType.CenterIfOutsideViewport,
pinned: !preserveFocus
}
}, sideBySide ? SIDE_GROUP : ACTIVE_GROUP);
}
export function getBreakpointMessageAndClassName(state: State, breakpointsActivated: boolean, breakpoint: IBreakpoint | IFunctionBreakpoint | IDataBreakpoint): { message?: string, className: string } {
const debugActive = state === State.Running || state === State.Stopped;
if (!breakpoint.enabled || !breakpointsActivated) {
return {
className: breakpoint instanceof DataBreakpoint ? 'codicon-debug-breakpoint-data-disabled' : breakpoint instanceof FunctionBreakpoint ? 'codicon-debug-breakpoint-function-disabled' : breakpoint.logMessage ? 'codicon-debug-breakpoint-log-disabled' : 'codicon-debug-breakpoint-disabled',
message: breakpoint.logMessage ? nls.localize('disabledLogpoint', "Disabled Logpoint") : nls.localize('disabledBreakpoint', "Disabled Breakpoint"),
};
}
const appendMessage = (text: string): string => {
return ('message' in breakpoint && breakpoint.message) ? text.concat(', ' + breakpoint.message) : text;
};
if (debugActive && !breakpoint.verified) {
return {
className: breakpoint instanceof DataBreakpoint ? 'codicon-debug-breakpoint-data-unverified' : breakpoint instanceof FunctionBreakpoint ? 'codicon-debug-breakpoint-function-unverified' : breakpoint.logMessage ? 'codicon-debug-breakpoint-log-unverified' : 'codicon-debug-breakpoint-unverified',
message: ('message' in breakpoint && breakpoint.message) ? breakpoint.message : (breakpoint.logMessage ? nls.localize('unverifiedLogpoint', "Unverified Logpoint") : nls.localize('unverifiedBreakopint', "Unverified Breakpoint")),
};
}
if (breakpoint instanceof FunctionBreakpoint) {
if (!breakpoint.supported) {
return {
className: 'codicon-debug-breakpoint-function-unverified',
message: nls.localize('functionBreakpointUnsupported', "Function breakpoints not supported by this debug type"),
};
}
return {
className: 'codicon-debug-breakpoint-function',
message: breakpoint.message || nls.localize('functionBreakpoint', "Function Breakpoint")
};
}
if (breakpoint instanceof DataBreakpoint) {
if (!breakpoint.supported) {
return {
className: 'codicon-debug-breakpoint-data-unverified',
message: nls.localize('dataBreakpointUnsupported', "Data breakpoints not supported by this debug type"),
};
}
return {
className: 'codicon-debug-breakpoint-data',
message: breakpoint.message || nls.localize('dataBreakpoint', "Data Breakpoint")
};
}
if (breakpoint.logMessage || breakpoint.condition || breakpoint.hitCondition) {
const messages: string[] = [];
if (!breakpoint.supported) {
return {
className: 'codicon-debug-breakpoint-unsupported',
message: nls.localize('breakpointUnsupported', "Breakpoints of this type are not supported by the debugger"),
};
}
if (breakpoint.logMessage) {
messages.push(nls.localize('logMessage', "Log Message: {0}", breakpoint.logMessage));
}
if (breakpoint.condition) {
messages.push(nls.localize('expression', "Expression: {0}", breakpoint.condition));
}
if (breakpoint.hitCondition) {
messages.push(nls.localize('hitCount', "Hit Count: {0}", breakpoint.hitCondition));
}
return {
className: breakpoint.logMessage ? 'codicon-debug-breakpoint-log' : 'codicon-debug-breakpoint-conditional',
message: appendMessage(messages.join('\n'))
};
}
return {
className: 'codicon-debug-breakpoint',
message: ('message' in breakpoint && breakpoint.message) ? breakpoint.message : nls.localize('breakpoint', "Breakpoint")
};
}
| src/vs/workbench/contrib/debug/browser/breakpointsView.ts | 0 | https://github.com/microsoft/vscode/commit/c0efffc91f0c4cd10e70f30229f19da96a50f960 | [
0.0007684515439905226,
0.0001964281254913658,
0.00016396126011386514,
0.00017012267198879272,
0.00009993249841500074
] |
{
"id": 3,
"code_window": [
"\t\t\t\t\tcontinue;\n",
"\t\t\t\t}\n",
"\t\t\t}\n",
"\n",
"\t\t\tcompressedEdits.push(editData.edits[i]);\n",
"\t\t\tcompressedEditsIndex++;\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tif (prev.editType === CellEditType.Delete && editData.edits[i].editType === CellEditType.Delete) {\n",
"\t\t\t\tif (prev.index === editData.edits[i].index) {\n",
"\t\t\t\t\tprev.count += (editData.edits[i] as ICellDeleteEdit).count;\n",
"\t\t\t\t\tcontinue;\n",
"\t\t\t\t}\n",
"\t\t\t}\n",
"\n"
],
"file_path": "src/vs/workbench/api/common/extHostNotebook.ts",
"type": "add",
"edit_start_line_idx": 503
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export class Kind {
public static readonly alias = 'alias';
public static readonly callSignature = 'call';
public static readonly class = 'class';
public static readonly const = 'const';
public static readonly constructorImplementation = 'constructor';
public static readonly constructSignature = 'construct';
public static readonly directory = 'directory';
public static readonly enum = 'enum';
public static readonly enumMember = 'enum member';
public static readonly externalModuleName = 'external module name';
public static readonly function = 'function';
public static readonly indexSignature = 'index';
public static readonly interface = 'interface';
public static readonly keyword = 'keyword';
public static readonly let = 'let';
public static readonly localFunction = 'local function';
public static readonly localVariable = 'local var';
public static readonly method = 'method';
public static readonly memberGetAccessor = 'getter';
public static readonly memberSetAccessor = 'setter';
public static readonly memberVariable = 'property';
public static readonly module = 'module';
public static readonly primitiveType = 'primitive type';
public static readonly script = 'script';
public static readonly type = 'type';
public static readonly variable = 'var';
public static readonly warning = 'warning';
public static readonly string = 'string';
public static readonly parameter = 'parameter';
public static readonly typeParameter = 'type parameter';
}
export class DiagnosticCategory {
public static readonly error = 'error';
public static readonly warning = 'warning';
public static readonly suggestion = 'suggestion';
}
export class KindModifiers {
public static readonly optional = 'optional';
public static readonly color = 'color';
public static readonly dtsFile = '.d.ts';
public static readonly tsFile = '.ts';
public static readonly tsxFile = '.tsx';
public static readonly jsFile = '.js';
public static readonly jsxFile = '.jsx';
public static readonly jsonFile = '.json';
public static readonly fileExtensionKindModifiers = [
KindModifiers.dtsFile,
KindModifiers.tsFile,
KindModifiers.tsxFile,
KindModifiers.jsFile,
KindModifiers.jsxFile,
KindModifiers.jsonFile,
];
}
export class DisplayPartKind {
public static readonly functionName = 'functionName';
public static readonly methodName = 'methodName';
public static readonly parameterName = 'parameterName';
public static readonly propertyName = 'propertyName';
public static readonly punctuation = 'punctuation';
public static readonly text = 'text';
}
| extensions/typescript-language-features/src/protocol.const.ts | 0 | https://github.com/microsoft/vscode/commit/c0efffc91f0c4cd10e70f30229f19da96a50f960 | [
0.00017578681581653655,
0.00017357492470182478,
0.00017110853514168411,
0.0001735108089633286,
0.0000016214017932725255
] |
{
"id": 3,
"code_window": [
"\t\t\t\t\tcontinue;\n",
"\t\t\t\t}\n",
"\t\t\t}\n",
"\n",
"\t\t\tcompressedEdits.push(editData.edits[i]);\n",
"\t\t\tcompressedEditsIndex++;\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tif (prev.editType === CellEditType.Delete && editData.edits[i].editType === CellEditType.Delete) {\n",
"\t\t\t\tif (prev.index === editData.edits[i].index) {\n",
"\t\t\t\t\tprev.count += (editData.edits[i] as ICellDeleteEdit).count;\n",
"\t\t\t\t\tcontinue;\n",
"\t\t\t\t}\n",
"\t\t\t}\n",
"\n"
],
"file_path": "src/vs/workbench/api/common/extHostNotebook.ts",
"type": "add",
"edit_start_line_idx": 503
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { asPromise } from 'vs/base/common/async';
import { CancellationToken } from 'vs/base/common/cancellation';
import { debounce } from 'vs/base/common/decorators';
import { Emitter } from 'vs/base/common/event';
import { DisposableStore, IDisposable, MutableDisposable } from 'vs/base/common/lifecycle';
import { URI, UriComponents } from 'vs/base/common/uri';
import { IRange } from 'vs/editor/common/core/range';
import * as modes from 'vs/editor/common/modes';
import { ExtensionIdentifier, IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { ExtHostDocuments } from 'vs/workbench/api/common/extHostDocuments';
import * as extHostTypeConverter from 'vs/workbench/api/common/extHostTypeConverters';
import * as types from 'vs/workbench/api/common/extHostTypes';
import type * as vscode from 'vscode';
import { ExtHostCommentsShape, IMainContext, MainContext, MainThreadCommentsShape, CommentThreadChanges } from './extHost.protocol';
import { ExtHostCommands } from './extHostCommands';
type ProviderHandle = number;
export class ExtHostComments implements ExtHostCommentsShape, IDisposable {
private static handlePool = 0;
private _proxy: MainThreadCommentsShape;
private _commentControllers: Map<ProviderHandle, ExtHostCommentController> = new Map<ProviderHandle, ExtHostCommentController>();
private _commentControllersByExtension: Map<string, ExtHostCommentController[]> = new Map<string, ExtHostCommentController[]>();
constructor(
mainContext: IMainContext,
commands: ExtHostCommands,
private readonly _documents: ExtHostDocuments,
) {
this._proxy = mainContext.getProxy(MainContext.MainThreadComments);
commands.registerArgumentProcessor({
processArgument: arg => {
if (arg && arg.$mid === 6) {
const commentController = this._commentControllers.get(arg.handle);
if (!commentController) {
return arg;
}
return commentController;
} else if (arg && arg.$mid === 7) {
const commentController = this._commentControllers.get(arg.commentControlHandle);
if (!commentController) {
return arg;
}
const commentThread = commentController.getCommentThread(arg.commentThreadHandle);
if (!commentThread) {
return arg;
}
return commentThread;
} else if (arg && arg.$mid === 8) {
const commentController = this._commentControllers.get(arg.thread.commentControlHandle);
if (!commentController) {
return arg;
}
const commentThread = commentController.getCommentThread(arg.thread.commentThreadHandle);
if (!commentThread) {
return arg;
}
return {
thread: commentThread,
text: arg.text
};
} else if (arg && arg.$mid === 9) {
const commentController = this._commentControllers.get(arg.thread.commentControlHandle);
if (!commentController) {
return arg;
}
const commentThread = commentController.getCommentThread(arg.thread.commentThreadHandle);
if (!commentThread) {
return arg;
}
let commentUniqueId = arg.commentUniqueId;
let comment = commentThread.getCommentByUniqueId(commentUniqueId);
if (!comment) {
return arg;
}
return comment;
} else if (arg && arg.$mid === 10) {
const commentController = this._commentControllers.get(arg.thread.commentControlHandle);
if (!commentController) {
return arg;
}
const commentThread = commentController.getCommentThread(arg.thread.commentThreadHandle);
if (!commentThread) {
return arg;
}
let body = arg.text;
let commentUniqueId = arg.commentUniqueId;
let comment = commentThread.getCommentByUniqueId(commentUniqueId);
if (!comment) {
return arg;
}
comment.body = body;
return comment;
}
return arg;
}
});
}
createCommentController(extension: IExtensionDescription, id: string, label: string): vscode.CommentController {
const handle = ExtHostComments.handlePool++;
const commentController = new ExtHostCommentController(extension, handle, this._proxy, id, label);
this._commentControllers.set(commentController.handle, commentController);
const commentControllers = this._commentControllersByExtension.get(ExtensionIdentifier.toKey(extension.identifier)) || [];
commentControllers.push(commentController);
this._commentControllersByExtension.set(ExtensionIdentifier.toKey(extension.identifier), commentControllers);
return commentController;
}
$createCommentThreadTemplate(commentControllerHandle: number, uriComponents: UriComponents, range: IRange): void {
const commentController = this._commentControllers.get(commentControllerHandle);
if (!commentController) {
return;
}
commentController.$createCommentThreadTemplate(uriComponents, range);
}
async $updateCommentThreadTemplate(commentControllerHandle: number, threadHandle: number, range: IRange) {
const commentController = this._commentControllers.get(commentControllerHandle);
if (!commentController) {
return;
}
commentController.$updateCommentThreadTemplate(threadHandle, range);
}
$deleteCommentThread(commentControllerHandle: number, commentThreadHandle: number) {
const commentController = this._commentControllers.get(commentControllerHandle);
if (commentController) {
commentController.$deleteCommentThread(commentThreadHandle);
}
}
$provideCommentingRanges(commentControllerHandle: number, uriComponents: UriComponents, token: CancellationToken): Promise<IRange[] | undefined> {
const commentController = this._commentControllers.get(commentControllerHandle);
if (!commentController || !commentController.commentingRangeProvider) {
return Promise.resolve(undefined);
}
const document = this._documents.getDocument(URI.revive(uriComponents));
return asPromise(() => {
return commentController.commentingRangeProvider!.provideCommentingRanges(document, token);
}).then(ranges => ranges ? ranges.map(x => extHostTypeConverter.Range.from(x)) : undefined);
}
$toggleReaction(commentControllerHandle: number, threadHandle: number, uri: UriComponents, comment: modes.Comment, reaction: modes.CommentReaction): Promise<void> {
const commentController = this._commentControllers.get(commentControllerHandle);
if (!commentController || !commentController.reactionHandler) {
return Promise.resolve(undefined);
}
return asPromise(() => {
const commentThread = commentController.getCommentThread(threadHandle);
if (commentThread) {
const vscodeComment = commentThread.getCommentByUniqueId(comment.uniqueIdInThread);
if (commentController !== undefined && vscodeComment) {
if (commentController.reactionHandler) {
return commentController.reactionHandler(vscodeComment, convertFromReaction(reaction));
}
}
}
return Promise.resolve(undefined);
});
}
dispose() {
}
}
type CommentThreadModification = Partial<{
range: vscode.Range,
label: string | undefined,
contextValue: string | undefined,
comments: vscode.Comment[],
collapsibleState: vscode.CommentThreadCollapsibleState
}>;
export class ExtHostCommentThread implements vscode.CommentThread {
private static _handlePool: number = 0;
readonly handle = ExtHostCommentThread._handlePool++;
public commentHandle: number = 0;
private modifications: CommentThreadModification = Object.create(null);
set threadId(id: string) {
this._id = id;
}
get threadId(): string {
return this._id!;
}
get id(): string {
return this._id!;
}
get resource(): vscode.Uri {
return this._uri;
}
get uri(): vscode.Uri {
return this._uri;
}
private readonly _onDidUpdateCommentThread = new Emitter<void>();
readonly onDidUpdateCommentThread = this._onDidUpdateCommentThread.event;
set range(range: vscode.Range) {
if (!range.isEqual(this._range)) {
this._range = range;
this.modifications.range = range;
this._onDidUpdateCommentThread.fire();
}
}
get range(): vscode.Range {
return this._range;
}
private _label: string | undefined;
get label(): string | undefined {
return this._label;
}
set label(label: string | undefined) {
this._label = label;
this.modifications.label = label;
this._onDidUpdateCommentThread.fire();
}
private _contextValue: string | undefined;
get contextValue(): string | undefined {
return this._contextValue;
}
set contextValue(context: string | undefined) {
this._contextValue = context;
this.modifications.contextValue = context;
this._onDidUpdateCommentThread.fire();
}
get comments(): vscode.Comment[] {
return this._comments;
}
set comments(newComments: vscode.Comment[]) {
this._comments = newComments;
this.modifications.comments = newComments;
this._onDidUpdateCommentThread.fire();
}
private _collapseState?: vscode.CommentThreadCollapsibleState;
get collapsibleState(): vscode.CommentThreadCollapsibleState {
return this._collapseState!;
}
set collapsibleState(newState: vscode.CommentThreadCollapsibleState) {
this._collapseState = newState;
this.modifications.collapsibleState = newState;
this._onDidUpdateCommentThread.fire();
}
private _localDisposables: types.Disposable[];
private _isDiposed: boolean;
public get isDisposed(): boolean {
return this._isDiposed;
}
private _commentsMap: Map<vscode.Comment, number> = new Map<vscode.Comment, number>();
private _acceptInputDisposables = new MutableDisposable<DisposableStore>();
constructor(
private _proxy: MainThreadCommentsShape,
private _commentController: ExtHostCommentController,
private _id: string | undefined,
private _uri: vscode.Uri,
private _range: vscode.Range,
private _comments: vscode.Comment[],
extensionId: ExtensionIdentifier
) {
this._acceptInputDisposables.value = new DisposableStore();
if (this._id === undefined) {
this._id = `${_commentController.id}.${this.handle}`;
}
this._proxy.$createCommentThread(
this._commentController.handle,
this.handle,
this._id,
this._uri,
extHostTypeConverter.Range.from(this._range),
extensionId
);
this._localDisposables = [];
this._isDiposed = false;
this._localDisposables.push(this.onDidUpdateCommentThread(() => {
this.eventuallyUpdateCommentThread();
}));
// set up comments after ctor to batch update events.
this.comments = _comments;
}
@debounce(100)
eventuallyUpdateCommentThread(): void {
if (this._isDiposed) {
return;
}
if (!this._acceptInputDisposables.value) {
this._acceptInputDisposables.value = new DisposableStore();
}
const modified = (value: keyof CommentThreadModification): boolean =>
Object.prototype.hasOwnProperty.call(this.modifications, value);
const formattedModifications: CommentThreadChanges = {};
if (modified('range')) {
formattedModifications.range = extHostTypeConverter.Range.from(this._range);
}
if (modified('label')) {
formattedModifications.label = this.label;
}
if (modified('contextValue')) {
formattedModifications.contextValue = this.contextValue;
}
if (modified('comments')) {
formattedModifications.comments =
this._comments.map(cmt => convertToModeComment(this, this._commentController, cmt, this._commentsMap));
}
if (modified('collapsibleState')) {
formattedModifications.collapseState = convertToCollapsibleState(this._collapseState);
}
this.modifications = {};
this._proxy.$updateCommentThread(
this._commentController.handle,
this.handle,
this._id!,
this._uri,
formattedModifications
);
}
getCommentByUniqueId(uniqueId: number): vscode.Comment | undefined {
for (let key of this._commentsMap) {
let comment = key[0];
let id = key[1];
if (uniqueId === id) {
return comment;
}
}
return;
}
dispose() {
this._isDiposed = true;
this._acceptInputDisposables.dispose();
this._localDisposables.forEach(disposable => disposable.dispose());
this._proxy.$deleteCommentThread(
this._commentController.handle,
this.handle
);
}
}
type ReactionHandler = (comment: vscode.Comment, reaction: vscode.CommentReaction) => Promise<void>;
class ExtHostCommentController implements vscode.CommentController {
get id(): string {
return this._id;
}
get label(): string {
return this._label;
}
public get handle(): number {
return this._handle;
}
private _threads: Map<number, ExtHostCommentThread> = new Map<number, ExtHostCommentThread>();
commentingRangeProvider?: vscode.CommentingRangeProvider;
private _reactionHandler?: ReactionHandler;
get reactionHandler(): ReactionHandler | undefined {
return this._reactionHandler;
}
set reactionHandler(handler: ReactionHandler | undefined) {
this._reactionHandler = handler;
this._proxy.$updateCommentControllerFeatures(this.handle, { reactionHandler: !!handler });
}
constructor(
private _extension: IExtensionDescription,
private _handle: number,
private _proxy: MainThreadCommentsShape,
private _id: string,
private _label: string
) {
this._proxy.$registerCommentController(this.handle, _id, _label);
}
createCommentThread(resource: vscode.Uri, range: vscode.Range, comments: vscode.Comment[]): vscode.CommentThread;
createCommentThread(arg0: vscode.Uri | string, arg1: vscode.Uri | vscode.Range, arg2: vscode.Range | vscode.Comment[], arg3?: vscode.Comment[]): vscode.CommentThread {
if (typeof arg0 === 'string') {
const commentThread = new ExtHostCommentThread(this._proxy, this, arg0, arg1 as vscode.Uri, arg2 as vscode.Range, arg3 as vscode.Comment[], this._extension.identifier);
this._threads.set(commentThread.handle, commentThread);
return commentThread;
} else {
const commentThread = new ExtHostCommentThread(this._proxy, this, undefined, arg0 as vscode.Uri, arg1 as vscode.Range, arg2 as vscode.Comment[], this._extension.identifier);
this._threads.set(commentThread.handle, commentThread);
return commentThread;
}
}
$createCommentThreadTemplate(uriComponents: UriComponents, range: IRange): ExtHostCommentThread {
const commentThread = new ExtHostCommentThread(this._proxy, this, undefined, URI.revive(uriComponents), extHostTypeConverter.Range.to(range), [], this._extension.identifier);
commentThread.collapsibleState = modes.CommentThreadCollapsibleState.Expanded;
this._threads.set(commentThread.handle, commentThread);
return commentThread;
}
$updateCommentThreadTemplate(threadHandle: number, range: IRange): void {
let thread = this._threads.get(threadHandle);
if (thread) {
thread.range = extHostTypeConverter.Range.to(range);
}
}
$deleteCommentThread(threadHandle: number): void {
let thread = this._threads.get(threadHandle);
if (thread) {
thread.dispose();
}
this._threads.delete(threadHandle);
}
getCommentThread(handle: number): ExtHostCommentThread | undefined {
return this._threads.get(handle);
}
dispose(): void {
this._threads.forEach(value => {
value.dispose();
});
this._proxy.$unregisterCommentController(this.handle);
}
}
function convertToModeComment(thread: ExtHostCommentThread, commentController: ExtHostCommentController, vscodeComment: vscode.Comment, commentsMap: Map<vscode.Comment, number>): modes.Comment {
let commentUniqueId = commentsMap.get(vscodeComment)!;
if (!commentUniqueId) {
commentUniqueId = ++thread.commentHandle;
commentsMap.set(vscodeComment, commentUniqueId);
}
const iconPath = vscodeComment.author && vscodeComment.author.iconPath ? vscodeComment.author.iconPath.toString() : undefined;
return {
mode: vscodeComment.mode,
contextValue: vscodeComment.contextValue,
uniqueIdInThread: commentUniqueId,
body: extHostTypeConverter.MarkdownString.from(vscodeComment.body),
userName: vscodeComment.author.name,
userIconPath: iconPath,
label: vscodeComment.label,
commentReactions: vscodeComment.reactions ? vscodeComment.reactions.map(reaction => convertToReaction(reaction)) : undefined
};
}
function convertToReaction(reaction: vscode.CommentReaction): modes.CommentReaction {
return {
label: reaction.label,
iconPath: reaction.iconPath ? extHostTypeConverter.pathOrURIToURI(reaction.iconPath) : undefined,
count: reaction.count,
hasReacted: reaction.authorHasReacted,
};
}
function convertFromReaction(reaction: modes.CommentReaction): vscode.CommentReaction {
return {
label: reaction.label || '',
count: reaction.count || 0,
iconPath: reaction.iconPath ? URI.revive(reaction.iconPath) : '',
authorHasReacted: reaction.hasReacted || false
};
}
function convertToCollapsibleState(kind: vscode.CommentThreadCollapsibleState | undefined): modes.CommentThreadCollapsibleState {
if (kind !== undefined) {
switch (kind) {
case types.CommentThreadCollapsibleState.Expanded:
return modes.CommentThreadCollapsibleState.Expanded;
case types.CommentThreadCollapsibleState.Collapsed:
return modes.CommentThreadCollapsibleState.Collapsed;
}
}
return modes.CommentThreadCollapsibleState.Collapsed;
}
| src/vs/workbench/api/common/extHostComments.ts | 0 | https://github.com/microsoft/vscode/commit/c0efffc91f0c4cd10e70f30229f19da96a50f960 | [
0.0001745053887134418,
0.00016980798682197928,
0.00016413348203059286,
0.00016993848839774728,
0.0000026515676836424973
] |
{
"id": 4,
"code_window": [
"export interface ICellDeleteEdit {\n",
"\teditType: CellEditType.Delete;\n",
"\tindex: number;\n",
"}\n",
"\n",
"export type ICellEditOperation = ICellInsertEdit | ICellDeleteEdit;\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tcount: number;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/common/notebookCommon.ts",
"type": "add",
"edit_start_line_idx": 226
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { readonly } from 'vs/base/common/errors';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import { ISplice } from 'vs/base/common/sequence';
import { URI, UriComponents } from 'vs/base/common/uri';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { CellKind, CellOutputKind, ExtHostNotebookShape, IMainContext, MainContext, MainThreadNotebookShape, NotebookCellOutputsSplice } from 'vs/workbench/api/common/extHost.protocol';
import { ExtHostCommands } from 'vs/workbench/api/common/extHostCommands';
import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors';
import { CellEditType, CellUri, diff, ICellEditOperation, ICellInsertEdit, IErrorOutput, INotebookDisplayOrder, INotebookEditData, IOrderedMimeType, IStreamOutput, ITransformedDisplayOutputDto, mimeTypeSupportedByCore, NotebookCellsChangedEvent, NotebookCellsSplice2, sortMimeTypes } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { Disposable as VSCodeDisposable } from './extHostTypes';
interface IObservable<T> {
proxy: T;
onDidChange: Event<void>;
}
function getObservable<T extends Object>(obj: T): IObservable<T> {
const onDidChange = new Emitter<void>();
const proxy = new Proxy(obj, {
set(target: T, p: PropertyKey, value: any, _receiver: any): boolean {
target[p as keyof T] = value;
onDidChange.fire();
return true;
}
});
return {
proxy,
onDidChange: onDidChange.event
};
}
const notebookDocumentMetadataDefaults: vscode.NotebookDocumentMetadata = {
editable: true,
cellEditable: true,
cellRunnable: true
};
export class ExtHostCell extends Disposable implements vscode.NotebookCell {
private originalSource: string[];
private _outputs: any[];
private _onDidChangeOutputs = new Emitter<ISplice<vscode.CellOutput>[]>();
onDidChangeOutputs: Event<ISplice<vscode.CellOutput>[]> = this._onDidChangeOutputs.event;
private _textDocument: vscode.TextDocument | undefined;
private _initalVersion: number = -1;
private _outputMapping = new Set<vscode.CellOutput>();
private _metadata: vscode.NotebookCellMetadata;
private _metadataChangeListener: IDisposable;
get source() {
if (this._textDocument && this._initalVersion !== this._textDocument?.version) {
return this._textDocument.getText();
} else {
return this.originalSource.join('\n');
}
}
constructor(
private viewType: string,
private documentUri: URI,
readonly handle: number,
readonly uri: URI,
private _content: string,
public readonly cellKind: CellKind,
public language: string,
outputs: any[],
_metadata: vscode.NotebookCellMetadata | undefined,
private _proxy: MainThreadNotebookShape
) {
super();
this.originalSource = this._content.split(/\r|\n|\r\n/g);
this._outputs = outputs;
const observableMetadata = getObservable(_metadata || {} as any);
this._metadata = observableMetadata.proxy;
this._metadataChangeListener = this._register(observableMetadata.onDidChange(() => {
this.updateMetadata();
}));
}
get outputs() {
return this._outputs;
}
set outputs(newOutputs: vscode.CellOutput[]) {
let diffs = diff<vscode.CellOutput>(this._outputs || [], newOutputs || [], (a) => {
return this._outputMapping.has(a);
});
diffs.forEach(diff => {
for (let i = diff.start; i < diff.start + diff.deleteCount; i++) {
this._outputMapping.delete(this._outputs[i]);
}
diff.toInsert.forEach(output => {
this._outputMapping.add(output);
});
});
this._outputs = newOutputs;
this._onDidChangeOutputs.fire(diffs);
}
get metadata() {
return this._metadata;
}
set metadata(newMetadata: vscode.NotebookCellMetadata) {
this._metadataChangeListener.dispose();
const observableMetadata = getObservable(newMetadata || {} as any); // TODO defaults
this._metadata = observableMetadata.proxy;
this._metadataChangeListener = this._register(observableMetadata.onDidChange(() => {
this.updateMetadata();
}));
this.updateMetadata();
}
private updateMetadata(): Promise<void> {
return this._proxy.$updateNotebookCellMetadata(this.viewType, this.documentUri, this.handle, this._metadata);
}
getContent(): string {
if (this._textDocument && this._initalVersion !== this._textDocument?.version) {
return this._textDocument.getText();
} else {
return this.originalSource.join('\n');
}
}
attachTextDocument(document: vscode.TextDocument) {
this._textDocument = document;
this._initalVersion = this._textDocument.version;
}
detachTextDocument() {
if (this._textDocument && this._textDocument.version !== this._initalVersion) {
this.originalSource = this._textDocument.getText().split(/\r|\n|\r\n/g);
}
this._textDocument = undefined;
this._initalVersion = -1;
}
}
export class ExtHostNotebookDocument extends Disposable implements vscode.NotebookDocument {
private static _handlePool: number = 0;
readonly handle = ExtHostNotebookDocument._handlePool++;
private _cells: ExtHostCell[] = [];
private _cellDisposableMapping = new Map<number, DisposableStore>();
get cells() {
return this._cells;
}
private _languages: string[] = [];
get languages() {
return this._languages = [];
}
set languages(newLanguages: string[]) {
this._languages = newLanguages;
this._proxy.$updateNotebookLanguages(this.viewType, this.uri, this._languages);
}
private _metadata: vscode.NotebookDocumentMetadata | undefined = notebookDocumentMetadataDefaults;
get metadata() {
return this._metadata;
}
set metadata(newMetadata: vscode.NotebookDocumentMetadata | undefined) {
this._metadata = newMetadata || notebookDocumentMetadataDefaults;
this._proxy.$updateNotebookMetadata(this.viewType, this.uri, this._metadata);
}
private _displayOrder: string[] = [];
get displayOrder() {
return this._displayOrder;
}
set displayOrder(newOrder: string[]) {
this._displayOrder = newOrder;
}
private _versionId = 0;
get versionId() {
return this._versionId;
}
constructor(
private readonly _proxy: MainThreadNotebookShape,
private _documentsAndEditors: ExtHostDocumentsAndEditors,
public viewType: string,
public uri: URI,
public renderingHandler: ExtHostNotebookOutputRenderingHandler
) {
super();
}
dispose() {
super.dispose();
this._cellDisposableMapping.forEach(cell => cell.dispose());
}
get fileName() { return this.uri.fsPath; }
get isDirty() { return false; }
accpetModelChanged(event: NotebookCellsChangedEvent) {
this.$spliceNotebookCells(event.changes);
this._versionId = event.versionId;
}
private $spliceNotebookCells(splices: NotebookCellsSplice2[]): void {
if (!splices.length) {
return;
}
splices.reverse().forEach(splice => {
let cellDtos = splice[2];
let newCells = cellDtos.map(cell => {
const extCell = new ExtHostCell(this.viewType, this.uri, cell.handle, URI.revive(cell.uri), cell.source.join('\n'), cell.cellKind, cell.language, cell.outputs, cell.metadata, this._proxy);
const document = this._documentsAndEditors.getDocument(URI.revive(cell.uri));
if (document) {
extCell.attachTextDocument(document.document);
}
if (!this._cellDisposableMapping.has(extCell.handle)) {
this._cellDisposableMapping.set(extCell.handle, new DisposableStore());
}
let store = this._cellDisposableMapping.get(extCell.handle)!;
store.add(extCell.onDidChangeOutputs((diffs) => {
this.eventuallyUpdateCellOutputs(extCell, diffs);
}));
return extCell;
});
for (let j = splice[0]; j < splice[0] + splice[1]; j++) {
this._cellDisposableMapping.get(this.cells[j].handle)?.dispose();
this._cellDisposableMapping.delete(this.cells[j].handle);
}
this.cells.splice(splice[0], splice[1], ...newCells);
});
}
eventuallyUpdateCellOutputs(cell: ExtHostCell, diffs: ISplice<vscode.CellOutput>[]) {
let renderers = new Set<number>();
let outputDtos: NotebookCellOutputsSplice[] = diffs.map(diff => {
let outputs = diff.toInsert;
let transformedOutputs = outputs.map(output => {
if (output.outputKind === CellOutputKind.Rich) {
const ret = this.transformMimeTypes(output);
if (ret.orderedMimeTypes[ret.pickedMimeTypeIndex].isResolved) {
renderers.add(ret.orderedMimeTypes[ret.pickedMimeTypeIndex].rendererId!);
}
return ret;
} else {
return output as IStreamOutput | IErrorOutput;
}
});
return [diff.start, diff.deleteCount, transformedOutputs];
});
this._proxy.$spliceNotebookCellOutputs(this.viewType, this.uri, cell.handle, outputDtos, Array.from(renderers));
}
transformMimeTypes(output: vscode.CellDisplayOutput): ITransformedDisplayOutputDto {
let mimeTypes = Object.keys(output.data);
// TODO@rebornix, the document display order might be assigned a bit later. We need to postpone sending the outputs to the core side.
let coreDisplayOrder = this.renderingHandler.outputDisplayOrder;
const sorted = sortMimeTypes(mimeTypes, coreDisplayOrder?.userOrder || [], this._displayOrder, coreDisplayOrder?.defaultOrder || []);
let orderMimeTypes: IOrderedMimeType[] = [];
sorted.forEach(mimeType => {
let handlers = this.renderingHandler.findBestMatchedRenderer(mimeType);
if (handlers.length) {
let renderedOutput = handlers[0].render(this, output, mimeType);
orderMimeTypes.push({
mimeType: mimeType,
isResolved: true,
rendererId: handlers[0].handle,
output: renderedOutput
});
for (let i = 1; i < handlers.length; i++) {
orderMimeTypes.push({
mimeType: mimeType,
isResolved: false,
rendererId: handlers[i].handle
});
}
if (mimeTypeSupportedByCore(mimeType)) {
orderMimeTypes.push({
mimeType: mimeType,
isResolved: false,
rendererId: -1
});
}
} else {
orderMimeTypes.push({
mimeType: mimeType,
isResolved: false
});
}
});
return {
outputKind: output.outputKind,
data: output.data,
orderedMimeTypes: orderMimeTypes,
pickedMimeTypeIndex: 0
};
}
getCell(cellHandle: number) {
return this.cells.find(cell => cell.handle === cellHandle);
}
attachCellTextDocument(textDocument: vscode.TextDocument) {
let cell = this.cells.find(cell => cell.uri.toString() === textDocument.uri.toString());
if (cell) {
cell.attachTextDocument(textDocument);
}
}
detachCellTextDocument(textDocument: vscode.TextDocument) {
let cell = this.cells.find(cell => cell.uri.toString() === textDocument.uri.toString());
if (cell) {
cell.detachTextDocument();
}
}
}
export class NotebookEditorCellEdit {
private _finalized: boolean = false;
private readonly _documentVersionId: number;
private _collectedEdits: ICellEditOperation[] = [];
private _renderers = new Set<number>();
constructor(
readonly editor: ExtHostNotebookEditor
) {
this._documentVersionId = editor.document.versionId;
}
finalize(): INotebookEditData {
this._finalized = true;
return {
documentVersionId: this._documentVersionId,
edits: this._collectedEdits,
renderers: Array.from(this._renderers)
};
}
private _throwIfFinalized() {
if (this._finalized) {
throw new Error('Edit is only valid while callback runs');
}
}
insert(index: number, content: string, language: string, type: CellKind, outputs: vscode.CellOutput[], metadata: vscode.NotebookCellMetadata | undefined): void {
this._throwIfFinalized();
let cell = {
source: [content],
language,
cellKind: type,
outputs: (outputs as any[]), // TODO@rebornix
metadata
};
const transformedOutputs = outputs.map(output => {
if (output.outputKind === CellOutputKind.Rich) {
const ret = this.editor.document.transformMimeTypes(output);
if (ret.orderedMimeTypes[ret.pickedMimeTypeIndex].isResolved) {
this._renderers.add(ret.orderedMimeTypes[ret.pickedMimeTypeIndex].rendererId!);
}
return ret;
} else {
return output as IStreamOutput | IErrorOutput;
}
});
cell.outputs = transformedOutputs;
this._collectedEdits.push({
editType: CellEditType.Insert,
index,
cells: [cell]
});
}
delete(index: number): void {
this._throwIfFinalized();
this._collectedEdits.push({
editType: CellEditType.Delete,
index
});
}
}
export class ExtHostNotebookEditor extends Disposable implements vscode.NotebookEditor {
private _viewColumn: vscode.ViewColumn | undefined;
onDidReceiveMessage: vscode.Event<any> = this._onDidReceiveMessage.event;
constructor(
private readonly viewType: string,
readonly id: string,
public uri: URI,
private _proxy: MainThreadNotebookShape,
private _onDidReceiveMessage: Emitter<any>,
public document: ExtHostNotebookDocument,
private _documentsAndEditors: ExtHostDocumentsAndEditors
) {
super();
this._register(this._documentsAndEditors.onDidAddDocuments(documents => {
for (const { document: textDocument } of documents) {
let data = CellUri.parse(textDocument.uri);
if (data) {
if (this.document.uri.toString() === data.notebook.toString()) {
document.attachCellTextDocument(textDocument);
}
}
}
}));
this._register(this._documentsAndEditors.onDidRemoveDocuments(documents => {
for (const { document: textDocument } of documents) {
let data = CellUri.parse(textDocument.uri);
if (data) {
if (this.document.uri.toString() === data.notebook.toString()) {
document.detachCellTextDocument(textDocument);
}
}
}
}));
}
edit(callback: (editBuilder: NotebookEditorCellEdit) => void): Thenable<boolean> {
const edit = new NotebookEditorCellEdit(this);
callback(edit);
return this._applyEdit(edit);
}
private _applyEdit(editBuilder: NotebookEditorCellEdit): Promise<boolean> {
const editData = editBuilder.finalize();
// return when there is nothing to do
if (editData.edits.length === 0) {
return Promise.resolve(true);
}
let compressedEdits: ICellEditOperation[] = [];
let compressedEditsIndex = -1;
for (let i = 0; i < editData.edits.length; i++) {
if (compressedEditsIndex < 0) {
compressedEdits.push(editData.edits[i]);
compressedEditsIndex++;
continue;
}
let prevIndex = compressedEditsIndex;
let prev = compressedEdits[prevIndex];
if (prev.editType === CellEditType.Insert && editData.edits[i].editType === CellEditType.Insert) {
if (prev.index + prev.cells.length === editData.edits[i].index) {
prev.cells.push(...(editData.edits[i] as ICellInsertEdit).cells);
continue;
}
}
compressedEdits.push(editData.edits[i]);
compressedEditsIndex++;
}
return this._proxy.$tryApplyEdits(this.viewType, this.uri, editData.documentVersionId, compressedEdits, editData.renderers);
}
get viewColumn(): vscode.ViewColumn | undefined {
return this._viewColumn;
}
set viewColumn(value) {
throw readonly('viewColumn');
}
async postMessage(message: any): Promise<boolean> {
return this._proxy.$postMessage(this.document.handle, message);
}
}
export class ExtHostNotebookOutputRenderer {
private static _handlePool: number = 0;
readonly handle = ExtHostNotebookOutputRenderer._handlePool++;
constructor(
public type: string,
public filter: vscode.NotebookOutputSelector,
public renderer: vscode.NotebookOutputRenderer
) {
}
matches(mimeType: string): boolean {
if (this.filter.subTypes) {
if (this.filter.subTypes.indexOf(mimeType) >= 0) {
return true;
}
}
return false;
}
render(document: ExtHostNotebookDocument, output: vscode.CellOutput, mimeType: string): string {
let html = this.renderer.render(document, output, mimeType);
return html;
}
}
export interface ExtHostNotebookOutputRenderingHandler {
outputDisplayOrder: INotebookDisplayOrder | undefined;
findBestMatchedRenderer(mimeType: string): ExtHostNotebookOutputRenderer[];
}
export class ExtHostNotebookController implements ExtHostNotebookShape, ExtHostNotebookOutputRenderingHandler {
private static _handlePool: number = 0;
private readonly _proxy: MainThreadNotebookShape;
private readonly _notebookProviders = new Map<string, { readonly provider: vscode.NotebookProvider, readonly extension: IExtensionDescription; }>();
private readonly _documents = new Map<string, ExtHostNotebookDocument>();
private readonly _editors = new Map<string, { editor: ExtHostNotebookEditor, onDidReceiveMessage: Emitter<any> }>();
private readonly _notebookOutputRenderers = new Map<number, ExtHostNotebookOutputRenderer>();
private _outputDisplayOrder: INotebookDisplayOrder | undefined;
get outputDisplayOrder(): INotebookDisplayOrder | undefined {
return this._outputDisplayOrder;
}
private _activeNotebookDocument: ExtHostNotebookDocument | undefined;
get activeNotebookDocument() {
return this._activeNotebookDocument;
}
constructor(mainContext: IMainContext, commands: ExtHostCommands, private _documentsAndEditors: ExtHostDocumentsAndEditors) {
this._proxy = mainContext.getProxy(MainContext.MainThreadNotebook);
commands.registerArgumentProcessor({
processArgument: arg => {
if (arg && arg.$mid === 12) {
const documentHandle = arg.notebookEditor?.notebookHandle;
const cellHandle = arg.cell.handle;
for (let value of this._editors) {
if (value[1].editor.document.handle === documentHandle) {
const cell = value[1].editor.document.getCell(cellHandle);
if (cell) {
return cell;
}
}
}
}
return arg;
}
});
}
registerNotebookOutputRenderer(
type: string,
extension: IExtensionDescription,
filter: vscode.NotebookOutputSelector,
renderer: vscode.NotebookOutputRenderer
): vscode.Disposable {
let extHostRenderer = new ExtHostNotebookOutputRenderer(type, filter, renderer);
this._notebookOutputRenderers.set(extHostRenderer.handle, extHostRenderer);
this._proxy.$registerNotebookRenderer({ id: extension.identifier, location: extension.extensionLocation }, type, filter, extHostRenderer.handle, renderer.preloads || []);
return new VSCodeDisposable(() => {
this._notebookOutputRenderers.delete(extHostRenderer.handle);
this._proxy.$unregisterNotebookRenderer(extHostRenderer.handle);
});
}
findBestMatchedRenderer(mimeType: string): ExtHostNotebookOutputRenderer[] {
let matches: ExtHostNotebookOutputRenderer[] = [];
for (let renderer of this._notebookOutputRenderers) {
if (renderer[1].matches(mimeType)) {
matches.push(renderer[1]);
}
}
return matches;
}
registerNotebookProvider(
extension: IExtensionDescription,
viewType: string,
provider: vscode.NotebookProvider,
): vscode.Disposable {
if (this._notebookProviders.has(viewType)) {
throw new Error(`Notebook provider for '${viewType}' already registered`);
}
this._notebookProviders.set(viewType, { extension, provider });
this._proxy.$registerNotebookProvider({ id: extension.identifier, location: extension.extensionLocation }, viewType);
return new VSCodeDisposable(() => {
this._notebookProviders.delete(viewType);
this._proxy.$unregisterNotebookProvider(viewType);
});
}
async $resolveNotebook(viewType: string, uri: UriComponents): Promise<number | undefined> {
let provider = this._notebookProviders.get(viewType);
if (provider) {
if (!this._documents.has(URI.revive(uri).toString())) {
let document = new ExtHostNotebookDocument(this._proxy, this._documentsAndEditors, viewType, URI.revive(uri), this);
await this._proxy.$createNotebookDocument(
document.handle,
viewType,
uri
);
this._documents.set(URI.revive(uri).toString(), document);
}
const onDidReceiveMessage = new Emitter<any>();
let editor = new ExtHostNotebookEditor(
viewType,
`${ExtHostNotebookController._handlePool++}`,
URI.revive(uri),
this._proxy,
onDidReceiveMessage,
this._documents.get(URI.revive(uri).toString())!,
this._documentsAndEditors
);
this._editors.set(URI.revive(uri).toString(), { editor, onDidReceiveMessage });
await provider.provider.resolveNotebook(editor);
// await editor.document.$updateCells();
return editor.document.handle;
}
return Promise.resolve(undefined);
}
async $executeNotebook(viewType: string, uri: UriComponents, cellHandle: number | undefined): Promise<void> {
let provider = this._notebookProviders.get(viewType);
if (!provider) {
return;
}
let document = this._documents.get(URI.revive(uri).toString());
if (!document) {
return;
}
let cell = cellHandle !== undefined ? document.getCell(cellHandle) : undefined;
return provider.provider.executeCell(document!, cell);
}
async $saveNotebook(viewType: string, uri: UriComponents): Promise<boolean> {
let provider = this._notebookProviders.get(viewType);
let document = this._documents.get(URI.revive(uri).toString());
if (provider && document) {
return await provider.provider.save(document);
}
return false;
}
async $updateActiveEditor(viewType: string, uri: UriComponents): Promise<void> {
this._activeNotebookDocument = this._documents.get(URI.revive(uri).toString());
}
async $destoryNotebookDocument(viewType: string, uri: UriComponents): Promise<boolean> {
let provider = this._notebookProviders.get(viewType);
if (!provider) {
return false;
}
let document = this._documents.get(URI.revive(uri).toString());
if (document) {
document.dispose();
this._documents.delete(URI.revive(uri).toString());
}
let editor = this._editors.get(URI.revive(uri).toString());
if (editor) {
editor.editor.dispose();
editor.onDidReceiveMessage.dispose();
this._editors.delete(URI.revive(uri).toString());
}
return true;
}
$acceptDisplayOrder(displayOrder: INotebookDisplayOrder): void {
this._outputDisplayOrder = displayOrder;
}
$onDidReceiveMessage(uri: UriComponents, message: any): void {
let editor = this._editors.get(URI.revive(uri).toString());
if (editor) {
editor.onDidReceiveMessage.fire(message);
}
}
$acceptModelChanged(uriComponents: UriComponents, event: NotebookCellsChangedEvent): void {
let editor = this._editors.get(URI.revive(uriComponents).toString());
if (editor) {
editor.editor.document.accpetModelChanged(event);
}
}
}
| src/vs/workbench/api/common/extHostNotebook.ts | 1 | https://github.com/microsoft/vscode/commit/c0efffc91f0c4cd10e70f30229f19da96a50f960 | [
0.99909508228302,
0.05294971540570259,
0.0001640755799598992,
0.00017220369772985578,
0.22294898331165314
] |
{
"id": 4,
"code_window": [
"export interface ICellDeleteEdit {\n",
"\teditType: CellEditType.Delete;\n",
"\tindex: number;\n",
"}\n",
"\n",
"export type ICellEditOperation = ICellInsertEdit | ICellDeleteEdit;\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tcount: number;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/common/notebookCommon.ts",
"type": "add",
"edit_start_line_idx": 226
} | {
"registrations": [
{
"component": {
"type": "other",
"other": {
"name": "lib-oniguruma",
"downloadUrl": "http://dl.fedoraproject.org/pub/epel/7/SRPMS/Packages/o/oniguruma-5.9.5-3.el7.src.rpm",
"version": "5.9.3"
}
},
"licenseDetail": [
"Copyright (c) 2002-2007 K.Kosako. All rights reserved.",
"",
"The BSD License",
"",
"Redistribution and use in source and binary forms, with or without",
"modification, are permitted provided that the following conditions",
"are met:",
"",
"1. Redistributions of source code must retain the above copyright",
" notice, this list of conditions and the following disclaimer.",
"",
"2. Redistributions in binary form must reproduce the above copyright",
" notice, this list of conditions and the following disclaimer in the",
" documentation and/or other materials provided with the distribution.",
"",
"THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND",
"ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE",
"IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR",
"PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS",
"BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR",
"CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF",
"SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR",
"BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,",
"WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE",
"OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN",
"IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
],
"isOnlyProductionDependency": true,
"license": "BSD",
"version": "5.9.3"
}
],
"version": 1
}
| src/vs/workbench/services/textMate/common/cgmanifest.json | 0 | https://github.com/microsoft/vscode/commit/c0efffc91f0c4cd10e70f30229f19da96a50f960 | [
0.0001753130927681923,
0.00017246705829165876,
0.00016604780103079975,
0.00017374033632222563,
0.000003428162244745181
] |
{
"id": 4,
"code_window": [
"export interface ICellDeleteEdit {\n",
"\teditType: CellEditType.Delete;\n",
"\tindex: number;\n",
"}\n",
"\n",
"export type ICellEditOperation = ICellInsertEdit | ICellDeleteEdit;\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tcount: number;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/common/notebookCommon.ts",
"type": "add",
"edit_start_line_idx": 226
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { RunOnceScheduler } from 'vs/base/common/async';
import { Disposable } from 'vs/base/common/lifecycle';
import * as platform from 'vs/base/common/platform';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { registerEditorContribution, EditorAction, ServicesAccessor, registerEditorAction } from 'vs/editor/browser/editorExtensions';
import { ConfigurationChangedEvent, EditorOption } from 'vs/editor/common/config/editorOptions';
import { ICursorSelectionChangedEvent } from 'vs/editor/common/controller/cursorEvents';
import { Range } from 'vs/editor/common/core/range';
import { IEditorContribution, Handler } from 'vs/editor/common/editorCommon';
import { EndOfLinePreference } from 'vs/editor/common/model';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { SelectionClipboardContributionID } from 'vs/workbench/contrib/codeEditor/browser/selectionClipboard';
import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle';
import { Registry } from 'vs/platform/registry/common/platform';
import { Extensions as WorkbenchExtensions, IWorkbenchContribution, IWorkbenchContributionsRegistry } from 'vs/workbench/common/contributions';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
export class SelectionClipboard extends Disposable implements IEditorContribution {
private static readonly SELECTION_LENGTH_LIMIT = 65536;
constructor(editor: ICodeEditor, @IClipboardService clipboardService: IClipboardService) {
super();
if (platform.isLinux) {
let isEnabled = editor.getOption(EditorOption.selectionClipboard);
this._register(editor.onDidChangeConfiguration((e: ConfigurationChangedEvent) => {
if (e.hasChanged(EditorOption.selectionClipboard)) {
isEnabled = editor.getOption(EditorOption.selectionClipboard);
}
}));
let setSelectionToClipboard = this._register(new RunOnceScheduler(() => {
if (!editor.hasModel()) {
return;
}
let model = editor.getModel();
let selections = editor.getSelections();
selections = selections.slice(0);
selections.sort(Range.compareRangesUsingStarts);
let resultLength = 0;
for (const sel of selections) {
if (sel.isEmpty()) {
// Only write if all cursors have selection
return;
}
resultLength += model.getValueLengthInRange(sel);
}
if (resultLength > SelectionClipboard.SELECTION_LENGTH_LIMIT) {
// This is a large selection!
// => do not write it to the selection clipboard
return;
}
let result: string[] = [];
for (const sel of selections) {
result.push(model.getValueInRange(sel, EndOfLinePreference.TextDefined));
}
let textToCopy = result.join(model.getEOL());
clipboardService.writeText(textToCopy, 'selection');
}, 100));
this._register(editor.onDidChangeCursorSelection((e: ICursorSelectionChangedEvent) => {
if (!isEnabled) {
return;
}
if (e.source === 'restoreState') {
// do not set selection to clipboard if this selection change
// was caused by restoring editors...
return;
}
setSelectionToClipboard.schedule();
}));
}
}
public dispose(): void {
super.dispose();
}
}
class SelectionClipboardPastePreventer implements IWorkbenchContribution {
constructor(
@IConfigurationService configurationService: IConfigurationService
) {
if (platform.isLinux) {
document.addEventListener('mouseup', (e) => {
if (e.button === 1) {
// middle button
const config = configurationService.getValue<{ selectionClipboard: boolean; }>('editor');
if (!config.selectionClipboard) {
// selection clipboard is disabled
// try to stop the upcoming paste
e.preventDefault();
}
}
});
}
}
}
class PasteSelectionClipboardAction extends EditorAction {
constructor() {
super({
id: 'editor.action.selectionClipboardPaste',
label: nls.localize('actions.pasteSelectionClipboard', "Paste Selection Clipboard"),
alias: 'Paste Selection Clipboard',
precondition: EditorContextKeys.writable
});
}
public async run(accessor: ServicesAccessor, editor: ICodeEditor, args: any): Promise<void> {
const clipboardService = accessor.get(IClipboardService);
// read selection clipboard
const text = await clipboardService.readText('selection');
editor.trigger('keyboard', Handler.Paste, {
text: text,
pasteOnNewLine: false,
multicursorText: null
});
}
}
registerEditorContribution(SelectionClipboardContributionID, SelectionClipboard);
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(SelectionClipboardPastePreventer, LifecyclePhase.Ready);
if (platform.isLinux) {
registerEditorAction(PasteSelectionClipboardAction);
}
| src/vs/workbench/contrib/codeEditor/electron-browser/selectionClipboard.ts | 0 | https://github.com/microsoft/vscode/commit/c0efffc91f0c4cd10e70f30229f19da96a50f960 | [
0.00017899535305332392,
0.0001710831857053563,
0.00016590948507655412,
0.00017157512775156647,
0.0000036666958749265177
] |
{
"id": 4,
"code_window": [
"export interface ICellDeleteEdit {\n",
"\teditType: CellEditType.Delete;\n",
"\tindex: number;\n",
"}\n",
"\n",
"export type ICellEditOperation = ICellInsertEdit | ICellDeleteEdit;\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tcount: number;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/common/notebookCommon.ts",
"type": "add",
"edit_start_line_idx": 226
} | /*---------------------------------------------------------------------------------------------
* 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 { setUnexpectedErrorHandler, errorHandler } from 'vs/base/common/errors';
import { URI } from 'vs/base/common/uri';
import * as types from 'vs/workbench/api/common/extHostTypes';
import { createTextModel } from 'vs/editor/test/common/editorTestUtils';
import { TestRPCProtocol } from './testRPCProtocol';
import { MarkerService } from 'vs/platform/markers/common/markerService';
import { IMarkerService } from 'vs/platform/markers/common/markers';
import { ICommandService, CommandsRegistry } from 'vs/platform/commands/common/commands';
import { IModelService } from 'vs/editor/common/services/modelService';
import { ExtHostLanguageFeatures } from 'vs/workbench/api/common/extHostLanguageFeatures';
import { MainThreadLanguageFeatures } from 'vs/workbench/api/browser/mainThreadLanguageFeatures';
import { ExtHostApiCommands } from 'vs/workbench/api/common/extHostApiCommands';
import { ExtHostCommands } from 'vs/workbench/api/common/extHostCommands';
import { MainThreadCommands } from 'vs/workbench/api/browser/mainThreadCommands';
import { ExtHostDocuments } from 'vs/workbench/api/common/extHostDocuments';
import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors';
import { MainContext, ExtHostContext } from 'vs/workbench/api/common/extHost.protocol';
import { ExtHostDiagnostics } from 'vs/workbench/api/common/extHostDiagnostics';
import type * as vscode from 'vscode';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import 'vs/workbench/contrib/search/browser/search.contribution';
import { NullLogService } from 'vs/platform/log/common/log';
import { ITextModel } from 'vs/editor/common/model';
import { nullExtensionDescription, IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { dispose } from 'vs/base/common/lifecycle';
import { IEditorWorkerService } from 'vs/editor/common/services/editorWorkerService';
import { mock } from 'vs/workbench/test/browser/api/mock';
import { NullApiDeprecationService } from 'vs/workbench/api/common/extHostApiDeprecationService';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService';
import 'vs/editor/contrib/codeAction/codeAction';
import 'vs/editor/contrib/codelens/codelens';
import 'vs/editor/contrib/colorPicker/color';
import 'vs/editor/contrib/format/format';
import 'vs/editor/contrib/gotoSymbol/goToCommands';
import 'vs/editor/contrib/hover/getHover';
import 'vs/editor/contrib/links/getLinks';
import 'vs/editor/contrib/parameterHints/provideSignatureHelp';
import 'vs/editor/contrib/quickOpen/quickOpen';
import 'vs/editor/contrib/smartSelect/smartSelect';
import 'vs/editor/contrib/suggest/suggest';
const defaultSelector = { scheme: 'far' };
const model: ITextModel = createTextModel(
[
'This is the first line',
'This is the second line',
'This is the third line',
].join('\n'),
undefined,
undefined,
URI.parse('far://testing/file.b'));
let rpcProtocol: TestRPCProtocol;
let extHost: ExtHostLanguageFeatures;
let mainThread: MainThreadLanguageFeatures;
let commands: ExtHostCommands;
let disposables: vscode.Disposable[] = [];
let originalErrorHandler: (e: any) => any;
function assertRejects(fn: () => Promise<any>, message: string = 'Expected rejection') {
return fn().then(() => assert.ok(false, message), _err => assert.ok(true));
}
suite('ExtHostLanguageFeatureCommands', function () {
suiteSetup(() => {
originalErrorHandler = errorHandler.getUnexpectedErrorHandler();
setUnexpectedErrorHandler(() => { });
// Use IInstantiationService to get typechecking when instantiating
let insta: IInstantiationService;
rpcProtocol = new TestRPCProtocol();
const services = new ServiceCollection();
services.set(IExtensionService, new class extends mock<IExtensionService>() {
async activateByEvent() {
}
});
services.set(ICommandService, new SyncDescriptor(class extends mock<ICommandService>() {
executeCommand(id: string, ...args: any): any {
const command = CommandsRegistry.getCommands().get(id);
if (!command) {
return Promise.reject(new Error(id + ' NOT known'));
}
const { handler } = command;
return Promise.resolve(insta.invokeFunction(handler, ...args));
}
}));
services.set(IMarkerService, new MarkerService());
services.set(IModelService, new class extends mock<IModelService>() {
getModel() { return model; }
});
services.set(IEditorWorkerService, new class extends mock<IEditorWorkerService>() {
async computeMoreMinimalEdits(_uri: any, edits: any) {
return edits || undefined;
}
});
insta = new InstantiationService(services);
const extHostDocumentsAndEditors = new ExtHostDocumentsAndEditors(rpcProtocol, new NullLogService());
extHostDocumentsAndEditors.$acceptDocumentsAndEditorsDelta({
addedDocuments: [{
isDirty: false,
versionId: model.getVersionId(),
modeId: model.getLanguageIdentifier().language,
uri: model.uri,
lines: model.getValue().split(model.getEOL()),
EOL: model.getEOL(),
}]
});
const extHostDocuments = new ExtHostDocuments(rpcProtocol, extHostDocumentsAndEditors);
rpcProtocol.set(ExtHostContext.ExtHostDocuments, extHostDocuments);
commands = new ExtHostCommands(rpcProtocol, new NullLogService());
rpcProtocol.set(ExtHostContext.ExtHostCommands, commands);
rpcProtocol.set(MainContext.MainThreadCommands, insta.createInstance(MainThreadCommands, rpcProtocol));
ExtHostApiCommands.register(commands);
const diagnostics = new ExtHostDiagnostics(rpcProtocol, new NullLogService());
rpcProtocol.set(ExtHostContext.ExtHostDiagnostics, diagnostics);
extHost = new ExtHostLanguageFeatures(rpcProtocol, null, extHostDocuments, commands, diagnostics, new NullLogService(), NullApiDeprecationService);
rpcProtocol.set(ExtHostContext.ExtHostLanguageFeatures, extHost);
mainThread = rpcProtocol.set(MainContext.MainThreadLanguageFeatures, insta.createInstance(MainThreadLanguageFeatures, rpcProtocol));
return rpcProtocol.sync();
});
suiteTeardown(() => {
setUnexpectedErrorHandler(originalErrorHandler);
model.dispose();
mainThread.dispose();
});
teardown(() => {
disposables = dispose(disposables);
return rpcProtocol.sync();
});
// --- workspace symbols
test('WorkspaceSymbols, invalid arguments', function () {
let promises = [
assertRejects(() => commands.executeCommand('vscode.executeWorkspaceSymbolProvider')),
assertRejects(() => commands.executeCommand('vscode.executeWorkspaceSymbolProvider', null)),
assertRejects(() => commands.executeCommand('vscode.executeWorkspaceSymbolProvider', undefined)),
assertRejects(() => commands.executeCommand('vscode.executeWorkspaceSymbolProvider', true))
];
return Promise.all(promises);
});
test('WorkspaceSymbols, back and forth', function () {
disposables.push(extHost.registerWorkspaceSymbolProvider(nullExtensionDescription, <vscode.WorkspaceSymbolProvider>{
provideWorkspaceSymbols(query): any {
return [
new types.SymbolInformation(query, types.SymbolKind.Array, new types.Range(0, 0, 1, 1), URI.parse('far://testing/first')),
new types.SymbolInformation(query, types.SymbolKind.Array, new types.Range(0, 0, 1, 1), URI.parse('far://testing/second'))
];
}
}));
disposables.push(extHost.registerWorkspaceSymbolProvider(nullExtensionDescription, <vscode.WorkspaceSymbolProvider>{
provideWorkspaceSymbols(query): any {
return [
new types.SymbolInformation(query, types.SymbolKind.Array, new types.Range(0, 0, 1, 1), URI.parse('far://testing/first'))
];
}
}));
return rpcProtocol.sync().then(() => {
return commands.executeCommand<vscode.SymbolInformation[]>('vscode.executeWorkspaceSymbolProvider', 'testing').then(value => {
for (let info of value) {
assert.ok(info instanceof types.SymbolInformation);
assert.equal(info.name, 'testing');
assert.equal(info.kind, types.SymbolKind.Array);
}
assert.equal(value.length, 3);
});
});
});
test('executeWorkspaceSymbolProvider should accept empty string, #39522', async function () {
disposables.push(extHost.registerWorkspaceSymbolProvider(nullExtensionDescription, {
provideWorkspaceSymbols(): vscode.SymbolInformation[] {
return [new types.SymbolInformation('hello', types.SymbolKind.Array, new types.Range(0, 0, 0, 0), URI.parse('foo:bar')) as vscode.SymbolInformation];
}
}));
await rpcProtocol.sync();
let symbols = await commands.executeCommand<vscode.SymbolInformation[]>('vscode.executeWorkspaceSymbolProvider', '');
assert.equal(symbols.length, 1);
await rpcProtocol.sync();
symbols = await commands.executeCommand<vscode.SymbolInformation[]>('vscode.executeWorkspaceSymbolProvider', '*');
assert.equal(symbols.length, 1);
});
// --- formatting
test('executeFormatDocumentProvider, back and forth', async function () {
disposables.push(extHost.registerDocumentFormattingEditProvider(nullExtensionDescription, defaultSelector, new class implements vscode.DocumentFormattingEditProvider {
provideDocumentFormattingEdits() {
return [types.TextEdit.insert(new types.Position(0, 0), '42')];
}
}));
await rpcProtocol.sync();
let edits = await commands.executeCommand<vscode.SymbolInformation[]>('vscode.executeFormatDocumentProvider', model.uri);
assert.equal(edits.length, 1);
});
// --- definition
test('Definition, invalid arguments', function () {
let promises = [
assertRejects(() => commands.executeCommand('vscode.executeDefinitionProvider')),
assertRejects(() => commands.executeCommand('vscode.executeDefinitionProvider', null)),
assertRejects(() => commands.executeCommand('vscode.executeDefinitionProvider', undefined)),
assertRejects(() => commands.executeCommand('vscode.executeDefinitionProvider', true, false))
];
return Promise.all(promises);
});
test('Definition, back and forth', function () {
disposables.push(extHost.registerDefinitionProvider(nullExtensionDescription, defaultSelector, <vscode.DefinitionProvider>{
provideDefinition(doc: any): any {
return new types.Location(doc.uri, new types.Range(0, 0, 0, 0));
}
}));
disposables.push(extHost.registerDefinitionProvider(nullExtensionDescription, defaultSelector, <vscode.DefinitionProvider>{
provideDefinition(doc: any): any {
return [
new types.Location(doc.uri, new types.Range(0, 0, 0, 0)),
new types.Location(doc.uri, new types.Range(0, 0, 0, 0)),
new types.Location(doc.uri, new types.Range(0, 0, 0, 0)),
];
}
}));
return rpcProtocol.sync().then(() => {
return commands.executeCommand<vscode.Location[]>('vscode.executeDefinitionProvider', model.uri, new types.Position(0, 0)).then(values => {
assert.equal(values.length, 4);
for (let v of values) {
assert.ok(v.uri instanceof URI);
assert.ok(v.range instanceof types.Range);
}
});
});
});
// --- declaration
test('Declaration, back and forth', function () {
disposables.push(extHost.registerDeclarationProvider(nullExtensionDescription, defaultSelector, <vscode.DeclarationProvider>{
provideDeclaration(doc: any): any {
return new types.Location(doc.uri, new types.Range(0, 0, 0, 0));
}
}));
disposables.push(extHost.registerDeclarationProvider(nullExtensionDescription, defaultSelector, <vscode.DeclarationProvider>{
provideDeclaration(doc: any): any {
return [
new types.Location(doc.uri, new types.Range(0, 0, 0, 0)),
new types.Location(doc.uri, new types.Range(0, 0, 0, 0)),
new types.Location(doc.uri, new types.Range(0, 0, 0, 0)),
];
}
}));
return rpcProtocol.sync().then(() => {
return commands.executeCommand<vscode.Location[]>('vscode.executeDeclarationProvider', model.uri, new types.Position(0, 0)).then(values => {
assert.equal(values.length, 4);
for (let v of values) {
assert.ok(v.uri instanceof URI);
assert.ok(v.range instanceof types.Range);
}
});
});
});
// --- type definition
test('Type Definition, invalid arguments', function () {
const promises = [
assertRejects(() => commands.executeCommand('vscode.executeTypeDefinitionProvider')),
assertRejects(() => commands.executeCommand('vscode.executeTypeDefinitionProvider', null)),
assertRejects(() => commands.executeCommand('vscode.executeTypeDefinitionProvider', undefined)),
assertRejects(() => commands.executeCommand('vscode.executeTypeDefinitionProvider', true, false))
];
return Promise.all(promises);
});
test('Type Definition, back and forth', function () {
disposables.push(extHost.registerTypeDefinitionProvider(nullExtensionDescription, defaultSelector, <vscode.TypeDefinitionProvider>{
provideTypeDefinition(doc: any): any {
return new types.Location(doc.uri, new types.Range(0, 0, 0, 0));
}
}));
disposables.push(extHost.registerTypeDefinitionProvider(nullExtensionDescription, defaultSelector, <vscode.TypeDefinitionProvider>{
provideTypeDefinition(doc: any): any {
return [
new types.Location(doc.uri, new types.Range(0, 0, 0, 0)),
new types.Location(doc.uri, new types.Range(0, 0, 0, 0)),
new types.Location(doc.uri, new types.Range(0, 0, 0, 0)),
];
}
}));
return rpcProtocol.sync().then(() => {
return commands.executeCommand<vscode.Location[]>('vscode.executeTypeDefinitionProvider', model.uri, new types.Position(0, 0)).then(values => {
assert.equal(values.length, 4);
for (const v of values) {
assert.ok(v.uri instanceof URI);
assert.ok(v.range instanceof types.Range);
}
});
});
});
// --- references
test('reference search, back and forth', function () {
disposables.push(extHost.registerReferenceProvider(nullExtensionDescription, defaultSelector, <vscode.ReferenceProvider>{
provideReferences() {
return [
new types.Location(URI.parse('some:uri/path'), new types.Range(0, 1, 0, 5))
];
}
}));
return commands.executeCommand<vscode.Location[]>('vscode.executeReferenceProvider', model.uri, new types.Position(0, 0)).then(values => {
assert.equal(values.length, 1);
let [first] = values;
assert.equal(first.uri.toString(), 'some:uri/path');
assert.equal(first.range.start.line, 0);
assert.equal(first.range.start.character, 1);
assert.equal(first.range.end.line, 0);
assert.equal(first.range.end.character, 5);
});
});
// --- outline
test('Outline, back and forth', function () {
disposables.push(extHost.registerDocumentSymbolProvider(nullExtensionDescription, defaultSelector, <vscode.DocumentSymbolProvider>{
provideDocumentSymbols(): any {
return [
new types.SymbolInformation('testing1', types.SymbolKind.Enum, new types.Range(1, 0, 1, 0)),
new types.SymbolInformation('testing2', types.SymbolKind.Enum, new types.Range(0, 1, 0, 3)),
];
}
}));
return rpcProtocol.sync().then(() => {
return commands.executeCommand<vscode.SymbolInformation[]>('vscode.executeDocumentSymbolProvider', model.uri).then(values => {
assert.equal(values.length, 2);
let [first, second] = values;
assert.ok(first instanceof types.SymbolInformation);
assert.ok(second instanceof types.SymbolInformation);
assert.equal(first.name, 'testing2');
assert.equal(second.name, 'testing1');
});
});
});
test('vscode.executeDocumentSymbolProvider command only returns SymbolInformation[] rather than DocumentSymbol[] #57984', function () {
disposables.push(extHost.registerDocumentSymbolProvider(nullExtensionDescription, defaultSelector, <vscode.DocumentSymbolProvider>{
provideDocumentSymbols(): any {
return [
new types.SymbolInformation('SymbolInformation', types.SymbolKind.Enum, new types.Range(1, 0, 1, 0))
];
}
}));
disposables.push(extHost.registerDocumentSymbolProvider(nullExtensionDescription, defaultSelector, <vscode.DocumentSymbolProvider>{
provideDocumentSymbols(): any {
let root = new types.DocumentSymbol('DocumentSymbol', 'DocumentSymbol#detail', types.SymbolKind.Enum, new types.Range(1, 0, 1, 0), new types.Range(1, 0, 1, 0));
root.children = [new types.DocumentSymbol('DocumentSymbol#child', 'DocumentSymbol#detail#child', types.SymbolKind.Enum, new types.Range(1, 0, 1, 0), new types.Range(1, 0, 1, 0))];
return [root];
}
}));
return rpcProtocol.sync().then(() => {
return commands.executeCommand<(vscode.SymbolInformation & vscode.DocumentSymbol)[]>('vscode.executeDocumentSymbolProvider', model.uri).then(values => {
assert.equal(values.length, 2);
let [first, second] = values;
assert.ok(first instanceof types.SymbolInformation);
assert.ok(!(first instanceof types.DocumentSymbol));
assert.ok(second instanceof types.SymbolInformation);
assert.equal(first.name, 'DocumentSymbol');
assert.equal(first.children.length, 1);
assert.equal(second.name, 'SymbolInformation');
});
});
});
// --- suggest
test('Suggest, back and forth', function () {
disposables.push(extHost.registerCompletionItemProvider(nullExtensionDescription, defaultSelector, <vscode.CompletionItemProvider>{
provideCompletionItems(): any {
let a = new types.CompletionItem('item1');
let b = new types.CompletionItem('item2');
b.textEdit = types.TextEdit.replace(new types.Range(0, 4, 0, 8), 'foo'); // overwite after
let c = new types.CompletionItem('item3');
c.textEdit = types.TextEdit.replace(new types.Range(0, 1, 0, 6), 'foobar'); // overwite before & after
// snippet string!
let d = new types.CompletionItem('item4');
d.range = new types.Range(0, 1, 0, 4);// overwite before
d.insertText = new types.SnippetString('foo$0bar');
return [a, b, c, d];
}
}, []));
return rpcProtocol.sync().then(() => {
return commands.executeCommand<vscode.CompletionList>('vscode.executeCompletionItemProvider', model.uri, new types.Position(0, 4)).then(list => {
assert.ok(list instanceof types.CompletionList);
let values = list.items;
assert.ok(Array.isArray(values));
assert.equal(values.length, 4);
let [first, second, third, fourth] = values;
assert.equal(first.label, 'item1');
assert.equal(first.textEdit, undefined);// no text edit, default ranges
assert.ok(!types.Range.isRange(first.range));
assert.equal(second.label, 'item2');
assert.equal(second.textEdit!.newText, 'foo');
assert.equal(second.textEdit!.range.start.line, 0);
assert.equal(second.textEdit!.range.start.character, 4);
assert.equal(second.textEdit!.range.end.line, 0);
assert.equal(second.textEdit!.range.end.character, 8);
assert.equal(third.label, 'item3');
assert.equal(third.textEdit!.newText, 'foobar');
assert.equal(third.textEdit!.range.start.line, 0);
assert.equal(third.textEdit!.range.start.character, 1);
assert.equal(third.textEdit!.range.end.line, 0);
assert.equal(third.textEdit!.range.end.character, 6);
assert.equal(fourth.label, 'item4');
assert.equal(fourth.textEdit, undefined);
const range: any = fourth.range!;
assert.ok(types.Range.isRange(range));
assert.equal(range.start.line, 0);
assert.equal(range.start.character, 1);
assert.equal(range.end.line, 0);
assert.equal(range.end.character, 4);
assert.ok(fourth.insertText instanceof types.SnippetString);
assert.equal((<types.SnippetString>fourth.insertText).value, 'foo$0bar');
});
});
});
test('Suggest, return CompletionList !array', function () {
disposables.push(extHost.registerCompletionItemProvider(nullExtensionDescription, defaultSelector, <vscode.CompletionItemProvider>{
provideCompletionItems(): any {
let a = new types.CompletionItem('item1');
let b = new types.CompletionItem('item2');
return new types.CompletionList(<any>[a, b], true);
}
}, []));
return rpcProtocol.sync().then(() => {
return commands.executeCommand<vscode.CompletionList>('vscode.executeCompletionItemProvider', model.uri, new types.Position(0, 4)).then(list => {
assert.ok(list instanceof types.CompletionList);
assert.equal(list.isIncomplete, true);
});
});
});
test('Suggest, resolve completion items', async function () {
let resolveCount = 0;
disposables.push(extHost.registerCompletionItemProvider(nullExtensionDescription, defaultSelector, <vscode.CompletionItemProvider>{
provideCompletionItems(): any {
let a = new types.CompletionItem('item1');
let b = new types.CompletionItem('item2');
let c = new types.CompletionItem('item3');
let d = new types.CompletionItem('item4');
return new types.CompletionList([a, b, c, d], false);
},
resolveCompletionItem(item) {
resolveCount += 1;
return item;
}
}, []));
await rpcProtocol.sync();
let list = await commands.executeCommand<vscode.CompletionList>(
'vscode.executeCompletionItemProvider',
model.uri,
new types.Position(0, 4),
undefined,
2 // maxItemsToResolve
);
assert.ok(list instanceof types.CompletionList);
assert.equal(resolveCount, 2);
});
test('"vscode.executeCompletionItemProvider" doesnot return a preselect field #53749', async function () {
disposables.push(extHost.registerCompletionItemProvider(nullExtensionDescription, defaultSelector, <vscode.CompletionItemProvider>{
provideCompletionItems(): any {
let a = new types.CompletionItem('item1');
a.preselect = true;
let b = new types.CompletionItem('item2');
let c = new types.CompletionItem('item3');
c.preselect = true;
let d = new types.CompletionItem('item4');
return new types.CompletionList([a, b, c, d], false);
}
}, []));
await rpcProtocol.sync();
let list = await commands.executeCommand<vscode.CompletionList>(
'vscode.executeCompletionItemProvider',
model.uri,
new types.Position(0, 4),
undefined
);
assert.ok(list instanceof types.CompletionList);
assert.equal(list.items.length, 4);
let [a, b, c, d] = list.items;
assert.equal(a.preselect, true);
assert.equal(b.preselect, undefined);
assert.equal(c.preselect, true);
assert.equal(d.preselect, undefined);
});
test('executeCompletionItemProvider doesn\'t capture commitCharacters #58228', async function () {
disposables.push(extHost.registerCompletionItemProvider(nullExtensionDescription, defaultSelector, <vscode.CompletionItemProvider>{
provideCompletionItems(): any {
let a = new types.CompletionItem('item1');
a.commitCharacters = ['a', 'b'];
let b = new types.CompletionItem('item2');
return new types.CompletionList([a, b], false);
}
}, []));
await rpcProtocol.sync();
let list = await commands.executeCommand<vscode.CompletionList>(
'vscode.executeCompletionItemProvider',
model.uri,
new types.Position(0, 4),
undefined
);
assert.ok(list instanceof types.CompletionList);
assert.equal(list.items.length, 2);
let [a, b] = list.items;
assert.deepEqual(a.commitCharacters, ['a', 'b']);
assert.equal(b.commitCharacters, undefined);
});
// --- signatureHelp
test('Parameter Hints, back and forth', async () => {
disposables.push(extHost.registerSignatureHelpProvider(nullExtensionDescription, defaultSelector, new class implements vscode.SignatureHelpProvider {
provideSignatureHelp(_document: vscode.TextDocument, _position: vscode.Position, _token: vscode.CancellationToken, context: vscode.SignatureHelpContext): vscode.SignatureHelp {
return {
activeSignature: 0,
activeParameter: 1,
signatures: [
{
label: 'abc',
documentation: `${context.triggerKind === 1 /* vscode.SignatureHelpTriggerKind.Invoke */ ? 'invoked' : 'unknown'} ${context.triggerCharacter}`,
parameters: []
}
]
};
}
}, []));
await rpcProtocol.sync();
const firstValue = await commands.executeCommand<vscode.SignatureHelp>('vscode.executeSignatureHelpProvider', model.uri, new types.Position(0, 1), ',');
assert.strictEqual(firstValue.activeSignature, 0);
assert.strictEqual(firstValue.activeParameter, 1);
assert.strictEqual(firstValue.signatures.length, 1);
assert.strictEqual(firstValue.signatures[0].label, 'abc');
assert.strictEqual(firstValue.signatures[0].documentation, 'invoked ,');
});
// --- quickfix
test('QuickFix, back and forth', function () {
disposables.push(extHost.registerCodeActionProvider(nullExtensionDescription, defaultSelector, {
provideCodeActions(): vscode.Command[] {
return [{ command: 'testing', title: 'Title', arguments: [1, 2, true] }];
}
}));
return rpcProtocol.sync().then(() => {
return commands.executeCommand<vscode.Command[]>('vscode.executeCodeActionProvider', model.uri, new types.Range(0, 0, 1, 1)).then(value => {
assert.equal(value.length, 1);
let [first] = value;
assert.equal(first.title, 'Title');
assert.equal(first.command, 'testing');
assert.deepEqual(first.arguments, [1, 2, true]);
});
});
});
test('vscode.executeCodeActionProvider results seem to be missing their `command` property #45124', function () {
disposables.push(extHost.registerCodeActionProvider(nullExtensionDescription, defaultSelector, {
provideCodeActions(document, range): vscode.CodeAction[] {
return [{
command: {
arguments: [document, range],
command: 'command',
title: 'command_title',
},
kind: types.CodeActionKind.Empty.append('foo'),
title: 'title',
}];
}
}));
return rpcProtocol.sync().then(() => {
return commands.executeCommand<vscode.CodeAction[]>('vscode.executeCodeActionProvider', model.uri, new types.Range(0, 0, 1, 1)).then(value => {
assert.equal(value.length, 1);
const [first] = value;
assert.ok(first.command);
assert.equal(first.command!.command, 'command');
assert.equal(first.command!.title, 'command_title');
assert.equal(first.kind!.value, 'foo');
assert.equal(first.title, 'title');
});
});
});
test('vscode.executeCodeActionProvider passes Range to provider although Selection is passed in #77997', function () {
disposables.push(extHost.registerCodeActionProvider(nullExtensionDescription, defaultSelector, {
provideCodeActions(document, rangeOrSelection): vscode.CodeAction[] {
return [{
command: {
arguments: [document, rangeOrSelection],
command: 'command',
title: 'command_title',
},
kind: types.CodeActionKind.Empty.append('foo'),
title: 'title',
}];
}
}));
const selection = new types.Selection(0, 0, 1, 1);
return rpcProtocol.sync().then(() => {
return commands.executeCommand<vscode.CodeAction[]>('vscode.executeCodeActionProvider', model.uri, selection).then(value => {
assert.equal(value.length, 1);
const [first] = value;
assert.ok(first.command);
assert.ok(first.command!.arguments![1] instanceof types.Selection);
assert.ok(first.command!.arguments![1].isEqual(selection));
});
});
});
test('vscode.executeCodeActionProvider results seem to be missing their `isPreferred` property #78098', function () {
disposables.push(extHost.registerCodeActionProvider(nullExtensionDescription, defaultSelector, {
provideCodeActions(document, rangeOrSelection): vscode.CodeAction[] {
return [{
command: {
arguments: [document, rangeOrSelection],
command: 'command',
title: 'command_title',
},
kind: types.CodeActionKind.Empty.append('foo'),
title: 'title',
isPreferred: true
}];
}
}));
const selection = new types.Selection(0, 0, 1, 1);
return rpcProtocol.sync().then(() => {
return commands.executeCommand<vscode.CodeAction[]>('vscode.executeCodeActionProvider', model.uri, selection).then(value => {
assert.equal(value.length, 1);
const [first] = value;
assert.equal(first.isPreferred, true);
});
});
});
// --- code lens
test('CodeLens, back and forth', function () {
const complexArg = {
foo() { },
bar() { },
big: extHost
};
disposables.push(extHost.registerCodeLensProvider(nullExtensionDescription, defaultSelector, <vscode.CodeLensProvider>{
provideCodeLenses(): any {
return [new types.CodeLens(new types.Range(0, 0, 1, 1), { title: 'Title', command: 'cmd', arguments: [1, true, complexArg] })];
}
}));
return rpcProtocol.sync().then(() => {
return commands.executeCommand<vscode.CodeLens[]>('vscode.executeCodeLensProvider', model.uri).then(value => {
assert.equal(value.length, 1);
const [first] = value;
assert.equal(first.command!.title, 'Title');
assert.equal(first.command!.command, 'cmd');
assert.equal(first.command!.arguments![0], 1);
assert.equal(first.command!.arguments![1], true);
assert.equal(first.command!.arguments![2], complexArg);
});
});
});
test('CodeLens, resolve', async function () {
let resolveCount = 0;
disposables.push(extHost.registerCodeLensProvider(nullExtensionDescription, defaultSelector, <vscode.CodeLensProvider>{
provideCodeLenses(): any {
return [
new types.CodeLens(new types.Range(0, 0, 1, 1)),
new types.CodeLens(new types.Range(0, 0, 1, 1)),
new types.CodeLens(new types.Range(0, 0, 1, 1)),
new types.CodeLens(new types.Range(0, 0, 1, 1), { title: 'Already resolved', command: 'fff' })
];
},
resolveCodeLens(codeLens: types.CodeLens) {
codeLens.command = { title: resolveCount.toString(), command: 'resolved' };
resolveCount += 1;
return codeLens;
}
}));
await rpcProtocol.sync();
let value = await commands.executeCommand<vscode.CodeLens[]>('vscode.executeCodeLensProvider', model.uri, 2);
assert.equal(value.length, 3); // the resolve argument defines the number of results being returned
assert.equal(resolveCount, 2);
resolveCount = 0;
value = await commands.executeCommand<vscode.CodeLens[]>('vscode.executeCodeLensProvider', model.uri);
assert.equal(value.length, 4);
assert.equal(resolveCount, 0);
});
test('Links, back and forth', function () {
disposables.push(extHost.registerDocumentLinkProvider(nullExtensionDescription, defaultSelector, <vscode.DocumentLinkProvider>{
provideDocumentLinks(): any {
return [new types.DocumentLink(new types.Range(0, 0, 0, 20), URI.parse('foo:bar'))];
}
}));
return rpcProtocol.sync().then(() => {
return commands.executeCommand<vscode.DocumentLink[]>('vscode.executeLinkProvider', model.uri).then(value => {
assert.equal(value.length, 1);
let [first] = value;
assert.equal(first.target + '', 'foo:bar');
assert.equal(first.range.start.line, 0);
assert.equal(first.range.start.character, 0);
assert.equal(first.range.end.line, 0);
assert.equal(first.range.end.character, 20);
});
});
});
test('Color provider', function () {
disposables.push(extHost.registerColorProvider(nullExtensionDescription, defaultSelector, <vscode.DocumentColorProvider>{
provideDocumentColors(): vscode.ColorInformation[] {
return [new types.ColorInformation(new types.Range(0, 0, 0, 20), new types.Color(0.1, 0.2, 0.3, 0.4))];
},
provideColorPresentations(): vscode.ColorPresentation[] {
const cp = new types.ColorPresentation('#ABC');
cp.textEdit = types.TextEdit.replace(new types.Range(1, 0, 1, 20), '#ABC');
cp.additionalTextEdits = [types.TextEdit.insert(new types.Position(2, 20), '*')];
return [cp];
}
}));
return rpcProtocol.sync().then(() => {
return commands.executeCommand<vscode.ColorInformation[]>('vscode.executeDocumentColorProvider', model.uri).then(value => {
assert.equal(value.length, 1);
let [first] = value;
assert.equal(first.color.red, 0.1);
assert.equal(first.color.green, 0.2);
assert.equal(first.color.blue, 0.3);
assert.equal(first.color.alpha, 0.4);
assert.equal(first.range.start.line, 0);
assert.equal(first.range.start.character, 0);
assert.equal(first.range.end.line, 0);
assert.equal(first.range.end.character, 20);
});
}).then(() => {
const color = new types.Color(0.5, 0.6, 0.7, 0.8);
const range = new types.Range(0, 0, 0, 20);
return commands.executeCommand<vscode.ColorPresentation[]>('vscode.executeColorPresentationProvider', color, { uri: model.uri, range }).then(value => {
assert.equal(value.length, 1);
let [first] = value;
assert.equal(first.label, '#ABC');
assert.equal(first.textEdit!.newText, '#ABC');
assert.equal(first.textEdit!.range.start.line, 1);
assert.equal(first.textEdit!.range.start.character, 0);
assert.equal(first.textEdit!.range.end.line, 1);
assert.equal(first.textEdit!.range.end.character, 20);
assert.equal(first.additionalTextEdits!.length, 1);
assert.equal(first.additionalTextEdits![0].range.start.line, 2);
assert.equal(first.additionalTextEdits![0].range.start.character, 20);
assert.equal(first.additionalTextEdits![0].range.end.line, 2);
assert.equal(first.additionalTextEdits![0].range.end.character, 20);
});
});
});
test('"TypeError: e.onCancellationRequested is not a function" calling hover provider in Insiders #54174', function () {
disposables.push(extHost.registerHoverProvider(nullExtensionDescription, defaultSelector, <vscode.HoverProvider>{
provideHover(): any {
return new types.Hover('fofofofo');
}
}));
return rpcProtocol.sync().then(() => {
return commands.executeCommand<vscode.Hover[]>('vscode.executeHoverProvider', model.uri, new types.Position(1, 1)).then(value => {
assert.equal(value.length, 1);
assert.equal(value[0].contents.length, 1);
});
});
});
// --- selection ranges
test('Selection Range, back and forth', async function () {
disposables.push(extHost.registerSelectionRangeProvider(nullExtensionDescription, defaultSelector, <vscode.SelectionRangeProvider>{
provideSelectionRanges() {
return [
new types.SelectionRange(new types.Range(0, 10, 0, 18), new types.SelectionRange(new types.Range(0, 2, 0, 20))),
];
}
}));
await rpcProtocol.sync();
let value = await commands.executeCommand<vscode.SelectionRange[]>('vscode.executeSelectionRangeProvider', model.uri, [new types.Position(0, 10)]);
assert.equal(value.length, 1);
assert.ok(value[0].parent);
});
// --- call hierarcht
test('CallHierarchy, back and forth', async function () {
disposables.push(extHost.registerCallHierarchyProvider(nullExtensionDescription, defaultSelector, new class implements vscode.CallHierarchyProvider {
prepareCallHierarchy(document: vscode.TextDocument, position: vscode.Position,): vscode.ProviderResult<vscode.CallHierarchyItem> {
return new types.CallHierarchyItem(types.SymbolKind.Constant, 'ROOT', 'ROOT', document.uri, new types.Range(0, 0, 0, 0), new types.Range(0, 0, 0, 0));
}
provideCallHierarchyIncomingCalls(item: vscode.CallHierarchyItem, token: vscode.CancellationToken): vscode.ProviderResult<vscode.CallHierarchyIncomingCall[]> {
return [new types.CallHierarchyIncomingCall(
new types.CallHierarchyItem(types.SymbolKind.Constant, 'INCOMING', 'INCOMING', item.uri, new types.Range(0, 0, 0, 0), new types.Range(0, 0, 0, 0)),
[new types.Range(0, 0, 0, 0)]
)];
}
provideCallHierarchyOutgoingCalls(item: vscode.CallHierarchyItem, token: vscode.CancellationToken): vscode.ProviderResult<vscode.CallHierarchyOutgoingCall[]> {
return [new types.CallHierarchyOutgoingCall(
new types.CallHierarchyItem(types.SymbolKind.Constant, 'OUTGOING', 'OUTGOING', item.uri, new types.Range(0, 0, 0, 0), new types.Range(0, 0, 0, 0)),
[new types.Range(0, 0, 0, 0)]
)];
}
}));
await rpcProtocol.sync();
const root = await commands.executeCommand<vscode.CallHierarchyItem[]>('vscode.prepareCallHierarchy', model.uri, new types.Position(0, 0));
assert.ok(Array.isArray(root));
assert.equal(root.length, 1);
assert.equal(root[0].name, 'ROOT');
const incoming = await commands.executeCommand<vscode.CallHierarchyIncomingCall[]>('vscode.provideIncomingCalls', root[0]);
assert.equal(incoming.length, 1);
assert.equal(incoming[0].from.name, 'INCOMING');
const outgoing = await commands.executeCommand<vscode.CallHierarchyOutgoingCall[]>('vscode.provideOutgoingCalls', root[0]);
assert.equal(outgoing.length, 1);
assert.equal(outgoing[0].to.name, 'OUTGOING');
});
test('selectionRangeProvider on inner array always returns outer array #91852', async function () {
disposables.push(extHost.registerSelectionRangeProvider(nullExtensionDescription, defaultSelector, <vscode.SelectionRangeProvider>{
provideSelectionRanges(_doc, positions) {
const [first] = positions;
return [
new types.SelectionRange(new types.Range(first.line, first.character, first.line, first.character)),
];
}
}));
await rpcProtocol.sync();
let value = await commands.executeCommand<vscode.SelectionRange[]>('vscode.executeSelectionRangeProvider', model.uri, [new types.Position(0, 10)]);
assert.equal(value.length, 1);
assert.equal(value[0].range.start.line, 0);
assert.equal(value[0].range.start.character, 10);
assert.equal(value[0].range.end.line, 0);
assert.equal(value[0].range.end.character, 10);
});
test('selectionRangeProvider on inner array always returns outer array #91852', async function () {
disposables.push(extHost.registerSelectionRangeProvider(nullExtensionDescription, defaultSelector, <vscode.SelectionRangeProvider>{
provideSelectionRanges(_doc, positions) {
const [first, second] = positions;
return [
new types.SelectionRange(new types.Range(first.line, first.character, first.line, first.character)),
new types.SelectionRange(new types.Range(second.line, second.character, second.line, second.character)),
];
}
}));
await rpcProtocol.sync();
let value = await commands.executeCommand<vscode.SelectionRange[]>(
'vscode.executeSelectionRangeProvider',
model.uri,
[new types.Position(0, 0), new types.Position(0, 10)]
);
assert.equal(value.length, 2);
assert.equal(value[0].range.start.line, 0);
assert.equal(value[0].range.start.character, 0);
assert.equal(value[0].range.end.line, 0);
assert.equal(value[0].range.end.character, 0);
assert.equal(value[1].range.start.line, 0);
assert.equal(value[1].range.start.character, 10);
assert.equal(value[1].range.end.line, 0);
assert.equal(value[1].range.end.character, 10);
});
});
| src/vs/workbench/test/browser/api/extHostApiCommands.test.ts | 0 | https://github.com/microsoft/vscode/commit/c0efffc91f0c4cd10e70f30229f19da96a50f960 | [
0.00017726985970512033,
0.00017317653691861778,
0.0001610631588846445,
0.0001735070691211149,
0.0000027119631340610795
] |
{
"id": 0,
"code_window": [
"function wrapCorePresets(presets) {\n",
" return {\n",
" babel: async (config, args) => presets.apply('babel', config, args),\n",
" webpack: async (config, args) => presets.apply('webpack', config, args),\n",
" webpackFinal: async (config, args) => presets.apply('webpackFinal', config, args),\n",
" preview: async (config, args) => presets.apply('preview', config, args),\n",
" manager: async (config, args) => presets.apply('manager', config, args),\n",
" };\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "lib/core/src/server/config.js",
"type": "replace",
"edit_start_line_idx": 9
} | import path from 'path';
import { logger } from '@storybook/node-logger';
import loadPresets from './presets';
import serverRequire from './serverRequire';
function wrapCorePresets(presets) {
return {
babel: async (config, args) => presets.apply('babel', config, args),
webpack: async (config, args) => presets.apply('webpack', config, args),
webpackFinal: async (config, args) => presets.apply('webpackFinal', config, args),
preview: async (config, args) => presets.apply('preview', config, args),
manager: async (config, args) => presets.apply('manager', config, args),
};
}
function customPreset({ configDir }) {
const presets = serverRequire(path.resolve(configDir, 'presets'));
if (presets) {
logger.warn(
'"Custom presets" is an experimental and undocumented feature that will be changed or deprecated soon. Use it on your own risk.'
);
return presets;
}
return [];
}
async function getWebpackConfig(options, presets) {
const babelOptions = await presets.babel({}, options);
const entries = {
iframe: await presets.preview([], options),
manager: await presets.manager([], options),
};
const webpackConfig = await presets.webpack({}, { ...options, babelOptions, entries });
return presets.webpackFinal(webpackConfig, options);
}
export default async options => {
const { corePresets = [], frameworkPresets = [], ...restOptions } = options;
const presetsConfig = [
...corePresets,
require.resolve('./core-preset-babel-cache.js'),
...frameworkPresets,
...customPreset(options),
require.resolve('./core-preset-webpack-custom.js'),
];
const presets = loadPresets(presetsConfig);
return getWebpackConfig({ ...restOptions, presets }, wrapCorePresets(presets));
};
| lib/core/src/server/config.js | 1 | https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9 | [
0.9978458881378174,
0.3404783010482788,
0.005948533769696951,
0.025493279099464417,
0.45902135968208313
] |
{
"id": 0,
"code_window": [
"function wrapCorePresets(presets) {\n",
" return {\n",
" babel: async (config, args) => presets.apply('babel', config, args),\n",
" webpack: async (config, args) => presets.apply('webpack', config, args),\n",
" webpackFinal: async (config, args) => presets.apply('webpackFinal', config, args),\n",
" preview: async (config, args) => presets.apply('preview', config, args),\n",
" manager: async (config, args) => presets.apply('manager', config, args),\n",
" };\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "lib/core/src/server/config.js",
"type": "replace",
"edit_start_line_idx": 9
} | package OpenSourceProjects_Storybook.buildTypes
import jetbrains.buildServer.configs.kotlin.v2017_2.*
import jetbrains.buildServer.configs.kotlin.v2017_2.buildFeatures.commitStatusPublisher
import jetbrains.buildServer.configs.kotlin.v2017_2.buildSteps.script
object OpenSourceProjects_Storybook_CliTest : BuildType({
uuid = "b1db1a3a-a4cf-46ea-8f55-98b86611f92e"
id = "OpenSourceProjects_Storybook_CliTest"
name = "CLI test"
vcs {
root(OpenSourceProjects_Storybook.vcsRoots.OpenSourceProjects_Storybook_HttpsGithubComStorybooksStorybookRefsHeadsMaster)
}
steps {
script {
name = "Test"
scriptContent = """
#!/bin/sh
set -e -x
yarn
yarn test --cli
""".trimIndent()
dockerImage = "node:%docker.node.version%"
}
}
features {
commitStatusPublisher {
publisher = github {
githubUrl = "https://api.github.com"
authType = personalToken {
token = "credentialsJSON:5ffe2d7e-531e-4f6f-b1fc-a41bfea26eaa"
}
}
param("github_oauth_user", "Hypnosphi")
}
}
dependencies {
dependency(OpenSourceProjects_Storybook.buildTypes.OpenSourceProjects_Storybook_Bootstrap) {
snapshot {
onDependencyFailure = FailureAction.FAIL_TO_START
}
artifacts {
artifactRules = "dist.zip!**"
}
}
}
requirements {
doesNotContain("env.OS", "Windows")
}
cleanup {
artifacts(days = 1)
}
})
| .teamcity/OpenSourceProjects_Storybook/buildTypes/OpenSourceProjects_Storybook_CliTest.kt | 0 | https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9 | [
0.00017435521294828504,
0.00017222703900188208,
0.00016533242887817323,
0.00017358071636408567,
0.0000029001362236158457
] |
{
"id": 0,
"code_window": [
"function wrapCorePresets(presets) {\n",
" return {\n",
" babel: async (config, args) => presets.apply('babel', config, args),\n",
" webpack: async (config, args) => presets.apply('webpack', config, args),\n",
" webpackFinal: async (config, args) => presets.apply('webpackFinal', config, args),\n",
" preview: async (config, args) => presets.apply('preview', config, args),\n",
" manager: async (config, args) => presets.apply('manager', config, args),\n",
" };\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "lib/core/src/server/config.js",
"type": "replace",
"edit_start_line_idx": 9
} | import 'react-native';
import React from 'react';
import Index from '../index.android.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
| lib/cli/test/fixtures/react_native/__tests__/index.android.js | 0 | https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9 | [
0.0001766843197401613,
0.00017396578914485872,
0.00017124727310147136,
0.00017396578914485872,
0.0000027185233193449676
] |
{
"id": 0,
"code_window": [
"function wrapCorePresets(presets) {\n",
" return {\n",
" babel: async (config, args) => presets.apply('babel', config, args),\n",
" webpack: async (config, args) => presets.apply('webpack', config, args),\n",
" webpackFinal: async (config, args) => presets.apply('webpackFinal', config, args),\n",
" preview: async (config, args) => presets.apply('preview', config, args),\n",
" manager: async (config, args) => presets.apply('manager', config, args),\n",
" };\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "lib/core/src/server/config.js",
"type": "replace",
"edit_start_line_idx": 9
} | import React from 'react';
import ReactDOM from 'react-dom';
import { document } from 'global';
import App from './App';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
});
| examples/cra-kitchen-sink/src/App.test.js | 0 | https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9 | [
0.0001743997709127143,
0.000172316882526502,
0.0001702339795883745,
0.000172316882526502,
0.0000020828956621699035
] |
{
"id": 1,
"code_window": [
" const entries = {\n",
" iframe: await presets.preview([], options),\n",
" manager: await presets.manager([], options),\n",
" };\n",
"\n",
" const webpackConfig = await presets.webpack({}, { ...options, babelOptions, entries });\n",
"\n",
" return presets.webpackFinal(webpackConfig, options);\n",
"}\n",
"\n",
"export default async options => {\n",
" const { corePresets = [], frameworkPresets = [], ...restOptions } = options;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return presets.webpack({}, { ...options, babelOptions, entries });\n"
],
"file_path": "lib/core/src/server/config.js",
"type": "replace",
"edit_start_line_idx": 37
} | import path from 'path';
import { logger } from '@storybook/node-logger';
import loadPresets from './presets';
import serverRequire from './serverRequire';
function wrapCorePresets(presets) {
return {
babel: async (config, args) => presets.apply('babel', config, args),
webpack: async (config, args) => presets.apply('webpack', config, args),
webpackFinal: async (config, args) => presets.apply('webpackFinal', config, args),
preview: async (config, args) => presets.apply('preview', config, args),
manager: async (config, args) => presets.apply('manager', config, args),
};
}
function customPreset({ configDir }) {
const presets = serverRequire(path.resolve(configDir, 'presets'));
if (presets) {
logger.warn(
'"Custom presets" is an experimental and undocumented feature that will be changed or deprecated soon. Use it on your own risk.'
);
return presets;
}
return [];
}
async function getWebpackConfig(options, presets) {
const babelOptions = await presets.babel({}, options);
const entries = {
iframe: await presets.preview([], options),
manager: await presets.manager([], options),
};
const webpackConfig = await presets.webpack({}, { ...options, babelOptions, entries });
return presets.webpackFinal(webpackConfig, options);
}
export default async options => {
const { corePresets = [], frameworkPresets = [], ...restOptions } = options;
const presetsConfig = [
...corePresets,
require.resolve('./core-preset-babel-cache.js'),
...frameworkPresets,
...customPreset(options),
require.resolve('./core-preset-webpack-custom.js'),
];
const presets = loadPresets(presetsConfig);
return getWebpackConfig({ ...restOptions, presets }, wrapCorePresets(presets));
};
| lib/core/src/server/config.js | 1 | https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9 | [
0.9981915354728699,
0.3389705419540405,
0.004077249206602573,
0.015190916135907173,
0.46567660570144653
] |
{
"id": 1,
"code_window": [
" const entries = {\n",
" iframe: await presets.preview([], options),\n",
" manager: await presets.manager([], options),\n",
" };\n",
"\n",
" const webpackConfig = await presets.webpack({}, { ...options, babelOptions, entries });\n",
"\n",
" return presets.webpackFinal(webpackConfig, options);\n",
"}\n",
"\n",
"export default async options => {\n",
" const { corePresets = [], frameworkPresets = [], ...restOptions } = options;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return presets.webpack({}, { ...options, babelOptions, entries });\n"
],
"file_path": "lib/core/src/server/config.js",
"type": "replace",
"edit_start_line_idx": 37
} | import hbs from 'htmlbars-inline-precompile';
import { storiesOf } from '@storybook/ember';
import { action } from '@storybook/addon-actions';
storiesOf('welcome-banner', module).add('basic', () => ({
template: hbs`
{{welcome-banner
backgroundColor=backgroundColor
titleColor=titleColor
subTitleColor=subTitleColor
title=title
subtitle=subtitle
click=(action onClick)
}}
`,
context: {
backgroundColor: '#FDF4E7',
titleColor: '#DF4D37',
subTitleColor: '#B8854F',
title: 'Welcome to storybook',
subtitle: 'This environment is completely editable',
onClick: action('clicked'),
},
}));
| examples/ember-cli/stories/welcome-banner.stories.js | 0 | https://github.com/storybookjs/storybook/commit/2873911d03791ecff4c275d93d2cf726825d95d9 | [
0.00017758859030436724,
0.00017560583364684135,
0.00017322323401458561,
0.00017600567662157118,
0.0000018044371472569765
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.