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": 2,
"code_window": [
" label=\"Log Groups\"\n",
" labelWidth={6}\n",
" className=\"flex-grow-1\"\n",
" inputEl={\n",
" <MultiSelect\n",
" menuShouldPortal\n",
" allowCustomValue={allowCustomValue}\n",
" options={unionBy(availableLogGroups, selectedLogGroups, 'value')}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Log Groups\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/LogsQueryField.tsx",
"type": "add",
"edit_start_line_idx": 350
} | import { getBackendSrv } from '@grafana/runtime';
import { TeamMember, ThunkResult } from 'app/types';
import { updateNavIndex } from 'app/core/actions';
import { buildNavModel } from './navModel';
import { teamGroupsLoaded, teamLoaded, teamMembersLoaded, teamsLoaded } from './reducers';
export function loadTeams(): ThunkResult<void> {
return async (dispatch) => {
const response = await getBackendSrv().get('/api/teams/search', { perpage: 1000, page: 1 });
dispatch(teamsLoaded(response.teams));
};
}
export function loadTeam(id: number): ThunkResult<void> {
return async (dispatch) => {
const response = await getBackendSrv().get(`/api/teams/${id}`);
dispatch(teamLoaded(response));
dispatch(updateNavIndex(buildNavModel(response)));
};
}
export function loadTeamMembers(): ThunkResult<void> {
return async (dispatch, getStore) => {
const team = getStore().team.team;
const response = await getBackendSrv().get(`/api/teams/${team.id}/members`);
dispatch(teamMembersLoaded(response));
};
}
export function addTeamMember(id: number): ThunkResult<void> {
return async (dispatch, getStore) => {
const team = getStore().team.team;
await getBackendSrv().post(`/api/teams/${team.id}/members`, { userId: id });
dispatch(loadTeamMembers());
};
}
export function removeTeamMember(id: number): ThunkResult<void> {
return async (dispatch, getStore) => {
const team = getStore().team.team;
await getBackendSrv().delete(`/api/teams/${team.id}/members/${id}`);
dispatch(loadTeamMembers());
};
}
export function updateTeam(name: string, email: string): ThunkResult<void> {
return async (dispatch, getStore) => {
const team = getStore().team.team;
await getBackendSrv().put(`/api/teams/${team.id}`, { name, email });
dispatch(loadTeam(team.id));
};
}
export function loadTeamGroups(): ThunkResult<void> {
return async (dispatch, getStore) => {
const team = getStore().team.team;
const response = await getBackendSrv().get(`/api/teams/${team.id}/groups`);
dispatch(teamGroupsLoaded(response));
};
}
export function addTeamGroup(groupId: string): ThunkResult<void> {
return async (dispatch, getStore) => {
const team = getStore().team.team;
await getBackendSrv().post(`/api/teams/${team.id}/groups`, { groupId: groupId });
dispatch(loadTeamGroups());
};
}
export function removeTeamGroup(groupId: string): ThunkResult<void> {
return async (dispatch, getStore) => {
const team = getStore().team.team;
await getBackendSrv().delete(`/api/teams/${team.id}/groups/${encodeURIComponent(groupId)}`);
dispatch(loadTeamGroups());
};
}
export function deleteTeam(id: number): ThunkResult<void> {
return async (dispatch) => {
await getBackendSrv().delete(`/api/teams/${id}`);
dispatch(loadTeams());
};
}
export function updateTeamMember(member: TeamMember): ThunkResult<void> {
return async (dispatch) => {
await getBackendSrv().put(`/api/teams/${member.teamId}/members/${member.userId}`, {
permission: member.permission,
});
dispatch(loadTeamMembers());
};
}
| public/app/features/teams/state/actions.ts | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.00019951025024056435,
0.00017526086594443768,
0.00016556117043364793,
0.0001727634371491149,
0.000009034493814397138
] |
{
"id": 2,
"code_window": [
" label=\"Log Groups\"\n",
" labelWidth={6}\n",
" className=\"flex-grow-1\"\n",
" inputEl={\n",
" <MultiSelect\n",
" menuShouldPortal\n",
" allowCustomValue={allowCustomValue}\n",
" options={unionBy(availableLogGroups, selectedLogGroups, 'value')}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Log Groups\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/LogsQueryField.tsx",
"type": "add",
"edit_start_line_idx": 350
} | import { PanelData } from '@grafana/data';
import { getDashboardSrv } from 'app/features/dashboard/services/DashboardSrv';
import { getTimeSrv } from 'app/features/dashboard/services/TimeSrv';
/**
* This will setup features that are accessible through the root window location
*
* This is useful for manipulating the application from external drivers like puppetter/cypress
*
* @internal and subject to change
*/
export function initWindowRuntime() {
(window as any).grafanaRuntime = {
/** Get info for the current dashboard. This will include the migrated dashboard JSON */
getDashboardSaveModel: () => {
const d = getDashboardSrv().getCurrent();
if (!d) {
return undefined;
}
return d.getSaveModelClone();
},
/** The selected time range */
getDashboardTimeRange: () => {
const tr = getTimeSrv().timeRange();
return {
from: tr.from.valueOf(),
to: tr.to.valueOf(),
raw: tr.raw,
};
},
/** Get the query results for the last loaded data */
getPanelData: () => {
const d = getDashboardSrv().getCurrent();
if (!d) {
return undefined;
}
return d.panels.reduce((acc, panel) => {
acc[panel.id] = panel.getQueryRunner().getLastResult();
return acc;
}, {} as Record<number, PanelData | undefined>);
},
};
}
| public/app/features/runtime/init.ts | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.00017343430954497308,
0.0001716294209472835,
0.00016949929704423994,
0.000172106345416978,
0.0000016769465673860395
] |
{
"id": 3,
"code_window": [
" <EditorFieldGroup>\n",
" <EditorField label=\"Namespace\" width={26}>\n",
" <Select\n",
" value={query.namespace}\n",
" allowCustomValue\n",
" options={namespaces}\n",
" onChange={({ value: namespace }) => {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Namespace\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/MetricStatEditor/MetricStatEditor.tsx",
"type": "add",
"edit_start_line_idx": 40
} | import React from 'react';
import { EditorField, EditorFieldGroup, EditorRow, EditorRows } from '@grafana/experimental';
import { Select, Switch } from '@grafana/ui';
import { Dimensions } from '..';
import { CloudWatchDatasource } from '../../datasource';
import { useDimensionKeys, useMetrics, useNamespaces } from '../../hooks';
import { CloudWatchMetricsQuery } from '../../types';
import { appendTemplateVariables, toOption } from '../../utils/utils';
export type Props = {
query: CloudWatchMetricsQuery;
datasource: CloudWatchDatasource;
disableExpressions?: boolean;
onChange: (value: CloudWatchMetricsQuery) => void;
onRunQuery: () => void;
};
export function MetricStatEditor({
query,
datasource,
disableExpressions = false,
onChange,
onRunQuery,
}: React.PropsWithChildren<Props>) {
const { region, namespace, metricName, dimensions } = query;
const namespaces = useNamespaces(datasource);
const metrics = useMetrics(datasource, region, namespace);
const dimensionKeys = useDimensionKeys(datasource, region, namespace, metricName, dimensions ?? {});
const onQueryChange = (query: CloudWatchMetricsQuery) => {
onChange(query);
onRunQuery();
};
return (
<EditorRows>
<EditorRow>
<EditorFieldGroup>
<EditorField label="Namespace" width={26}>
<Select
value={query.namespace}
allowCustomValue
options={namespaces}
onChange={({ value: namespace }) => {
if (namespace) {
onQueryChange({ ...query, namespace });
}
}}
/>
</EditorField>
<EditorField label="Metric name" width={16}>
<Select
value={query.metricName}
allowCustomValue
options={metrics}
onChange={({ value: metricName }) => {
if (metricName) {
onQueryChange({ ...query, metricName });
}
}}
/>
</EditorField>
<EditorField label="Statistic" width={16}>
<Select
inputId={`${query.refId}-metric-stat-editor-select-statistic`}
allowCustomValue
value={toOption(query.statistic ?? datasource.standardStatistics[0])}
options={appendTemplateVariables(
datasource,
datasource.standardStatistics.filter((s) => s !== query.statistic).map(toOption)
)}
onChange={({ value: statistic }) => {
if (
!statistic ||
(!datasource.standardStatistics.includes(statistic) &&
!/^p\d{2}(?:\.\d{1,2})?$/.test(statistic) &&
!statistic.startsWith('$'))
) {
return;
}
onQueryChange({ ...query, statistic });
}}
/>
</EditorField>
</EditorFieldGroup>
</EditorRow>
<EditorRow>
<EditorField label="Dimensions">
<Dimensions
query={query}
onChange={(dimensions) => onQueryChange({ ...query, dimensions })}
dimensionKeys={dimensionKeys}
disableExpressions={disableExpressions}
datasource={datasource}
/>
</EditorField>
</EditorRow>
{!disableExpressions && (
<EditorRow>
<EditorField
label="Match exact"
optional={true}
tooltip="Only show metrics that exactly match all defined dimension names."
>
<Switch
id={`${query.refId}-cloudwatch-match-exact`}
value={!!query.matchExact}
onChange={(e) => {
onQueryChange({
...query,
matchExact: e.currentTarget.checked,
});
}}
/>
</EditorField>
</EditorRow>
)}
</EditorRows>
);
}
| public/app/plugins/datasource/cloudwatch/components/MetricStatEditor/MetricStatEditor.tsx | 1 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.9906113743782043,
0.14784348011016846,
0.00016763817984610796,
0.00421554408967495,
0.3379237949848175
] |
{
"id": 3,
"code_window": [
" <EditorFieldGroup>\n",
" <EditorField label=\"Namespace\" width={26}>\n",
" <Select\n",
" value={query.namespace}\n",
" allowCustomValue\n",
" options={namespaces}\n",
" onChange={({ value: namespace }) => {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Namespace\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/MetricStatEditor/MetricStatEditor.tsx",
"type": "add",
"edit_start_line_idx": 40
} | #!/bin/bash
set -eo pipefail
cd "$(dirname "$0")"/..
mixtool generate all mixin.libsonnet
| grafana-mixin/scripts/build.sh | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.00017057925288099796,
0.00017057925288099796,
0.00017057925288099796,
0.00017057925288099796,
0
] |
{
"id": 3,
"code_window": [
" <EditorFieldGroup>\n",
" <EditorField label=\"Namespace\" width={26}>\n",
" <Select\n",
" value={query.namespace}\n",
" allowCustomValue\n",
" options={namespaces}\n",
" onChange={({ value: namespace }) => {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Namespace\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/MetricStatEditor/MetricStatEditor.tsx",
"type": "add",
"edit_start_line_idx": 40
} | #### Alias patterns
- replaced with measurement name
- $measurement = replaced with measurement name
- $1 - $9 = replaced with part of measurement name (if you separate your measurement name with dots)
- $col = replaced with column name
- $tag_exampletag = replaced with the value of the <i>exampletag</i> tag
- You can also use [[tag_exampletag]] pattern replacement syntax
#### Stacking and fill
- When stacking is enabled it is important that points align
- If there are missing points for one series it can cause gaps or missing bars
- You must use fill(0), and select a group by time low limit
- Use the group by time option below your queries and specify for example 10s if your metrics are written every 10 seconds
- This will insert zeros for series that are missing measurements and will make stacking work properly
#### Group by time
- Group by time is important, otherwise the query could return many thousands of datapoints that will slow down Grafana
- Leave the group by time field empty for each query and it will be calculated based on time range and pixel width of the graph
- If you use fill(0) or fill(null) set a low limit for the auto group by time interval
- The low limit can only be set in the group by time option below your queries
- Example: 60s if you write metrics to InfluxDB every 60 seconds
#### Documentation links:
[Grafana's InfluxDB Documentation](http://docs.grafana.org/features/datasources/influxdb)
[Official InfluxDB Documentation](https://docs.influxdata.com/influxdb)
| public/app/plugins/datasource/influxdb/query_help.md | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.00018311374878976494,
0.00017678947187960148,
0.00017375159950461239,
0.00017514625506009907,
0.0000037641023027390474
] |
{
"id": 3,
"code_window": [
" <EditorFieldGroup>\n",
" <EditorField label=\"Namespace\" width={26}>\n",
" <Select\n",
" value={query.namespace}\n",
" allowCustomValue\n",
" options={namespaces}\n",
" onChange={({ value: namespace }) => {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Namespace\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/MetricStatEditor/MetricStatEditor.tsx",
"type": "add",
"edit_start_line_idx": 40
} | package manager
import (
"context"
"testing"
"time"
"github.com/grafana/grafana/pkg/infra/usagestats"
"github.com/grafana/grafana/pkg/services/encryption/ossencryption"
"github.com/grafana/grafana/pkg/services/kmsproviders/osskmsproviders"
"github.com/grafana/grafana/pkg/services/secrets"
"github.com/grafana/grafana/pkg/services/secrets/database"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/setting"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gopkg.in/ini.v1"
)
func TestSecretsService_EnvelopeEncryption(t *testing.T) {
store := database.ProvideSecretsStore(sqlstore.InitTestDB(t))
svc := SetupTestService(t, store)
ctx := context.Background()
t.Run("encrypting with no entity_id should create DEK", func(t *testing.T) {
plaintext := []byte("very secret string")
encrypted, err := svc.Encrypt(context.Background(), plaintext, secrets.WithoutScope())
require.NoError(t, err)
decrypted, err := svc.Decrypt(context.Background(), encrypted)
require.NoError(t, err)
assert.Equal(t, plaintext, decrypted)
keys, err := store.GetAllDataKeys(ctx)
require.NoError(t, err)
assert.Equal(t, len(keys), 1)
})
t.Run("encrypting another secret with no entity_id should use the same DEK", func(t *testing.T) {
plaintext := []byte("another very secret string")
encrypted, err := svc.Encrypt(context.Background(), plaintext, secrets.WithoutScope())
require.NoError(t, err)
decrypted, err := svc.Decrypt(context.Background(), encrypted)
require.NoError(t, err)
assert.Equal(t, plaintext, decrypted)
keys, err := store.GetAllDataKeys(ctx)
require.NoError(t, err)
assert.Equal(t, len(keys), 1)
})
t.Run("encrypting with entity_id provided should create a new DEK", func(t *testing.T) {
plaintext := []byte("some test data")
encrypted, err := svc.Encrypt(context.Background(), plaintext, secrets.WithScope("user:100"))
require.NoError(t, err)
decrypted, err := svc.Decrypt(context.Background(), encrypted)
require.NoError(t, err)
assert.Equal(t, plaintext, decrypted)
keys, err := store.GetAllDataKeys(ctx)
require.NoError(t, err)
assert.Equal(t, len(keys), 2)
})
t.Run("decrypting empty payload should return error", func(t *testing.T) {
_, err := svc.Decrypt(context.Background(), []byte(""))
require.Error(t, err)
assert.Equal(t, "unable to decrypt empty payload", err.Error())
})
t.Run("decrypting legacy secret encrypted with secret key from settings", func(t *testing.T) {
expected := "grafana"
encrypted := []byte{122, 56, 53, 113, 101, 117, 73, 89, 20, 254, 36, 112, 112, 16, 128, 232, 227, 52, 166, 108, 192, 5, 28, 125, 126, 42, 197, 190, 251, 36, 94}
decrypted, err := svc.Decrypt(context.Background(), encrypted)
require.NoError(t, err)
assert.Equal(t, expected, string(decrypted))
})
t.Run("usage stats should be registered", func(t *testing.T) {
reports, err := svc.usageStats.GetUsageReport(context.Background())
require.NoError(t, err)
assert.Equal(t, 1, reports.Metrics["stats.encryption.envelope_encryption_enabled.count"])
})
}
func TestSecretsService_DataKeys(t *testing.T) {
store := database.ProvideSecretsStore(sqlstore.InitTestDB(t))
ctx := context.Background()
dataKey := secrets.DataKey{
Active: true,
Name: "test1",
Provider: "test",
EncryptedData: []byte{0x62, 0xAF, 0xA1, 0x1A},
}
t.Run("querying for a DEK that does not exist", func(t *testing.T) {
res, err := store.GetDataKey(ctx, dataKey.Name)
assert.ErrorIs(t, secrets.ErrDataKeyNotFound, err)
assert.Nil(t, res)
})
t.Run("creating an active DEK", func(t *testing.T) {
err := store.CreateDataKey(ctx, dataKey)
require.NoError(t, err)
res, err := store.GetDataKey(ctx, dataKey.Name)
require.NoError(t, err)
assert.Equal(t, dataKey.EncryptedData, res.EncryptedData)
assert.Equal(t, dataKey.Provider, res.Provider)
assert.Equal(t, dataKey.Name, res.Name)
assert.True(t, dataKey.Active)
})
t.Run("creating an inactive DEK", func(t *testing.T) {
k := secrets.DataKey{
Active: false,
Name: "test2",
Provider: "test",
EncryptedData: []byte{0x62, 0xAF, 0xA1, 0x1A},
}
err := store.CreateDataKey(ctx, k)
require.Error(t, err)
res, err := store.GetDataKey(ctx, k.Name)
assert.Equal(t, secrets.ErrDataKeyNotFound, err)
assert.Nil(t, res)
})
t.Run("deleting DEK when no name provided must fail", func(t *testing.T) {
beforeDelete, err := store.GetAllDataKeys(ctx)
require.NoError(t, err)
err = store.DeleteDataKey(ctx, "")
require.Error(t, err)
afterDelete, err := store.GetAllDataKeys(ctx)
require.NoError(t, err)
assert.Equal(t, beforeDelete, afterDelete)
})
t.Run("deleting a DEK", func(t *testing.T) {
err := store.DeleteDataKey(ctx, dataKey.Name)
require.NoError(t, err)
res, err := store.GetDataKey(ctx, dataKey.Name)
assert.Equal(t, secrets.ErrDataKeyNotFound, err)
assert.Nil(t, res)
})
}
func TestSecretsService_UseCurrentProvider(t *testing.T) {
t.Run("When encryption_provider is not specified explicitly, should use 'secretKey' as a current provider", func(t *testing.T) {
svc := SetupTestService(t, database.ProvideSecretsStore(sqlstore.InitTestDB(t)))
assert.Equal(t, "secretKey", svc.currentProvider)
})
t.Run("Should use encrypt/decrypt methods of the current encryption provider", func(t *testing.T) {
rawCfg := `
[security]
secret_key = sdDkslslld
encryption_provider = fakeProvider.v1
available_encryption_providers = fakeProvider.v1
[security.encryption.fakeProvider.v1]
`
raw, err := ini.Load([]byte(rawCfg))
require.NoError(t, err)
providerID := "fakeProvider.v1"
settings := &setting.OSSImpl{
Cfg: &setting.Cfg{
Raw: raw,
FeatureToggles: map[string]bool{secrets.EnvelopeEncryptionFeatureToggle: true},
},
}
encr := ossencryption.ProvideService()
kms := newFakeKMS(osskmsproviders.ProvideService(encr, settings))
secretStore := database.ProvideSecretsStore(sqlstore.InitTestDB(t))
svcEncrypt, err := ProvideSecretsService(
secretStore,
&kms,
encr,
settings,
&usagestats.UsageStatsMock{T: t},
)
require.NoError(t, err)
assert.Equal(t, providerID, svcEncrypt.currentProvider)
assert.Equal(t, 2, len(svcEncrypt.GetProviders()))
encrypted, _ := svcEncrypt.Encrypt(context.Background(), []byte{}, secrets.WithoutScope())
assert.True(t, kms.fake.encryptCalled)
// secret service tries to find a DEK in a cache first before calling provider's decrypt
// to bypass the cache, we set up one more secrets service to test decrypting
svcDecrypt, err := ProvideSecretsService(
secretStore,
&kms,
encr,
settings,
&usagestats.UsageStatsMock{T: t},
)
require.NoError(t, err)
_, _ = svcDecrypt.Decrypt(context.Background(), encrypted)
assert.True(t, kms.fake.decryptCalled, "fake provider's decrypt should be called")
})
}
type fakeProvider struct {
encryptCalled bool
decryptCalled bool
}
func (p *fakeProvider) Encrypt(_ context.Context, _ []byte) ([]byte, error) {
p.encryptCalled = true
return []byte{}, nil
}
func (p *fakeProvider) Decrypt(_ context.Context, _ []byte) ([]byte, error) {
p.decryptCalled = true
return []byte{}, nil
}
type fakeKMS struct {
kms osskmsproviders.Service
fake *fakeProvider
}
func newFakeKMS(kms osskmsproviders.Service) fakeKMS {
return fakeKMS{
kms: kms,
fake: &fakeProvider{},
}
}
func (f *fakeKMS) Provide() (map[string]secrets.Provider, error) {
providers, err := f.kms.Provide()
if err != nil {
return providers, err
}
providers["fakeProvider.v1"] = f.fake
return providers, nil
}
func TestSecretsService_Run(t *testing.T) {
ctx := context.Background()
sql := sqlstore.InitTestDB(t)
store := database.ProvideSecretsStore(sql)
svc := SetupTestService(t, store)
t.Run("should stop with no error once the context's finished", func(t *testing.T) {
ctx, cancel := context.WithTimeout(ctx, time.Millisecond)
defer cancel()
err := svc.Run(ctx)
assert.NoError(t, err)
})
t.Run("should trigger cache clean up", func(t *testing.T) {
// Encrypt to ensure there's a data encryption key generated
_, err := svc.Encrypt(ctx, []byte("grafana"), secrets.WithoutScope())
require.NoError(t, err)
// Data encryption key cache should contain one element
require.Len(t, svc.dataKeyCache, 1)
// Execute background process after key's TTL, to force
// clean up process, during a hundred milliseconds with
// gc ticker configured on every nanosecond, to ensure
// the ticker is triggered.
gcInterval = time.Nanosecond
t.Cleanup(func() { now = time.Now })
now = func() time.Time { return time.Now().Add(dekTTL) }
ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
defer cancel()
err = svc.Run(ctx)
require.NoError(t, err)
// Then, once the ticker has been triggered,
// the cleanup process should have happened,
// therefore the cache should be empty.
require.Len(t, svc.dataKeyCache, 0)
})
t.Run("should update data key expiry after every use", func(t *testing.T) {
// Encrypt to generate data encryption key
withoutScope := secrets.WithoutScope()
_, err := svc.Encrypt(ctx, []byte("grafana"), withoutScope)
require.NoError(t, err)
// New call to Encrypt one minute later should update cache entry's expiry
t.Cleanup(func() { now = time.Now })
now = func() time.Time { return time.Now().Add(time.Minute) }
_, err = svc.Encrypt(ctx, []byte("grafana"), withoutScope)
require.NoError(t, err)
dataKeyID := svc.keyName(withoutScope())
assert.True(t, svc.dataKeyCache[dataKeyID].expiry.After(time.Now().Add(dekTTL)))
})
}
| pkg/services/secrets/manager/manager_test.go | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.0001781238242983818,
0.0001733738899929449,
0.0001615812216186896,
0.00017402951198164374,
0.0000033510739285702584
] |
{
"id": 4,
"code_window": [
" />\n",
" </EditorField>\n",
" <EditorField label=\"Metric name\" width={16}>\n",
" <Select\n",
" value={query.metricName}\n",
" allowCustomValue\n",
" options={metrics}\n",
" onChange={({ value: metricName }) => {\n",
" if (metricName) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Metric name\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/MetricStatEditor/MetricStatEditor.tsx",
"type": "add",
"edit_start_line_idx": 52
} | import React, { ChangeEvent, PureComponent } from 'react';
import { QueryEditorProps } from '@grafana/data';
import { EditorField, EditorRow, Space } from '@grafana/experimental';
import { Input } from '@grafana/ui';
import { CloudWatchDatasource } from '../datasource';
import { isMetricsQuery } from '../guards';
import {
CloudWatchJsonData,
CloudWatchMetricsQuery,
CloudWatchQuery,
MetricEditorMode,
MetricQueryType,
} from '../types';
import { Alias, MathExpressionQueryField, MetricStatEditor, SQLBuilderEditor, SQLCodeEditor } from './';
import QueryHeader from './QueryHeader';
export type Props = QueryEditorProps<CloudWatchDatasource, CloudWatchQuery, CloudWatchJsonData>;
interface State {
sqlCodeEditorIsDirty: boolean;
}
export const normalizeQuery = ({
namespace,
metricName,
expression,
dimensions,
region,
id,
alias,
statistic,
period,
sqlExpression,
metricQueryType,
metricEditorMode,
...rest
}: CloudWatchMetricsQuery): CloudWatchMetricsQuery => {
const normalizedQuery = {
queryMode: 'Metrics' as const,
namespace: namespace ?? '',
metricName: metricName ?? '',
expression: expression ?? '',
dimensions: dimensions ?? {},
region: region ?? 'default',
id: id ?? '',
alias: alias ?? '',
statistic: statistic ?? 'Average',
period: period ?? '',
metricQueryType: metricQueryType ?? MetricQueryType.Search,
metricEditorMode: metricEditorMode ?? MetricEditorMode.Builder,
sqlExpression: sqlExpression ?? '',
...rest,
};
return !rest.hasOwnProperty('matchExact') ? { ...normalizedQuery, matchExact: true } : normalizedQuery;
};
export class MetricsQueryEditor extends PureComponent<Props, State> {
state = {
sqlCodeEditorIsDirty: false,
};
componentDidMount = () => {
const metricsQuery = this.props.query as CloudWatchMetricsQuery;
const query = normalizeQuery(metricsQuery);
this.props.onChange(query);
};
onChange = (query: CloudWatchQuery) => {
const { onChange, onRunQuery } = this.props;
onChange(query);
onRunQuery();
};
render() {
const { onRunQuery, datasource } = this.props;
const metricsQuery = this.props.query as CloudWatchMetricsQuery;
const query = normalizeQuery(metricsQuery);
return (
<>
<QueryHeader
query={query}
onRunQuery={onRunQuery}
datasource={datasource}
onChange={(newQuery) => {
if (isMetricsQuery(newQuery) && newQuery.metricEditorMode !== query.metricEditorMode) {
this.setState({ sqlCodeEditorIsDirty: false });
}
this.onChange(newQuery);
}}
sqlCodeEditorIsDirty={this.state.sqlCodeEditorIsDirty}
/>
<Space v={0.5} />
{query.metricQueryType === MetricQueryType.Search && (
<>
{query.metricEditorMode === MetricEditorMode.Builder && (
<MetricStatEditor {...{ ...this.props, query }}></MetricStatEditor>
)}
{query.metricEditorMode === MetricEditorMode.Code && (
<MathExpressionQueryField
onRunQuery={onRunQuery}
expression={query.expression ?? ''}
onChange={(expression) => this.props.onChange({ ...query, expression })}
></MathExpressionQueryField>
)}
</>
)}
{query.metricQueryType === MetricQueryType.Query && (
<>
{query.metricEditorMode === MetricEditorMode.Code && (
<SQLCodeEditor
region={query.region}
sql={query.sqlExpression ?? ''}
onChange={(sqlExpression) => {
if (!this.state.sqlCodeEditorIsDirty) {
this.setState({ sqlCodeEditorIsDirty: true });
}
this.props.onChange({ ...metricsQuery, sqlExpression });
}}
onRunQuery={onRunQuery}
datasource={datasource}
/>
)}
{query.metricEditorMode === MetricEditorMode.Builder && (
<>
<SQLBuilderEditor
query={query}
onChange={this.props.onChange}
onRunQuery={onRunQuery}
datasource={datasource}
></SQLBuilderEditor>
</>
)}
</>
)}
<Space v={0.5} />
<EditorRow>
<EditorField
label="ID"
width={26}
optional
tooltip="ID can be used to reference other queries in math expressions. The ID can include numbers, letters, and underscore, and must start with a lowercase letter."
>
<Input
onBlur={onRunQuery}
onChange={(event: ChangeEvent<HTMLInputElement>) =>
this.onChange({ ...metricsQuery, id: event.target.value })
}
type="text"
invalid={!!query.id && !/^$|^[a-z][a-zA-Z0-9_]*$/.test(query.id)}
value={query.id}
/>
</EditorField>
<EditorField label="Period" width={26} tooltip="Minimum interval between points in seconds.">
<Input
value={query.period || ''}
placeholder="auto"
onBlur={onRunQuery}
onChange={(event: ChangeEvent<HTMLInputElement>) =>
this.onChange({ ...metricsQuery, period: event.target.value })
}
/>
</EditorField>
<EditorField
label="Alias"
width={26}
optional
tooltip="Change time series legend name using this field. See documentation for replacement variable formats."
>
<Alias
value={metricsQuery.alias ?? ''}
onChange={(value: string) => this.onChange({ ...metricsQuery, alias: value })}
/>
</EditorField>
</EditorRow>
</>
);
}
}
| public/app/plugins/datasource/cloudwatch/components/MetricsQueryEditor.tsx | 1 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.9731582999229431,
0.21677835285663605,
0.00016968509589787573,
0.0037509349640458822,
0.38658615946769714
] |
{
"id": 4,
"code_window": [
" />\n",
" </EditorField>\n",
" <EditorField label=\"Metric name\" width={16}>\n",
" <Select\n",
" value={query.metricName}\n",
" allowCustomValue\n",
" options={metrics}\n",
" onChange={({ value: metricName }) => {\n",
" if (metricName) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Metric name\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/MetricStatEditor/MetricStatEditor.tsx",
"type": "add",
"edit_start_line_idx": 52
} | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Render should render component 1`] = `
<div>
<div
className="page-action-bar"
>
<h3
className="page-sub-heading"
>
External group sync
</h3>
<Tooltip
content="Sync LDAP or OAuth groups with your Grafana teams."
placement="auto"
>
<Icon
className="icon--has-hover page-sub-heading-icon"
name="question-circle"
/>
</Tooltip>
<div
className="page-action-bar__spacer"
/>
</div>
<SlideDown
in={false}
>
<div
className="cta-form"
>
<CloseButton
onClick={[Function]}
/>
<h5>
Add External Group
</h5>
<form
className="gf-form-inline"
onSubmit={[Function]}
>
<div
className="gf-form"
>
<Input
className="gf-form-input width-30"
onChange={[Function]}
placeholder="cn=ops,ou=groups,dc=grafana,dc=org"
type="text"
value=""
/>
</div>
<div
className="gf-form"
>
<Button
disabled={true}
type="submit"
>
Add group
</Button>
</div>
</form>
</div>
</SlideDown>
<EmptyListCTA
buttonIcon="users-alt"
buttonTitle="Add Group"
onClick={[Function]}
proTip="Sync LDAP or OAuth groups with your Grafana teams."
proTipLink="http://docs.grafana.org/auth/enhanced_ldap/"
proTipLinkTitle="Learn more"
proTipTarget="_blank"
title="There are no external groups to sync with"
/>
</div>
`;
exports[`Render should render groups table 1`] = `
<div>
<div
className="page-action-bar"
>
<h3
className="page-sub-heading"
>
External group sync
</h3>
<Tooltip
content="Sync LDAP or OAuth groups with your Grafana teams."
placement="auto"
>
<Icon
className="icon--has-hover page-sub-heading-icon"
name="question-circle"
/>
</Tooltip>
<div
className="page-action-bar__spacer"
/>
<Button
className="pull-right"
onClick={[Function]}
>
<Icon
name="plus"
/>
Add group
</Button>
</div>
<SlideDown
in={false}
>
<div
className="cta-form"
>
<CloseButton
onClick={[Function]}
/>
<h5>
Add External Group
</h5>
<form
className="gf-form-inline"
onSubmit={[Function]}
>
<div
className="gf-form"
>
<Input
className="gf-form-input width-30"
onChange={[Function]}
placeholder="cn=ops,ou=groups,dc=grafana,dc=org"
type="text"
value=""
/>
</div>
<div
className="gf-form"
>
<Button
disabled={true}
type="submit"
>
Add group
</Button>
</div>
</form>
</div>
</SlideDown>
<div
className="admin-list-table"
>
<table
className="filter-table filter-table--hover form-inline"
>
<thead>
<tr>
<th>
External Group ID
</th>
<th
style={
Object {
"width": "1%",
}
}
/>
</tr>
</thead>
<tbody>
<tr
key="group-1"
>
<td>
group-1
</td>
<td
style={
Object {
"width": "1%",
}
}
>
<Button
onClick={[Function]}
size="sm"
variant="destructive"
>
<Icon
name="times"
/>
</Button>
</td>
</tr>
<tr
key="group-2"
>
<td>
group-2
</td>
<td
style={
Object {
"width": "1%",
}
}
>
<Button
onClick={[Function]}
size="sm"
variant="destructive"
>
<Icon
name="times"
/>
</Button>
</td>
</tr>
<tr
key="group-3"
>
<td>
group-3
</td>
<td
style={
Object {
"width": "1%",
}
}
>
<Button
onClick={[Function]}
size="sm"
variant="destructive"
>
<Icon
name="times"
/>
</Button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
`;
| public/app/features/teams/__snapshots__/TeamGroupSync.test.tsx.snap | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.0012110135285183787,
0.00021316178026609123,
0.0001614135253475979,
0.00016863763448782265,
0.00020417732594069093
] |
{
"id": 4,
"code_window": [
" />\n",
" </EditorField>\n",
" <EditorField label=\"Metric name\" width={16}>\n",
" <Select\n",
" value={query.metricName}\n",
" allowCustomValue\n",
" options={metrics}\n",
" onChange={({ value: metricName }) => {\n",
" if (metricName) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Metric name\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/MetricStatEditor/MetricStatEditor.tsx",
"type": "add",
"edit_start_line_idx": 52
} | export { Icon } from './Icon/Icon';
export { IconButton, IconButtonVariant } from './IconButton/IconButton';
export { ConfirmButton } from './ConfirmButton/ConfirmButton';
export { DeleteButton } from './ConfirmButton/DeleteButton';
export { Tooltip, PopoverContent } from './Tooltip/Tooltip';
export { PopoverController } from './Tooltip/PopoverController';
export { Popover } from './Tooltip/Popover';
export { Portal } from './Portal/Portal';
export { CustomScrollbar, ScrollbarPosition } from './CustomScrollbar/CustomScrollbar';
export { TabbedContainer, TabConfig } from './TabbedContainer/TabbedContainer';
export { ClipboardButton } from './ClipboardButton/ClipboardButton';
export { Cascader, CascaderOption } from './Cascader/Cascader';
export { ButtonCascader } from './ButtonCascader/ButtonCascader';
export { LoadingPlaceholder, LoadingPlaceholderProps } from './LoadingPlaceholder/LoadingPlaceholder';
export { ColorPicker, SeriesColorPicker } from './ColorPicker/ColorPicker';
export { ColorValueEditor, ColorValueEditorProps } from './OptionsUI/color';
export { SeriesColorPickerPopover, SeriesColorPickerPopoverWithTheme } from './ColorPicker/SeriesColorPickerPopover';
export { EmptySearchResult } from './EmptySearchResult/EmptySearchResult';
export { UnitPicker } from './UnitPicker/UnitPicker';
export { StatsPicker } from './StatsPicker/StatsPicker';
export { RefreshPicker, defaultIntervals } from './RefreshPicker/RefreshPicker';
export { TimeRangePicker, TimeRangePickerProps } from './DateTimePickers/TimeRangePicker';
export { TimeOfDayPicker } from './DateTimePickers/TimeOfDayPicker';
export { TimeZonePicker } from './DateTimePickers/TimeZonePicker';
export { WeekStartPicker } from './DateTimePickers/WeekStartPicker';
export { DatePicker, DatePickerProps } from './DateTimePickers/DatePicker/DatePicker';
export {
DatePickerWithInput,
DatePickerWithInputProps,
} from './DateTimePickers/DatePickerWithInput/DatePickerWithInput';
export { DateTimePicker } from './DateTimePickers/DateTimePicker/DateTimePicker';
export { List } from './List/List';
export { TagsInput } from './TagsInput/TagsInput';
export { Pagination } from './Pagination/Pagination';
export { Tag, OnTagClick } from './Tags/Tag';
export { TagList } from './Tags/TagList';
export { FilterPill } from './FilterPill/FilterPill';
export { ConfirmModal, ConfirmModalProps } from './ConfirmModal/ConfirmModal';
export { QueryField } from './QueryField/QueryField';
// Code editor
export { CodeEditor } from './Monaco/CodeEditor';
export { ReactMonacoEditorLazy as ReactMonacoEditor } from './Monaco/ReactMonacoEditorLazy';
export {
Monaco,
monacoTypes,
MonacoEditor,
MonacoOptions as CodeEditorMonacoOptions,
CodeEditorSuggestionItem,
CodeEditorSuggestionItemKind,
} from './Monaco/types';
export { variableSuggestionToCodeEditorSuggestion } from './Monaco/utils';
// TODO: namespace
export { Modal } from './Modal/Modal';
export { ModalHeader } from './Modal/ModalHeader';
export { ModalTabsHeader } from './Modal/ModalTabsHeader';
export { ModalTabContent } from './Modal/ModalTabContent';
export { ModalsProvider, ModalRoot, ModalsController } from './Modal/ModalsContext';
export { PageToolbar } from './PageLayout/PageToolbar';
// Renderless
export { SetInterval } from './SetInterval/SetInterval';
export { Table } from './Table/Table';
export { TableCellDisplayMode, TableSortByFieldState } from './Table/types';
export { TableInputCSV } from './TableInputCSV/TableInputCSV';
export { TabsBar } from './Tabs/TabsBar';
export { Tab } from './Tabs/Tab';
export { TabContent } from './Tabs/TabContent';
export { Counter } from './Tabs/Counter';
// Visualizations
export {
BigValue,
BigValueColorMode,
BigValueGraphMode,
BigValueJustifyMode,
BigValueTextMode,
} from './BigValue/BigValue';
export { Gauge } from './Gauge/Gauge';
export { Graph } from './Graph/Graph';
export { GraphWithLegend } from './Graph/GraphWithLegend';
export { GraphContextMenu, GraphContextMenuHeader } from './Graph/GraphContextMenu';
export { BarGauge, BarGaugeDisplayMode } from './BarGauge/BarGauge';
export {
VizTooltip,
VizTooltipContainer,
SeriesTable,
SeriesTableProps,
SeriesTableRow,
SeriesTableRowProps,
} from './VizTooltip';
export { VizRepeater, VizRepeaterRenderValueProps } from './VizRepeater/VizRepeater';
export { graphTimeFormat, graphTickFormatter } from './Graph/utils';
export {
PanelChrome,
PanelChromeProps,
PanelPadding,
PanelChromeType,
PanelChromeLoadingIndicator,
PanelChromeLoadingIndicatorProps,
PanelChromeErrorIndicator,
PanelChromeErrorIndicatorProps,
PanelContextProvider,
PanelContext,
PanelContextRoot,
usePanelContext,
} from './PanelChrome';
export { VizLayout, VizLayoutComponentType, VizLayoutLegendProps, VizLayoutProps } from './VizLayout/VizLayout';
export { VizLegendItem, SeriesVisibilityChangeBehavior } from './VizLegend/types';
export { VizLegend } from './VizLegend/VizLegend';
export { VizLegendListItem } from './VizLegend/VizLegendListItem';
export { Alert, AlertVariant } from './Alert/Alert';
export { GraphSeriesToggler, GraphSeriesTogglerAPI } from './Graph/GraphSeriesToggler';
export { Collapse, ControlledCollapse } from './Collapse/Collapse';
export { CollapsableSection } from './Collapse/CollapsableSection';
export { LogLabels } from './Logs/LogLabels';
export { LogMessageAnsi } from './Logs/LogMessageAnsi';
export { LogRows } from './Logs/LogRows';
export { getLogRowStyles } from './Logs/getLogRowStyles';
export { DataLinkButton } from './DataLinks/DataLinkButton';
export { FieldLinkList } from './DataLinks/FieldLinkList';
// Panel editors
export { FullWidthButtonContainer } from './Button/FullWidthButtonContainer';
export { ClickOutsideWrapper } from './ClickOutsideWrapper/ClickOutsideWrapper';
export * from './SingleStatShared/index';
export { CallToActionCard } from './CallToActionCard/CallToActionCard';
export { ContextMenu, ContextMenuProps } from './ContextMenu/ContextMenu';
export { Menu, MenuProps } from './Menu/Menu';
export { MenuGroup, MenuItemsGroup, MenuGroupProps } from './Menu/MenuGroup';
export { MenuItem, MenuItemProps } from './Menu/MenuItem';
export { WithContextMenu } from './ContextMenu/WithContextMenu';
export { DataLinksInlineEditor } from './DataLinks/DataLinksInlineEditor/DataLinksInlineEditor';
export { DataLinkInput } from './DataLinks/DataLinkInput';
export { DataLinksContextMenu } from './DataLinks/DataLinksContextMenu';
export { SeriesIcon } from './VizLegend/SeriesIcon';
export { InfoBox } from './InfoBox/InfoBox';
export { FeatureBadge, FeatureInfoBox } from './InfoBox/FeatureInfoBox';
export { JSONFormatter } from './JSONFormatter/JSONFormatter';
export { JsonExplorer } from './JSONFormatter/json_explorer/json_explorer';
export {
ErrorBoundary,
ErrorBoundaryAlert,
ErrorBoundaryAlertProps,
withErrorBoundary,
} from './ErrorBoundary/ErrorBoundary';
export { ErrorWithStack } from './ErrorBoundary/ErrorWithStack';
export { DataSourceHttpSettings } from './DataSourceSettings/DataSourceHttpSettings';
export { AlertingSettings } from './DataSourceSettings/AlertingSettings';
export { TLSAuthSettings } from './DataSourceSettings/TLSAuthSettings';
export { CertificationKey } from './DataSourceSettings/CertificationKey';
export { Spinner } from './Spinner/Spinner';
export { FadeTransition } from './transitions/FadeTransition';
export { SlideOutTransition } from './transitions/SlideOutTransition';
export { Segment, SegmentAsync, SegmentInput, SegmentSelect, SegmentSection } from './Segment/';
export { Drawer } from './Drawer/Drawer';
export { Slider } from './Slider/Slider';
export { RangeSlider } from './Slider/RangeSlider';
// TODO: namespace!!
export { StringValueEditor } from './OptionsUI/string';
export { StringArrayEditor } from './OptionsUI/strings';
export { NumberValueEditor } from './OptionsUI/number';
export { SliderValueEditor } from './OptionsUI/slider';
export { SelectValueEditor } from './OptionsUI/select';
export { MultiSelectValueEditor } from './OptionsUI/multiSelect';
// Next-gen forms
export { Form } from './Forms/Form';
export { sharedInputStyle } from './Forms/commonStyles';
export { InputControl } from './InputControl';
export { Button, LinkButton, ButtonVariant, ToolbarButton, ButtonGroup, ToolbarButtonRow, ButtonProps } from './Button';
export { ValuePicker } from './ValuePicker/ValuePicker';
export { fieldMatchersUI } from './MatchersUI/fieldMatchersUI';
export { getFormStyles } from './Forms/getFormStyles';
export { Link } from './Link/Link';
export { Label } from './Forms/Label';
export { Field } from './Forms/Field';
export { Legend } from './Forms/Legend';
export { FieldSet } from './Forms/FieldSet';
export { FieldValidationMessage } from './Forms/FieldValidationMessage';
export { InlineField } from './Forms/InlineField';
export { InlineSegmentGroup } from './Forms/InlineSegmentGroup';
export { InlineLabel } from './Forms/InlineLabel';
export { InlineFieldRow } from './Forms/InlineFieldRow';
export { FieldArray } from './Forms/FieldArray';
// Select
export { default as resetSelectStyles } from './Select/resetSelectStyles';
export { selectOptionInTest } from './Select/test-utils';
export * from './Select/Select';
export { DropdownIndicator } from './Select/DropdownIndicator';
export { getSelectStyles } from './Select/getSelectStyles';
export * from './Select/types';
export { HorizontalGroup, VerticalGroup, Container } from './Layout/Layout';
export { Badge, BadgeColor, BadgeProps } from './Badge/Badge';
export { RadioButtonGroup } from './Forms/RadioButtonGroup/RadioButtonGroup';
export { Input, getInputStyles } from './Input/Input';
export { FilterInput } from './FilterInput/FilterInput';
export { FormInputSize } from './Forms/types';
export { Switch, InlineSwitch } from './Switch/Switch';
export { Checkbox } from './Forms/Checkbox';
export { TextArea } from './TextArea/TextArea';
export { FileUpload } from './FileUpload/FileUpload';
export * from './FileDropzone';
export { TimeRangeInput } from './DateTimePickers/TimeRangeInput';
export { RelativeTimeRangePicker } from './DateTimePickers/RelativeTimeRangePicker/RelativeTimeRangePicker';
export { Card, Props as CardProps, getCardStyles } from './Card/Card';
export { CardContainer, CardContainerProps } from './Card/CardContainer';
export { FormattedValueDisplay } from './FormattedValueDisplay/FormattedValueDisplay';
export { ButtonSelect } from './Dropdown/ButtonSelect';
export { PluginSignatureBadge, PluginSignatureBadgeProps } from './PluginSignatureBadge/PluginSignatureBadge';
// Export this until we've figured out a good approach to inline form styles.
export { InlineFormLabel } from './FormLabel/FormLabel';
// Select
import { AsyncSelect, Select } from './Forms/Legacy/Select/Select';
import { IndicatorsContainer } from './Forms/Legacy/Select/IndicatorsContainer';
import { NoOptionsMessage } from './Forms/Legacy/Select/NoOptionsMessage';
//Input
import { Input, LegacyInputStatus } from './Forms/Legacy/Input/Input';
import { FormField } from './FormField/FormField';
import { SecretFormField } from './SecretFormField/SecretFormField';
import { Switch } from './Forms/Legacy/Switch/Switch';
const LegacyForms = {
SecretFormField,
FormField,
Select,
AsyncSelect,
IndicatorsContainer,
NoOptionsMessage,
Input,
Switch,
};
export { LegacyForms, LegacyInputStatus };
// WIP, need renames and exports cleanup
export * from './uPlot/config';
export { ScaleDistribution } from '@grafana/schema';
export { UPlotConfigBuilder } from './uPlot/config/UPlotConfigBuilder';
export { UPLOT_AXIS_FONT_SIZE } from './uPlot/config/UPlotAxisBuilder';
export { UPlotChart } from './uPlot/Plot';
export { PlotLegend } from './uPlot/PlotLegend';
export * from './uPlot/geometries';
export * from './uPlot/plugins';
export { PlotTooltipInterpolator, PlotSelection } from './uPlot/types';
export { UPlotConfigPrepFn } from './uPlot/config/UPlotConfigBuilder';
export { GraphNG, GraphNGProps, FIXED_UNIT } from './GraphNG/GraphNG';
export { TimeSeries } from './TimeSeries/TimeSeries';
export { useGraphNGContext } from './GraphNG/hooks';
export { preparePlotFrame, buildScaleKey } from './GraphNG/utils';
export { GraphNGLegendEvent } from './GraphNG/types';
export * from './PanelChrome/types';
export { EmotionPerfTest } from './ThemeDemos/EmotionPerfTest';
export { Label as BrowserLabel } from './BrowserLabel/Label';
| packages/grafana-ui/src/components/index.ts | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.000176318091689609,
0.00017275023856200278,
0.00015640056517440826,
0.0001734550460241735,
0.0000037709862681367667
] |
{
"id": 4,
"code_window": [
" />\n",
" </EditorField>\n",
" <EditorField label=\"Metric name\" width={16}>\n",
" <Select\n",
" value={query.metricName}\n",
" allowCustomValue\n",
" options={metrics}\n",
" onChange={({ value: metricName }) => {\n",
" if (metricName) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Metric name\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/MetricStatEditor/MetricStatEditor.tsx",
"type": "add",
"edit_start_line_idx": 52
} | import { Subscription } from 'rxjs';
import { getDataSourceSrv, toDataQueryError } from '@grafana/runtime';
import { DataSourceRef } from '@grafana/data';
import { updateOptions } from '../state/actions';
import { QueryVariableModel } from '../types';
import { ThunkResult } from '../../../types';
import { getVariable } from '../state/selectors';
import {
addVariableEditorError,
changeVariableEditorExtended,
removeVariableEditorError,
VariableEditorState,
} from '../editor/reducer';
import { changeVariableProp } from '../state/sharedReducer';
import { toVariableIdentifier, toVariablePayload, VariableIdentifier } from '../state/types';
import { getVariableQueryEditor } from '../editor/getVariableQueryEditor';
import { getVariableQueryRunner } from './VariableQueryRunner';
import { variableQueryObserver } from './variableQueryObserver';
import { QueryVariableEditorState } from './reducer';
export const updateQueryVariableOptions = (
identifier: VariableIdentifier,
searchFilter?: string
): ThunkResult<void> => {
return async (dispatch, getState) => {
const variableInState = getVariable<QueryVariableModel>(identifier.id, getState());
try {
if (getState().templating.editor.id === variableInState.id) {
dispatch(removeVariableEditorError({ errorProp: 'update' }));
}
const datasource = await getDataSourceSrv().get(variableInState.datasource ?? '');
// We need to await the result from variableQueryRunner before moving on otherwise variables dependent on this
// variable will have the wrong current value as input
await new Promise((resolve, reject) => {
const subscription: Subscription = new Subscription();
const observer = variableQueryObserver(resolve, reject, subscription);
const responseSubscription = getVariableQueryRunner().getResponse(identifier).subscribe(observer);
subscription.add(responseSubscription);
getVariableQueryRunner().queueRequest({ identifier, datasource, searchFilter });
});
} catch (err) {
const error = toDataQueryError(err);
if (getState().templating.editor.id === variableInState.id) {
dispatch(addVariableEditorError({ errorProp: 'update', errorText: error.message }));
}
throw error;
}
};
};
export const initQueryVariableEditor = (identifier: VariableIdentifier): ThunkResult<void> => async (
dispatch,
getState
) => {
const variable = getVariable<QueryVariableModel>(identifier.id, getState());
await dispatch(changeQueryVariableDataSource(toVariableIdentifier(variable), variable.datasource));
};
export const changeQueryVariableDataSource = (
identifier: VariableIdentifier,
name: DataSourceRef | null
): ThunkResult<void> => {
return async (dispatch, getState) => {
try {
const editorState = getState().templating.editor as VariableEditorState<QueryVariableEditorState>;
const previousDatasource = editorState.extended?.dataSource;
const dataSource = await getDataSourceSrv().get(name ?? '');
if (previousDatasource && previousDatasource.type !== dataSource?.type) {
dispatch(changeVariableProp(toVariablePayload(identifier, { propName: 'query', propValue: '' })));
}
dispatch(changeVariableEditorExtended({ propName: 'dataSource', propValue: dataSource }));
const VariableQueryEditor = await getVariableQueryEditor(dataSource);
dispatch(changeVariableEditorExtended({ propName: 'VariableQueryEditor', propValue: VariableQueryEditor }));
} catch (err) {
console.error(err);
}
};
};
export const changeQueryVariableQuery = (
identifier: VariableIdentifier,
query: any,
definition?: string
): ThunkResult<void> => async (dispatch, getState) => {
const variableInState = getVariable<QueryVariableModel>(identifier.id, getState());
if (hasSelfReferencingQuery(variableInState.name, query)) {
const errorText = 'Query cannot contain a reference to itself. Variable: $' + variableInState.name;
dispatch(addVariableEditorError({ errorProp: 'query', errorText }));
return;
}
dispatch(removeVariableEditorError({ errorProp: 'query' }));
dispatch(changeVariableProp(toVariablePayload(identifier, { propName: 'query', propValue: query })));
if (definition) {
dispatch(changeVariableProp(toVariablePayload(identifier, { propName: 'definition', propValue: definition })));
} else if (typeof query === 'string') {
dispatch(changeVariableProp(toVariablePayload(identifier, { propName: 'definition', propValue: query })));
}
await dispatch(updateOptions(identifier));
};
export function hasSelfReferencingQuery(name: string, query: any): boolean {
if (typeof query === 'string' && query.match(new RegExp('\\$' + name + '(/| |$)'))) {
return true;
}
const flattened = flattenQuery(query);
for (let prop in flattened) {
if (flattened.hasOwnProperty(prop)) {
const value = flattened[prop];
if (typeof value === 'string' && value.match(new RegExp('\\$' + name + '(/| |$)'))) {
return true;
}
}
}
return false;
}
/*
* Function that takes any object and flattens all props into one level deep object
* */
export function flattenQuery(query: any): any {
if (typeof query !== 'object') {
return { query };
}
const keys = Object.keys(query);
const flattened = keys.reduce((all, key) => {
const value = query[key];
if (typeof value !== 'object') {
all[key] = value;
return all;
}
const result = flattenQuery(value);
for (let childProp in result) {
if (result.hasOwnProperty(childProp)) {
all[`${key}_${childProp}`] = result[childProp];
}
}
return all;
}, {} as Record<string, any>);
return flattened;
}
| public/app/features/variables/query/actions.ts | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.00743603752925992,
0.0007557659992016852,
0.00016034708824008703,
0.00016971025615930557,
0.0017866032430902123
] |
{
"id": 5,
"code_window": [
" width={26}\n",
" optional\n",
" tooltip=\"ID can be used to reference other queries in math expressions. The ID can include numbers, letters, and underscore, and must start with a lowercase letter.\"\n",
" >\n",
" <Input\n",
" onBlur={onRunQuery}\n",
" onChange={(event: ChangeEvent<HTMLInputElement>) =>\n",
" this.onChange({ ...metricsQuery, id: event.target.value })\n",
" }\n",
" type=\"text\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Optional ID\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/MetricsQueryEditor.tsx",
"type": "add",
"edit_start_line_idx": 146
} | import React, { useCallback, useState } from 'react';
import { pick } from 'lodash';
import { SelectableValue } from '@grafana/data';
import { Button, ConfirmModal, RadioButtonGroup } from '@grafana/ui';
import { EditorHeader, InlineSelect, FlexItem } from '@grafana/experimental';
import { CloudWatchDatasource } from '../datasource';
import {
CloudWatchMetricsQuery,
CloudWatchQuery,
CloudWatchQueryMode,
MetricEditorMode,
MetricQueryType,
} from '../types';
import { useRegions } from '../hooks';
interface QueryHeaderProps {
query: CloudWatchMetricsQuery;
datasource: CloudWatchDatasource;
onChange: (query: CloudWatchQuery) => void;
onRunQuery: () => void;
sqlCodeEditorIsDirty: boolean;
}
const apiModes: Array<SelectableValue<CloudWatchQueryMode>> = [
{ label: 'CloudWatch Metrics', value: 'Metrics' },
{ label: 'CloudWatch Logs', value: 'Logs' },
];
const metricEditorModes: Array<SelectableValue<MetricQueryType>> = [
{ label: 'Metric Search', value: MetricQueryType.Search },
{ label: 'Metric Query', value: MetricQueryType.Query },
];
const editorModes = [
{ label: 'Builder', value: MetricEditorMode.Builder },
{ label: 'Code', value: MetricEditorMode.Code },
];
const QueryHeader: React.FC<QueryHeaderProps> = ({ query, sqlCodeEditorIsDirty, datasource, onChange, onRunQuery }) => {
const { metricEditorMode, metricQueryType, queryMode, region } = query;
const [showConfirm, setShowConfirm] = useState(false);
const [regions, regionIsLoading] = useRegions(datasource);
const onEditorModeChange = useCallback(
(newMetricEditorMode: MetricEditorMode) => {
if (
sqlCodeEditorIsDirty &&
metricQueryType === MetricQueryType.Query &&
metricEditorMode === MetricEditorMode.Code
) {
setShowConfirm(true);
return;
}
onChange({ ...query, metricEditorMode: newMetricEditorMode });
},
[setShowConfirm, onChange, sqlCodeEditorIsDirty, query, metricEditorMode, metricQueryType]
);
const onQueryModeChange = ({ value }: SelectableValue<CloudWatchQueryMode>) => {
if (value !== queryMode) {
const commonProps = pick(query, 'id', 'region', 'namespace', 'refId', 'hide', 'key', 'queryType', 'datasource');
onChange({
...commonProps,
queryMode: value,
});
}
};
return (
<EditorHeader>
<InlineSelect
label="Region"
value={regions.find((v) => v.value === region)}
placeholder="Select region"
allowCustomValue
onChange={({ value: region }) => region && onChange({ ...query, region: region })}
options={regions}
isLoading={regionIsLoading}
/>
<InlineSelect value={queryMode} options={apiModes} onChange={onQueryModeChange} />
<InlineSelect
value={metricEditorModes.find((m) => m.value === metricQueryType)}
options={metricEditorModes}
onChange={({ value }) => {
onChange({ ...query, metricQueryType: value });
}}
/>
<FlexItem grow={1} />
<RadioButtonGroup options={editorModes} size="sm" value={metricEditorMode} onChange={onEditorModeChange} />
{query.metricQueryType === MetricQueryType.Query && query.metricEditorMode === MetricEditorMode.Code && (
<Button variant="secondary" size="sm" onClick={() => onRunQuery()}>
Run query
</Button>
)}
<ConfirmModal
isOpen={showConfirm}
title="Are you sure?"
body="You will lose manual changes done to the query if you go back to the visual builder."
confirmText="Yes, I am sure."
dismissText="No, continue editing the query manually."
icon="exclamation-triangle"
onConfirm={() => {
setShowConfirm(false);
onChange({ ...query, metricEditorMode: MetricEditorMode.Builder });
}}
onDismiss={() => setShowConfirm(false)}
/>
</EditorHeader>
);
};
export default QueryHeader;
| public/app/plugins/datasource/cloudwatch/components/QueryHeader.tsx | 1 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.016822926700115204,
0.0022672447375953197,
0.00016504530503880233,
0.0012352437479421496,
0.00429517962038517
] |
{
"id": 5,
"code_window": [
" width={26}\n",
" optional\n",
" tooltip=\"ID can be used to reference other queries in math expressions. The ID can include numbers, letters, and underscore, and must start with a lowercase letter.\"\n",
" >\n",
" <Input\n",
" onBlur={onRunQuery}\n",
" onChange={(event: ChangeEvent<HTMLInputElement>) =>\n",
" this.onChange({ ...metricsQuery, id: event.target.value })\n",
" }\n",
" type=\"text\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Optional ID\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/MetricsQueryEditor.tsx",
"type": "add",
"edit_start_line_idx": 146
} | declare var CloudWatchDatasource: any;
export default CloudWatchDatasource;
| public/app/plugins/datasource/cloudwatch/datasource.d.ts | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.00016840880562085658,
0.00016840880562085658,
0.00016840880562085658,
0.00016840880562085658,
0
] |
{
"id": 5,
"code_window": [
" width={26}\n",
" optional\n",
" tooltip=\"ID can be used to reference other queries in math expressions. The ID can include numbers, letters, and underscore, and must start with a lowercase letter.\"\n",
" >\n",
" <Input\n",
" onBlur={onRunQuery}\n",
" onChange={(event: ChangeEvent<HTMLInputElement>) =>\n",
" this.onChange({ ...metricsQuery, id: event.target.value })\n",
" }\n",
" type=\"text\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Optional ID\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/MetricsQueryEditor.tsx",
"type": "add",
"edit_start_line_idx": 146
} | +++
title = "KMS integration"
description = ""
keywords = ["grafana", "kms", "key management system integration"]
weight = 1200
+++
# Key management systems (KMSs)
You can choose to encrypt secrets stored in the Grafana database using a key from a KMS, which is a secure central storage location that is designed to help you to create and manage cryptographic keys and control their use across many services. When you integrate with a KMS, Grafana does not directly store your encryption key. Instead, Grafana stores KMS credentials and the identifier of the key, which Grafana uses to encrypt the database.
Grafana integrates with the following key management systems:
- [AWS KMS]({{< relref "/using-aws-kms-to-encrypt-database-secrets.md" >}})
- [Azure Key Vault]({{< relref "/using-azure-key-vault-to-encrypt-database-secrets.md" >}})
Refer to [Database encryption]({{< relref "../../administration/database-encryption.md" >}}) to learn more about how Grafana encrypts secrets in the database.
| docs/sources/enterprise/kms-integration/_index.md | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.00016818655421957374,
0.00016592512838542461,
0.0001636637025512755,
0.00016592512838542461,
0.0000022614258341491222
] |
{
"id": 5,
"code_window": [
" width={26}\n",
" optional\n",
" tooltip=\"ID can be used to reference other queries in math expressions. The ID can include numbers, letters, and underscore, and must start with a lowercase letter.\"\n",
" >\n",
" <Input\n",
" onBlur={onRunQuery}\n",
" onChange={(event: ChangeEvent<HTMLInputElement>) =>\n",
" this.onChange({ ...metricsQuery, id: event.target.value })\n",
" }\n",
" type=\"text\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Optional ID\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/MetricsQueryEditor.tsx",
"type": "add",
"edit_start_line_idx": 146
} | import { AnyAction } from 'redux';
import { isEqual } from 'lodash';
import {
DEFAULT_RANGE,
getQueryKeys,
parseUrlState,
ensureQueries,
generateNewKeyAndAddRefIdIfMissing,
getTimeRangeFromUrl,
ExploreGraphStyle,
} from 'app/core/utils/explore';
import { ExploreId, ExploreItemState } from 'app/types/explore';
import { queryReducer, runQueries, setQueriesAction } from './query';
import { datasourceReducer } from './datasource';
import { timeReducer, updateTime } from './time';
import { historyReducer } from './history';
import {
makeExplorePaneState,
loadAndInitDatasource,
createEmptyQueryResponse,
getUrlStateFromPaneState,
storeGraphStyle,
} from './utils';
import { createAction, PayloadAction } from '@reduxjs/toolkit';
import { EventBusExtended, DataQuery, ExploreUrlState, TimeRange, HistoryItem, DataSourceApi } from '@grafana/data';
// Types
import { ThunkResult } from 'app/types';
import { getFiscalYearStartMonth, getTimeZone } from 'app/features/profile/state/selectors';
import { getDataSourceSrv } from '@grafana/runtime';
import { getRichHistory } from '../../../core/utils/richHistory';
import { richHistoryUpdatedAction } from './main';
//
// Actions and Payloads
//
/**
* Keep track of the Explore container size, in particular the width.
* The width will be used to calculate graph intervals (number of datapoints).
*/
export interface ChangeSizePayload {
exploreId: ExploreId;
width: number;
height: number;
}
export const changeSizeAction = createAction<ChangeSizePayload>('explore/changeSize');
/**
* Initialize Explore state with state from the URL and the React component.
* Call this only on components for with the Explore state has not been initialized.
*/
export interface InitializeExplorePayload {
exploreId: ExploreId;
containerWidth: number;
eventBridge: EventBusExtended;
queries: DataQuery[];
range: TimeRange;
history: HistoryItem[];
datasourceInstance?: DataSourceApi;
originPanelId?: number | null;
}
export const initializeExploreAction = createAction<InitializeExplorePayload>('explore/initializeExplore');
export interface SetUrlReplacedPayload {
exploreId: ExploreId;
}
export const setUrlReplacedAction = createAction<SetUrlReplacedPayload>('explore/setUrlReplaced');
/**
* Keep track of the Explore container size, in particular the width.
* The width will be used to calculate graph intervals (number of datapoints).
*/
export function changeSize(
exploreId: ExploreId,
{ height, width }: { height: number; width: number }
): PayloadAction<ChangeSizePayload> {
return changeSizeAction({ exploreId, height, width });
}
interface ChangeGraphStylePayload {
exploreId: ExploreId;
graphStyle: ExploreGraphStyle;
}
const changeGraphStyleAction = createAction<ChangeGraphStylePayload>('explore/changeGraphStyle');
export function changeGraphStyle(exploreId: ExploreId, graphStyle: ExploreGraphStyle): ThunkResult<void> {
return async (dispatch, getState) => {
storeGraphStyle(graphStyle);
dispatch(changeGraphStyleAction({ exploreId, graphStyle }));
};
}
/**
* Initialize Explore state with state from the URL and the React component.
* Call this only on components for with the Explore state has not been initialized.
*/
export function initializeExplore(
exploreId: ExploreId,
datasourceNameOrUid: string,
queries: DataQuery[],
range: TimeRange,
containerWidth: number,
eventBridge: EventBusExtended,
originPanelId?: number | null
): ThunkResult<void> {
return async (dispatch, getState) => {
const exploreDatasources = getDataSourceSrv().getList();
let instance = undefined;
let history: HistoryItem[] = [];
if (exploreDatasources.length >= 1) {
const orgId = getState().user.orgId;
const loadResult = await loadAndInitDatasource(orgId, datasourceNameOrUid);
instance = loadResult.instance;
history = loadResult.history;
}
dispatch(
initializeExploreAction({
exploreId,
containerWidth,
eventBridge,
queries,
range,
originPanelId,
datasourceInstance: instance,
history,
})
);
dispatch(updateTime({ exploreId }));
if (instance) {
// We do not want to add the url to browser history on init because when the pane is initialised it's because
// we already have something in the url. Adding basically the same state as additional history item prevents
// user to go back to previous url.
dispatch(runQueries(exploreId, { replaceUrl: true }));
}
const richHistory = getRichHistory();
dispatch(richHistoryUpdatedAction({ richHistory }));
};
}
/**
* Reacts to changes in URL state that we need to sync back to our redux state. Computes diff of newUrlQuery vs current
* state and runs update actions for relevant parts.
*/
export function refreshExplore(exploreId: ExploreId, newUrlQuery: string): ThunkResult<void> {
return async (dispatch, getState) => {
const itemState = getState().explore[exploreId]!;
if (!itemState.initialized) {
return;
}
// Get diff of what should be updated
const newUrlState = parseUrlState(newUrlQuery);
const update = urlDiff(newUrlState, getUrlStateFromPaneState(itemState));
const { containerWidth, eventBridge } = itemState;
const { datasource, queries, range: urlRange, originPanelId } = newUrlState;
const refreshQueries: DataQuery[] = [];
for (let index = 0; index < queries.length; index++) {
const query = queries[index];
refreshQueries.push(generateNewKeyAndAddRefIdIfMissing(query, refreshQueries, index));
}
const timeZone = getTimeZone(getState().user);
const fiscalYearStartMonth = getFiscalYearStartMonth(getState().user);
const range = getTimeRangeFromUrl(urlRange, timeZone, fiscalYearStartMonth);
// commit changes based on the diff of new url vs old url
if (update.datasource) {
const initialQueries = ensureQueries(queries);
await dispatch(
initializeExplore(exploreId, datasource, initialQueries, range, containerWidth, eventBridge, originPanelId)
);
return;
}
if (update.range) {
dispatch(updateTime({ exploreId, rawRange: range.raw }));
}
if (update.queries) {
dispatch(setQueriesAction({ exploreId, queries: refreshQueries }));
}
// always run queries when refresh is needed
if (update.queries || update.range) {
dispatch(runQueries(exploreId));
}
};
}
/**
* Reducer for an Explore area, to be used by the global Explore reducer.
*/
// Redux Toolkit uses ImmerJs as part of their solution to ensure that state objects are not mutated.
// ImmerJs has an autoFreeze option that freezes objects from change which means this reducer can't be migrated to createSlice
// because the state would become frozen and during run time we would get errors because flot (Graph lib) would try to mutate
// the frozen state.
// https://github.com/reduxjs/redux-toolkit/issues/242
export const paneReducer = (state: ExploreItemState = makeExplorePaneState(), action: AnyAction): ExploreItemState => {
state = queryReducer(state, action);
state = datasourceReducer(state, action);
state = timeReducer(state, action);
state = historyReducer(state, action);
if (changeSizeAction.match(action)) {
const containerWidth = action.payload.width;
return { ...state, containerWidth };
}
if (changeGraphStyleAction.match(action)) {
const { graphStyle } = action.payload;
return { ...state, graphStyle };
}
if (initializeExploreAction.match(action)) {
const { containerWidth, eventBridge, queries, range, originPanelId, datasourceInstance, history } = action.payload;
return {
...state,
containerWidth,
eventBridge,
range,
queries,
initialized: true,
queryKeys: getQueryKeys(queries, datasourceInstance),
originPanelId,
datasourceInstance,
history,
datasourceMissing: !datasourceInstance,
queryResponse: createEmptyQueryResponse(),
cache: [],
};
}
return state;
};
/**
* Compare 2 explore urls and return a map of what changed. Used to update the local state with all the
* side effects needed.
*/
export const urlDiff = (
oldUrlState: ExploreUrlState | undefined,
currentUrlState: ExploreUrlState | undefined
): {
datasource: boolean;
queries: boolean;
range: boolean;
} => {
const datasource = !isEqual(currentUrlState?.datasource, oldUrlState?.datasource);
const queries = !isEqual(currentUrlState?.queries, oldUrlState?.queries);
const range = !isEqual(currentUrlState?.range || DEFAULT_RANGE, oldUrlState?.range || DEFAULT_RANGE);
return {
datasource,
queries,
range,
};
};
| public/app/features/explore/state/explorePane.ts | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.0003209903370589018,
0.00017327007662970573,
0.00016140445950441062,
0.00016740722639951855,
0.00002923529245890677
] |
{
"id": 6,
"code_window": [
" />\n",
" </EditorField>\n",
"\n",
" <EditorField label=\"Period\" width={26} tooltip=\"Minimum interval between points in seconds.\">\n",
" <Input\n",
" value={query.period || ''}\n",
" placeholder=\"auto\"\n",
" onBlur={onRunQuery}\n",
" onChange={(event: ChangeEvent<HTMLInputElement>) =>\n",
" this.onChange({ ...metricsQuery, period: event.target.value })\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Period\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/MetricsQueryEditor.tsx",
"type": "add",
"edit_start_line_idx": 158
} | import React, { useCallback, useState } from 'react';
import { pick } from 'lodash';
import { SelectableValue } from '@grafana/data';
import { Button, ConfirmModal, RadioButtonGroup } from '@grafana/ui';
import { EditorHeader, InlineSelect, FlexItem } from '@grafana/experimental';
import { CloudWatchDatasource } from '../datasource';
import {
CloudWatchMetricsQuery,
CloudWatchQuery,
CloudWatchQueryMode,
MetricEditorMode,
MetricQueryType,
} from '../types';
import { useRegions } from '../hooks';
interface QueryHeaderProps {
query: CloudWatchMetricsQuery;
datasource: CloudWatchDatasource;
onChange: (query: CloudWatchQuery) => void;
onRunQuery: () => void;
sqlCodeEditorIsDirty: boolean;
}
const apiModes: Array<SelectableValue<CloudWatchQueryMode>> = [
{ label: 'CloudWatch Metrics', value: 'Metrics' },
{ label: 'CloudWatch Logs', value: 'Logs' },
];
const metricEditorModes: Array<SelectableValue<MetricQueryType>> = [
{ label: 'Metric Search', value: MetricQueryType.Search },
{ label: 'Metric Query', value: MetricQueryType.Query },
];
const editorModes = [
{ label: 'Builder', value: MetricEditorMode.Builder },
{ label: 'Code', value: MetricEditorMode.Code },
];
const QueryHeader: React.FC<QueryHeaderProps> = ({ query, sqlCodeEditorIsDirty, datasource, onChange, onRunQuery }) => {
const { metricEditorMode, metricQueryType, queryMode, region } = query;
const [showConfirm, setShowConfirm] = useState(false);
const [regions, regionIsLoading] = useRegions(datasource);
const onEditorModeChange = useCallback(
(newMetricEditorMode: MetricEditorMode) => {
if (
sqlCodeEditorIsDirty &&
metricQueryType === MetricQueryType.Query &&
metricEditorMode === MetricEditorMode.Code
) {
setShowConfirm(true);
return;
}
onChange({ ...query, metricEditorMode: newMetricEditorMode });
},
[setShowConfirm, onChange, sqlCodeEditorIsDirty, query, metricEditorMode, metricQueryType]
);
const onQueryModeChange = ({ value }: SelectableValue<CloudWatchQueryMode>) => {
if (value !== queryMode) {
const commonProps = pick(query, 'id', 'region', 'namespace', 'refId', 'hide', 'key', 'queryType', 'datasource');
onChange({
...commonProps,
queryMode: value,
});
}
};
return (
<EditorHeader>
<InlineSelect
label="Region"
value={regions.find((v) => v.value === region)}
placeholder="Select region"
allowCustomValue
onChange={({ value: region }) => region && onChange({ ...query, region: region })}
options={regions}
isLoading={regionIsLoading}
/>
<InlineSelect value={queryMode} options={apiModes} onChange={onQueryModeChange} />
<InlineSelect
value={metricEditorModes.find((m) => m.value === metricQueryType)}
options={metricEditorModes}
onChange={({ value }) => {
onChange({ ...query, metricQueryType: value });
}}
/>
<FlexItem grow={1} />
<RadioButtonGroup options={editorModes} size="sm" value={metricEditorMode} onChange={onEditorModeChange} />
{query.metricQueryType === MetricQueryType.Query && query.metricEditorMode === MetricEditorMode.Code && (
<Button variant="secondary" size="sm" onClick={() => onRunQuery()}>
Run query
</Button>
)}
<ConfirmModal
isOpen={showConfirm}
title="Are you sure?"
body="You will lose manual changes done to the query if you go back to the visual builder."
confirmText="Yes, I am sure."
dismissText="No, continue editing the query manually."
icon="exclamation-triangle"
onConfirm={() => {
setShowConfirm(false);
onChange({ ...query, metricEditorMode: MetricEditorMode.Builder });
}}
onDismiss={() => setShowConfirm(false)}
/>
</EditorHeader>
);
};
export default QueryHeader;
| public/app/plugins/datasource/cloudwatch/components/QueryHeader.tsx | 1 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.004694923758506775,
0.0013041781494393945,
0.00016423243505414575,
0.0007086400873959064,
0.001353551633656025
] |
{
"id": 6,
"code_window": [
" />\n",
" </EditorField>\n",
"\n",
" <EditorField label=\"Period\" width={26} tooltip=\"Minimum interval between points in seconds.\">\n",
" <Input\n",
" value={query.period || ''}\n",
" placeholder=\"auto\"\n",
" onBlur={onRunQuery}\n",
" onChange={(event: ChangeEvent<HTMLInputElement>) =>\n",
" this.onChange({ ...metricsQuery, period: event.target.value })\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Period\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/MetricsQueryEditor.tsx",
"type": "add",
"edit_start_line_idx": 158
} | input.validation-error,
input.ng-dirty.ng-invalid {
box-shadow: inset 0 0px 5px $red;
}
input.invalid {
box-shadow: inset 0 0px 5px $red;
}
| public/sass/utils/_validation.scss | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.00017038160876836628,
0.00017038160876836628,
0.00017038160876836628,
0.00017038160876836628,
0
] |
{
"id": 6,
"code_window": [
" />\n",
" </EditorField>\n",
"\n",
" <EditorField label=\"Period\" width={26} tooltip=\"Minimum interval between points in seconds.\">\n",
" <Input\n",
" value={query.period || ''}\n",
" placeholder=\"auto\"\n",
" onBlur={onRunQuery}\n",
" onChange={(event: ChangeEvent<HTMLInputElement>) =>\n",
" this.onChange({ ...metricsQuery, period: event.target.value })\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Period\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/MetricsQueryEditor.tsx",
"type": "add",
"edit_start_line_idx": 158
} | package pipeline
import (
"context"
"time"
)
type AutoJsonConverter struct {
config AutoJsonConverterConfig
nowTimeFunc func() time.Time
}
func NewAutoJsonConverter(c AutoJsonConverterConfig) *AutoJsonConverter {
return &AutoJsonConverter{config: c}
}
const ConverterTypeJsonAuto = "jsonAuto"
func (c *AutoJsonConverter) Type() string {
return ConverterTypeJsonAuto
}
// Automatic conversion works this way:
// * Time added automatically
// * Nulls dropped
// To preserve nulls we need FieldTips from a user.
// Custom time can be injected on FrameProcessor stage theoretically.
// Custom labels can be injected on FrameProcessor stage theoretically.
func (c *AutoJsonConverter) Convert(_ context.Context, vars Vars, body []byte) ([]*ChannelFrame, error) {
nowTimeFunc := c.nowTimeFunc
if nowTimeFunc == nil {
nowTimeFunc = time.Now
}
frame, err := jsonDocToFrame(vars.Path, body, c.config.FieldTips, nowTimeFunc)
if err != nil {
return nil, err
}
return []*ChannelFrame{
{Channel: "", Frame: frame},
}, nil
}
| pkg/services/live/pipeline/converter_json_auto.go | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.00018438661936670542,
0.00017219979781657457,
0.00016532976587768644,
0.00017060627578757703,
0.0000068226931944082025
] |
{
"id": 6,
"code_window": [
" />\n",
" </EditorField>\n",
"\n",
" <EditorField label=\"Period\" width={26} tooltip=\"Minimum interval between points in seconds.\">\n",
" <Input\n",
" value={query.period || ''}\n",
" placeholder=\"auto\"\n",
" onBlur={onRunQuery}\n",
" onChange={(event: ChangeEvent<HTMLInputElement>) =>\n",
" this.onChange({ ...metricsQuery, period: event.target.value })\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Period\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/MetricsQueryEditor.tsx",
"type": "add",
"edit_start_line_idx": 158
} | {
"title": "Grafana1",
"tags": [],
"id": 3,
"style": "dark",
"timezone": "browser",
"editable": true,
"rows": [
{
"title": "New row",
"height": "150px",
"collapse": false,
"editable": true,
"panels": [
{
"id": 1,
"span": 12,
"editable": true,
"type": "text",
"mode": "html",
"content": "<div class=\"text-center\" style=\"padding-top: 15px\">\n<img src=\"img/logo_transparent_200x.png\"> \n</div>",
"style": {},
"title": "Welcome to"
}
]
}
],
"nav": [
{
"type": "timepicker",
"collapse": false,
"enable": true,
"status": "Stable",
"time_options": [
"5m",
"15m",
"1h",
"6h",
"12h",
"24h",
"2d",
"7d",
"30d"
],
"refresh_intervals": [
"5s",
"10s",
"30s",
"1m",
"5m",
"15m",
"30m",
"1h",
"2h",
"1d"
],
"now": true
}
],
"time": {
"from": "now-6h",
"to": "now"
},
"templating": {
"list": []
},
"version": 5
}
| pkg/services/provisioning/dashboards/testdata/test-dashboards/containing-id/dashboard1.json | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.00017588253831490874,
0.00017380795907229185,
0.00017097496311180294,
0.00017375656170770526,
0.0000015142850315896794
] |
{
"id": 7,
"code_window": [
" options={regions}\n",
" isLoading={regionIsLoading}\n",
" />\n",
"\n",
" <InlineSelect value={queryMode} options={apiModes} onChange={onQueryModeChange} />\n",
"\n",
" <InlineSelect\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" <InlineSelect aria-label=\"Query mode\" value={queryMode} options={apiModes} onChange={onQueryModeChange} />\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/QueryHeader.tsx",
"type": "replace",
"edit_start_line_idx": 84
} | import React, { FunctionComponent, useState } from 'react';
import { debounce } from 'lodash';
import { Input } from '@grafana/ui';
export interface Props {
onChange: (alias: any) => void;
value: string;
}
export const Alias: FunctionComponent<Props> = ({ value = '', onChange }) => {
const [alias, setAlias] = useState(value);
const propagateOnChange = debounce(onChange, 1500);
onChange = (e: any) => {
setAlias(e.target.value);
propagateOnChange(e.target.value);
};
return <Input type="text" value={alias} onChange={onChange} />;
};
| public/app/plugins/datasource/cloudwatch/components/Alias.tsx | 1 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.00888736080378294,
0.003078114939853549,
0.00017030525486916304,
0.00017667807696852833,
0.0041077579371631145
] |
{
"id": 7,
"code_window": [
" options={regions}\n",
" isLoading={regionIsLoading}\n",
" />\n",
"\n",
" <InlineSelect value={queryMode} options={apiModes} onChange={onQueryModeChange} />\n",
"\n",
" <InlineSelect\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" <InlineSelect aria-label=\"Query mode\" value={queryMode} options={apiModes} onChange={onQueryModeChange} />\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/QueryHeader.tsx",
"type": "replace",
"edit_start_line_idx": 84
} | import React, { ChangeEvent, useState } from 'react';
import { Button, Icon, InlineField, InlineFieldRow, Input } from '@grafana/ui';
import MappingsHelp from './MappingsHelp';
type Props = {
mappings: string[];
onChange: (mappings: string[]) => void;
onDismiss: () => void;
onRestoreHelp: () => void;
showHelp: boolean;
};
export const MappingsConfiguration = (props: Props): JSX.Element => {
const [mappings, setMappings] = useState(props.mappings || []);
return (
<div>
<h3 className="page-heading">Label mappings</h3>
{!props.showHelp && (
<p>
<Button variant="link" onClick={props.onRestoreHelp}>
Learn how label mappings work
</Button>
</p>
)}
{props.showHelp && <MappingsHelp onDismiss={props.onDismiss} />}
<div className="gf-form-group">
{mappings.map((mapping, i) => (
<InlineFieldRow key={i}>
<InlineField label={`Mapping (${i + 1})`}>
<Input
width={50}
onChange={(changeEvent: ChangeEvent<HTMLInputElement>) => {
let newMappings = mappings.concat();
newMappings[i] = changeEvent.target.value;
setMappings(newMappings);
}}
onBlur={() => {
props.onChange(mappings);
}}
placeholder="e.g. test.metric.(labelName).*"
value={mapping}
/>
</InlineField>
<Button
type="button"
aria-label="Remove header"
variant="secondary"
size="xs"
onClick={(_) => {
let newMappings = mappings.concat();
newMappings.splice(i, 1);
setMappings(newMappings);
props.onChange(newMappings);
}}
>
<Icon name="trash-alt" />
</Button>
</InlineFieldRow>
))}
<Button
variant="secondary"
icon="plus"
type="button"
onClick={() => {
setMappings([...mappings, '']);
}}
>
Add label mapping
</Button>
</div>
</div>
);
};
| public/app/plugins/datasource/graphite/configuration/MappingsConfiguration.tsx | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.004152690526098013,
0.0013984652468934655,
0.0001656532404012978,
0.00017774984007701278,
0.0016442235792055726
] |
{
"id": 7,
"code_window": [
" options={regions}\n",
" isLoading={regionIsLoading}\n",
" />\n",
"\n",
" <InlineSelect value={queryMode} options={apiModes} onChange={onQueryModeChange} />\n",
"\n",
" <InlineSelect\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" <InlineSelect aria-label=\"Query mode\" value={queryMode} options={apiModes} onChange={onQueryModeChange} />\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/QueryHeader.tsx",
"type": "replace",
"edit_start_line_idx": 84
} | {
"panels": [
{
"datasource": "${DS_GDEV-TESTDATA}",
"fieldConfig": {
"defaults": {
"custom": {
"align": "right",
"filterable": false
},
"decimals": 3,
"mappings": [],
"unit": "watt"
}
}
}
]
}
| pkg/cmd/grafana-cli/commands/testdata/panels/invalid_resource_panel.json | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.0001753370015649125,
0.00017505066352896392,
0.00017476434004493058,
0.00017505066352896392,
2.8633075999096036e-7
] |
{
"id": 7,
"code_window": [
" options={regions}\n",
" isLoading={regionIsLoading}\n",
" />\n",
"\n",
" <InlineSelect value={queryMode} options={apiModes} onChange={onQueryModeChange} />\n",
"\n",
" <InlineSelect\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" <InlineSelect aria-label=\"Query mode\" value={queryMode} options={apiModes} onChange={onQueryModeChange} />\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/QueryHeader.tsx",
"type": "replace",
"edit_start_line_idx": 84
} | package sqlstore
import (
"context"
"time"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/models"
)
func (ss *SQLStore) addTempUserQueryAndCommandHandlers() {
bus.AddHandler("sql", ss.CreateTempUser)
bus.AddHandler("sql", ss.GetTempUsersQuery)
bus.AddHandler("sql", ss.UpdateTempUserStatus)
bus.AddHandler("sql", ss.GetTempUserByCode)
bus.AddHandler("sql", ss.UpdateTempUserWithEmailSent)
bus.AddHandler("sql", ss.ExpireOldUserInvites)
}
func (ss *SQLStore) UpdateTempUserStatus(ctx context.Context, cmd *models.UpdateTempUserStatusCommand) error {
return ss.WithTransactionalDbSession(ctx, func(sess *DBSession) error {
var rawSQL = "UPDATE temp_user SET status=? WHERE code=?"
_, err := sess.Exec(rawSQL, string(cmd.Status), cmd.Code)
return err
})
}
func (ss *SQLStore) CreateTempUser(ctx context.Context, cmd *models.CreateTempUserCommand) error {
return ss.WithTransactionalDbSession(ctx, func(sess *DBSession) error {
// create user
user := &models.TempUser{
Email: cmd.Email,
Name: cmd.Name,
OrgId: cmd.OrgId,
Code: cmd.Code,
Role: cmd.Role,
Status: cmd.Status,
RemoteAddr: cmd.RemoteAddr,
InvitedByUserId: cmd.InvitedByUserId,
EmailSentOn: time.Now(),
Created: time.Now().Unix(),
Updated: time.Now().Unix(),
}
if _, err := sess.Insert(user); err != nil {
return err
}
cmd.Result = user
return nil
})
}
func (ss *SQLStore) UpdateTempUserWithEmailSent(ctx context.Context, cmd *models.UpdateTempUserWithEmailSentCommand) error {
return ss.WithTransactionalDbSession(ctx, func(sess *DBSession) error {
user := &models.TempUser{
EmailSent: true,
EmailSentOn: time.Now(),
}
_, err := sess.Where("code = ?", cmd.Code).Cols("email_sent", "email_sent_on").Update(user)
return err
})
}
func (ss *SQLStore) GetTempUsersQuery(ctx context.Context, query *models.GetTempUsersQuery) error {
return ss.WithDbSession(ctx, func(dbSess *DBSession) error {
rawSQL := `SELECT
tu.id as id,
tu.org_id as org_id,
tu.email as email,
tu.name as name,
tu.role as role,
tu.code as code,
tu.status as status,
tu.email_sent as email_sent,
tu.email_sent_on as email_sent_on,
tu.created as created,
u.login as invited_by_login,
u.name as invited_by_name,
u.email as invited_by_email
FROM ` + dialect.Quote("temp_user") + ` as tu
LEFT OUTER JOIN ` + dialect.Quote("user") + ` as u on u.id = tu.invited_by_user_id
WHERE tu.status=?`
params := []interface{}{string(query.Status)}
if query.OrgId > 0 {
rawSQL += ` AND tu.org_id=?`
params = append(params, query.OrgId)
}
if query.Email != "" {
rawSQL += ` AND tu.email=?`
params = append(params, query.Email)
}
rawSQL += " ORDER BY tu.created desc"
query.Result = make([]*models.TempUserDTO, 0)
sess := dbSess.SQL(rawSQL, params...)
err := sess.Find(&query.Result)
return err
})
}
func (ss *SQLStore) GetTempUserByCode(ctx context.Context, query *models.GetTempUserByCodeQuery) error {
return ss.WithDbSession(ctx, func(dbSess *DBSession) error {
var rawSQL = `SELECT
tu.id as id,
tu.org_id as org_id,
tu.email as email,
tu.name as name,
tu.role as role,
tu.code as code,
tu.status as status,
tu.email_sent as email_sent,
tu.email_sent_on as email_sent_on,
tu.created as created,
u.login as invited_by_login,
u.name as invited_by_name,
u.email as invited_by_email
FROM ` + dialect.Quote("temp_user") + ` as tu
LEFT OUTER JOIN ` + dialect.Quote("user") + ` as u on u.id = tu.invited_by_user_id
WHERE tu.code=?`
var tempUser models.TempUserDTO
sess := dbSess.SQL(rawSQL, query.Code)
has, err := sess.Get(&tempUser)
if err != nil {
return err
} else if !has {
return models.ErrTempUserNotFound
}
query.Result = &tempUser
return err
})
}
func (ss *SQLStore) ExpireOldUserInvites(ctx context.Context, cmd *models.ExpireTempUsersCommand) error {
return ss.WithTransactionalDbSession(ctx, func(sess *DBSession) error {
var rawSQL = "UPDATE temp_user SET status = ?, updated = ? WHERE created <= ? AND status in (?, ?)"
if result, err := sess.Exec(rawSQL, string(models.TmpUserExpired), time.Now().Unix(), cmd.OlderThan.Unix(), string(models.TmpUserSignUpStarted), string(models.TmpUserInvitePending)); err != nil {
return err
} else if cmd.NumExpired, err = result.RowsAffected(); err != nil {
return err
}
return nil
})
}
| pkg/services/sqlstore/temp_user.go | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.0003142946807201952,
0.0001796135475160554,
0.00016609531303402036,
0.00017046392895281315,
0.000034884928027167916
] |
{
"id": 8,
"code_window": [
"\n",
" <InlineSelect\n",
" value={metricEditorModes.find((m) => m.value === metricQueryType)}\n",
" options={metricEditorModes}\n",
" onChange={({ value }) => {\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Metric editor mode\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/QueryHeader.tsx",
"type": "add",
"edit_start_line_idx": 87
} | import React, { ChangeEvent, PureComponent } from 'react';
import { QueryEditorProps } from '@grafana/data';
import { EditorField, EditorRow, Space } from '@grafana/experimental';
import { Input } from '@grafana/ui';
import { CloudWatchDatasource } from '../datasource';
import { isMetricsQuery } from '../guards';
import {
CloudWatchJsonData,
CloudWatchMetricsQuery,
CloudWatchQuery,
MetricEditorMode,
MetricQueryType,
} from '../types';
import { Alias, MathExpressionQueryField, MetricStatEditor, SQLBuilderEditor, SQLCodeEditor } from './';
import QueryHeader from './QueryHeader';
export type Props = QueryEditorProps<CloudWatchDatasource, CloudWatchQuery, CloudWatchJsonData>;
interface State {
sqlCodeEditorIsDirty: boolean;
}
export const normalizeQuery = ({
namespace,
metricName,
expression,
dimensions,
region,
id,
alias,
statistic,
period,
sqlExpression,
metricQueryType,
metricEditorMode,
...rest
}: CloudWatchMetricsQuery): CloudWatchMetricsQuery => {
const normalizedQuery = {
queryMode: 'Metrics' as const,
namespace: namespace ?? '',
metricName: metricName ?? '',
expression: expression ?? '',
dimensions: dimensions ?? {},
region: region ?? 'default',
id: id ?? '',
alias: alias ?? '',
statistic: statistic ?? 'Average',
period: period ?? '',
metricQueryType: metricQueryType ?? MetricQueryType.Search,
metricEditorMode: metricEditorMode ?? MetricEditorMode.Builder,
sqlExpression: sqlExpression ?? '',
...rest,
};
return !rest.hasOwnProperty('matchExact') ? { ...normalizedQuery, matchExact: true } : normalizedQuery;
};
export class MetricsQueryEditor extends PureComponent<Props, State> {
state = {
sqlCodeEditorIsDirty: false,
};
componentDidMount = () => {
const metricsQuery = this.props.query as CloudWatchMetricsQuery;
const query = normalizeQuery(metricsQuery);
this.props.onChange(query);
};
onChange = (query: CloudWatchQuery) => {
const { onChange, onRunQuery } = this.props;
onChange(query);
onRunQuery();
};
render() {
const { onRunQuery, datasource } = this.props;
const metricsQuery = this.props.query as CloudWatchMetricsQuery;
const query = normalizeQuery(metricsQuery);
return (
<>
<QueryHeader
query={query}
onRunQuery={onRunQuery}
datasource={datasource}
onChange={(newQuery) => {
if (isMetricsQuery(newQuery) && newQuery.metricEditorMode !== query.metricEditorMode) {
this.setState({ sqlCodeEditorIsDirty: false });
}
this.onChange(newQuery);
}}
sqlCodeEditorIsDirty={this.state.sqlCodeEditorIsDirty}
/>
<Space v={0.5} />
{query.metricQueryType === MetricQueryType.Search && (
<>
{query.metricEditorMode === MetricEditorMode.Builder && (
<MetricStatEditor {...{ ...this.props, query }}></MetricStatEditor>
)}
{query.metricEditorMode === MetricEditorMode.Code && (
<MathExpressionQueryField
onRunQuery={onRunQuery}
expression={query.expression ?? ''}
onChange={(expression) => this.props.onChange({ ...query, expression })}
></MathExpressionQueryField>
)}
</>
)}
{query.metricQueryType === MetricQueryType.Query && (
<>
{query.metricEditorMode === MetricEditorMode.Code && (
<SQLCodeEditor
region={query.region}
sql={query.sqlExpression ?? ''}
onChange={(sqlExpression) => {
if (!this.state.sqlCodeEditorIsDirty) {
this.setState({ sqlCodeEditorIsDirty: true });
}
this.props.onChange({ ...metricsQuery, sqlExpression });
}}
onRunQuery={onRunQuery}
datasource={datasource}
/>
)}
{query.metricEditorMode === MetricEditorMode.Builder && (
<>
<SQLBuilderEditor
query={query}
onChange={this.props.onChange}
onRunQuery={onRunQuery}
datasource={datasource}
></SQLBuilderEditor>
</>
)}
</>
)}
<Space v={0.5} />
<EditorRow>
<EditorField
label="ID"
width={26}
optional
tooltip="ID can be used to reference other queries in math expressions. The ID can include numbers, letters, and underscore, and must start with a lowercase letter."
>
<Input
onBlur={onRunQuery}
onChange={(event: ChangeEvent<HTMLInputElement>) =>
this.onChange({ ...metricsQuery, id: event.target.value })
}
type="text"
invalid={!!query.id && !/^$|^[a-z][a-zA-Z0-9_]*$/.test(query.id)}
value={query.id}
/>
</EditorField>
<EditorField label="Period" width={26} tooltip="Minimum interval between points in seconds.">
<Input
value={query.period || ''}
placeholder="auto"
onBlur={onRunQuery}
onChange={(event: ChangeEvent<HTMLInputElement>) =>
this.onChange({ ...metricsQuery, period: event.target.value })
}
/>
</EditorField>
<EditorField
label="Alias"
width={26}
optional
tooltip="Change time series legend name using this field. See documentation for replacement variable formats."
>
<Alias
value={metricsQuery.alias ?? ''}
onChange={(value: string) => this.onChange({ ...metricsQuery, alias: value })}
/>
</EditorField>
</EditorRow>
</>
);
}
}
| public/app/plugins/datasource/cloudwatch/components/MetricsQueryEditor.tsx | 1 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.6833392977714539,
0.044039465487003326,
0.00016907555982470512,
0.0005971245118416846,
0.15199579298496246
] |
{
"id": 8,
"code_window": [
"\n",
" <InlineSelect\n",
" value={metricEditorModes.find((m) => m.value === metricQueryType)}\n",
" options={metricEditorModes}\n",
" onChange={({ value }) => {\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Metric editor mode\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/QueryHeader.tsx",
"type": "add",
"edit_start_line_idx": 87
} | import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { DataSourceApi } from '@grafana/data';
import { Props, QueryVariableEditorUnConnected } from './QueryVariableEditor';
import { initialQueryVariableModelState } from './reducer';
import { initialVariableEditorState } from '../editor/reducer';
import { describe, expect } from '../../../../test/lib/common';
import { NEW_VARIABLE_ID } from '../state/types';
import { LegacyVariableQueryEditor } from '../editor/LegacyVariableQueryEditor';
import { mockDataSource } from 'app/features/alerting/unified/mocks';
import { DataSourceType } from 'app/features/alerting/unified/utils/datasource';
const setupTestContext = (options: Partial<Props>) => {
const defaults: Props = {
variable: { ...initialQueryVariableModelState },
initQueryVariableEditor: jest.fn(),
changeQueryVariableDataSource: jest.fn(),
changeQueryVariableQuery: jest.fn(),
changeVariableMultiValue: jest.fn(),
editor: {
...initialVariableEditorState,
extended: {
VariableQueryEditor: LegacyVariableQueryEditor,
dataSource: ({} as unknown) as DataSourceApi,
},
},
onPropChange: jest.fn(),
};
const props: Props & Record<string, any> = { ...defaults, ...options };
const { rerender } = render(<QueryVariableEditorUnConnected {...props} />);
return { rerender, props };
};
const mockDS = mockDataSource({
name: 'CloudManager',
type: DataSourceType.Alertmanager,
});
jest.mock('@grafana/runtime/src/services/dataSourceSrv', () => {
return {
getDataSourceSrv: () => ({
get: () => Promise.resolve(mockDS),
getList: () => [mockDS],
getInstanceSettings: () => mockDS,
}),
};
});
describe('QueryVariableEditor', () => {
describe('when the component is mounted', () => {
it('then it should call initQueryVariableEditor', () => {
const { props } = setupTestContext({});
expect(props.initQueryVariableEditor).toHaveBeenCalledTimes(1);
expect(props.initQueryVariableEditor).toHaveBeenCalledWith({ type: 'query', id: NEW_VARIABLE_ID });
});
});
describe('when the user changes', () => {
it.each`
fieldName | propName | expectedArgs
${'query'} | ${'changeQueryVariableQuery'} | ${[{ type: 'query', id: NEW_VARIABLE_ID }, 't', 't']}
${'regex'} | ${'onPropChange'} | ${[{ propName: 'regex', propValue: 't', updateOptions: true }]}
`(
'$fieldName field and tabs away then $propName should be called with correct args',
({ fieldName, propName, expectedArgs }) => {
const { props } = setupTestContext({});
const propUnderTest = props[propName];
const fieldAccessor = fieldAccessors[fieldName];
userEvent.type(fieldAccessor(), 't');
userEvent.tab();
expect(propUnderTest).toHaveBeenCalledTimes(1);
expect(propUnderTest).toHaveBeenCalledWith(...expectedArgs);
}
);
});
describe('when the user changes', () => {
it.each`
fieldName | propName
${'query'} | ${'changeQueryVariableQuery'}
${'regex'} | ${'onPropChange'}
`(
'$fieldName field but reverts the change and tabs away then $propName should not be called',
({ fieldName, propName }) => {
const { props } = setupTestContext({});
const propUnderTest = props[propName];
const fieldAccessor = fieldAccessors[fieldName];
userEvent.type(fieldAccessor(), 't');
userEvent.type(fieldAccessor(), '{backspace}');
userEvent.tab();
expect(propUnderTest).not.toHaveBeenCalled();
}
);
});
});
const getQueryField = () =>
screen.getByRole('textbox', { name: /variable editor form default variable query editor textarea/i });
const getRegExField = () => screen.getByRole('textbox', { name: /variable editor form query regex field/i });
const fieldAccessors: Record<string, () => HTMLElement> = {
query: getQueryField,
regex: getRegExField,
};
| public/app/features/variables/query/QueryVariableEditor.test.tsx | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.00040861047455109656,
0.00019829657685477287,
0.0001651411730563268,
0.0001701328728813678,
0.00006961879989830777
] |
{
"id": 8,
"code_window": [
"\n",
" <InlineSelect\n",
" value={metricEditorModes.find((m) => m.value === metricQueryType)}\n",
" options={metricEditorModes}\n",
" onChange={({ value }) => {\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Metric editor mode\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/QueryHeader.tsx",
"type": "add",
"edit_start_line_idx": 87
} | import { DataQueryError } from '@grafana/data';
/**
* Convert an object into a DataQueryError -- if this is an HTTP response,
* it will put the correct values in the error field
*
* @public
*/
export function toDataQueryError(err: DataQueryError | string | Object): DataQueryError {
const error = (err || {}) as DataQueryError;
if (!error.message) {
if (typeof err === 'string' || err instanceof String) {
return { message: err } as DataQueryError;
}
let message = 'Query error';
if (error.message) {
message = error.message;
} else if (error.data && error.data.message) {
message = error.data.message;
} else if (error.data && error.data.error) {
message = error.data.error;
} else if (error.status) {
message = `Query error: ${error.status} ${error.statusText}`;
}
error.message = message;
}
return error;
}
| packages/grafana-runtime/src/utils/toDataQueryError.ts | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.00036764791002497077,
0.00023714479175396264,
0.00017689164087641984,
0.00020201984443701804,
0.00007749238284304738
] |
{
"id": 8,
"code_window": [
"\n",
" <InlineSelect\n",
" value={metricEditorModes.find((m) => m.value === metricQueryType)}\n",
" options={metricEditorModes}\n",
" onChange={({ value }) => {\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" aria-label=\"Metric editor mode\"\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/components/QueryHeader.tsx",
"type": "add",
"edit_start_line_idx": 87
} | <?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 19.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.0" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="100px" height="100px" viewBox="692 0 100 100" style="enable-background:new 692 0 100 100;" xml:space="preserve">
<style type="text/css">
.st0{fill:#787878;}
</style>
<g>
<path class="st0" d="M780.9,44.8c-3.2,0-5.9,2.1-6.7,5h-18.6c-0.2-1.6-0.6-3.1-1.2-4.6l12.5-7.2c1.5,1.6,3.6,2.5,5.9,2.5
c4.5,0,8.2-3.7,8.2-8.2s-3.7-8.2-8.2-8.2s-8.2,3.7-8.2,8.2c0,0.8,0.1,1.5,0.3,2.3l-12.5,7.2c-0.9-1.3-2.1-2.4-3.3-3.3l2.3-4.1
c0.8,0.2,1.5,0.3,2.4,0.3c4.6,0,8.4-3.8,8.4-8.4s-3.8-8.4-8.4-8.4c-4.6,0-8.4,3.8-8.4,8.4c0,2.4,1,4.6,2.6,6.1l-2.3,4
c-1.4-0.6-3-1-4.6-1.2V12c2.4-0.8,4.2-3.1,4.2-5.8c0-3.4-2.8-6.2-6.2-6.2c-3.4,0-6.2,2.8-6.2,6.2c0,2.7,1.8,5,4.2,5.8v23.3
c-1.6,0.2-3.1,0.6-4.6,1.2l-8.3-14.3c1.1-1.2,1.8-2.8,1.8-4.6c0-3.8-3.1-6.8-6.8-6.8c-3.7,0-6.8,3.1-6.8,6.8s3.1,6.8,6.8,6.8
c0.5,0,1-0.1,1.5-0.2l8.2,14.3c-1.3,1-2.4,2.1-3.4,3.4l-14.3-8.2c0.1-0.5,0.2-1,0.2-1.6c0-3.8-3.1-6.8-6.8-6.8
c-3.7,0-6.8,3.1-6.8,6.8c0,3.8,3.1,6.8,6.8,6.8c1.8,0,3.4-0.7,4.6-1.8l14.3,8.2c-0.6,1.4-1,2.9-1.2,4.5h-5.6
c-0.9-4.1-4.6-7.3-9-7.3c-5.1,0-9.2,4.1-9.2,9.2s4.1,9.2,9.2,9.2c4.4,0,8.1-3.1,9-7.2h5.6c0.2,1.6,0.6,3.1,1.2,4.6l-15.3,8.8
c-1.3-1.3-3.1-2.1-5.1-2.1c-4,0-7.3,3.3-7.3,7.3c0,4,3.3,7.3,7.3,7.3c4,0,7.3-3.3,7.3-7.3c0-0.6-0.1-1.2-0.2-1.8l15.3-8.8
c1,1.3,2.1,2.4,3.4,3.4L717.2,86c-0.5-0.1-1.1-0.2-1.7-0.2c-3.9,0-7.1,3.2-7.1,7.1c0,3.9,3.2,7.1,7.1,7.1s7.1-3.2,7.1-7.1
c0-1.9-0.8-3.7-2-5l11.9-20.7c1.4,0.6,2.9,1,4.5,1.2V74c-3.6,0.9-6.2,4.1-6.2,8c0,4.5,3.7,8.2,8.2,8.2s8.2-3.7,8.2-8.2
c0-3.8-2.7-7.1-6.2-8v-5.6c1.6-0.2,3.1-0.6,4.6-1.2l9.8,17c-1.3,1.3-2.1,3.1-2.1,5.1c0,4,3.3,7.3,7.3,7.3c4,0,7.3-3.3,7.3-7.3
s-3.3-7.3-7.3-7.3c-0.6,0-1.2,0.1-1.8,0.2L749,65.2c1.3-0.9,2.4-2,3.3-3.3l1.8,1c-0.3,0.9-0.5,1.9-0.5,2.9c0,5.3,4.3,9.6,9.6,9.6
s9.6-4.3,9.6-9.6c0-5.3-4.3-9.6-9.6-9.6c-2.8,0-5.3,1.2-7.1,3.2l-1.8-1c0.6-1.4,1-3,1.2-4.6h18.6c0.9,2.9,3.6,5,6.7,5
c3.9,0,7-3.1,7-7C788,48,784.8,44.8,780.9,44.8z M780.9,55.7c-2.1,0-3.8-1.7-3.8-3.8c0-2.1,1.7-3.8,3.8-3.8c2.1,0,3.8,1.7,3.8,3.8
C784.8,54,783.1,55.7,780.9,55.7z M739.1,64.6c-7,0-12.7-5.7-12.7-12.7s5.7-12.7,12.7-12.7s12.7,5.7,12.7,12.7
S746.1,64.6,739.1,64.6z M767.7,32.4c0-2.8,2.3-5,5-5c2.8,0,5,2.3,5,5s-2.3,5-5,5C770,37.4,767.7,35.2,767.7,32.4z M759,26.4
c0,2.9-2.4,5.3-5.3,5.3c-2.9,0-5.3-2.4-5.3-5.3s2.4-5.3,5.3-5.3C756.6,21.1,759,23.5,759,26.4z M736,6.2c0-1.7,1.3-3,3-3
c1.7,0,3,1.3,3,3c0,1.7-1.3,3-3,3C737.4,9.2,736,7.8,736,6.2z M715.6,17.6c0-2,1.6-3.6,3.6-3.6c2,0,3.6,1.6,3.6,3.6
c0,2-1.6,3.6-3.6,3.6C717.3,21.3,715.6,19.6,715.6,17.6z M704.8,35.7c-2,0-3.6-1.6-3.6-3.6c0-2,1.6-3.6,3.6-3.6s3.6,1.6,3.6,3.6
C708.5,34.1,706.8,35.7,704.8,35.7z M707.9,57.8c-3.3,0-6-2.7-6-6c0-3.3,2.7-6,6-6c3.3,0,6,2.7,6,6
C713.9,55.1,711.2,57.8,707.9,57.8z M707.5,72.4c0,2.3-1.9,4.1-4.1,4.1s-4.1-1.9-4.1-4.1c0-2.3,1.9-4.1,4.1-4.1
S707.5,70.2,707.5,72.4z M719.4,92.9c0,2.2-1.8,3.9-3.9,3.9c-2.2,0-3.9-1.8-3.9-3.9s1.8-3.9,3.9-3.9
C717.7,88.9,719.4,90.7,719.4,92.9z M739.1,87c-2.8,0-5-2.3-5-5s2.3-5,5-5c2.8,0,5,2.3,5,5S741.8,87,739.1,87z M764.8,89.3
c0,2.3-1.9,4.1-4.1,4.1c-2.3,0-4.1-1.9-4.1-4.1s1.9-4.1,4.1-4.1C762.9,85.2,764.8,87,764.8,89.3z M763.2,59.5
c3.5,0,6.4,2.9,6.4,6.4s-2.9,6.4-6.4,6.4c-3.5,0-6.4-2.9-6.4-6.4S759.7,59.5,763.2,59.5z"/>
</g>
</svg>
| public/img/icn-app.svg | 0 | https://github.com/grafana/grafana/commit/ba58b34219739aada59dd8853d4cb9cf640eae8f | [
0.00021986194769851863,
0.00018060338334180415,
0.00016429711831733584,
0.00016912721912376583,
0.00002294455043738708
] |
{
"id": 0,
"code_window": [
"import React, { PureComponent } from 'react';\n",
"import Paper from '@material-ui/core/Paper';\n",
"\n",
"// Make sure that for using static pickers you use path imports\n"
],
"labels": [
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export default `import React, { PureComponent } from 'react';\n"
],
"file_path": "docs/src/Examples/CodeSnippets/StaticPickers.jsx",
"type": "replace",
"edit_start_line_idx": 0
} | import withStyles, { WithStyles } from '@material-ui/core/styles/withStyles';
import keycode from 'keycode';
import * as PropTypes from 'prop-types';
import * as React from 'react';
import EventListener from 'react-event-listener';
import { Theme } from '@material-ui/core';
import { IconButtonProps } from '@material-ui/core/IconButton';
import { findClosestEnabledDate } from '../../_helpers/date-utils';
import { withUtils, WithUtilsProps } from '../../_shared/WithUtils';
import DomainPropTypes, { DateType } from '../../constants/prop-types';
import { MaterialUiPickersDate } from '../../typings/date';
import CalendarHeader from './CalendarHeader';
import Day from './Day';
import DayWrapper from './DayWrapper';
import SlideTransition, { SlideDirection } from './SlideTransition';
export type DayComponent = React.ReactElement<IconButtonProps>;
export type RenderDay = (
day: MaterialUiPickersDate,
selectedDate: MaterialUiPickersDate,
dayInCurrentMonth: boolean,
dayComponent: DayComponent
) => JSX.Element;
export interface CalendarProps
extends WithUtilsProps,
WithStyles<typeof styles, true> {
date: MaterialUiPickersDate;
minDate: DateType;
maxDate: DateType;
onChange: (date: MaterialUiPickersDate, isFinish?: boolean) => void;
disablePast?: boolean;
disableFuture?: boolean;
leftArrowIcon?: React.ReactNode;
rightArrowIcon?: React.ReactNode;
renderDay?: RenderDay;
allowKeyboardControl?: boolean;
shouldDisableDate?: (day: MaterialUiPickersDate) => boolean;
}
export interface CalendarState {
slideDirection: SlideDirection;
currentMonth: MaterialUiPickersDate;
lastDate?: MaterialUiPickersDate;
}
export class Calendar extends React.Component<CalendarProps, CalendarState> {
public static propTypes: any = {
date: PropTypes.object.isRequired,
minDate: DomainPropTypes.date,
maxDate: DomainPropTypes.date,
classes: PropTypes.object.isRequired,
onChange: PropTypes.func.isRequired,
disablePast: PropTypes.bool,
disableFuture: PropTypes.bool,
leftArrowIcon: PropTypes.node,
rightArrowIcon: PropTypes.node,
renderDay: PropTypes.func,
theme: PropTypes.object.isRequired,
shouldDisableDate: PropTypes.func,
utils: PropTypes.object.isRequired,
allowKeyboardControl: PropTypes.bool,
innerRef: PropTypes.any,
};
public static defaultProps = {
minDate: '1900-01-01',
maxDate: '2100-01-01',
disablePast: false,
disableFuture: false,
leftArrowIcon: undefined,
rightArrowIcon: undefined,
renderDay: undefined,
allowKeyboardControl: false,
shouldDisableDate: () => false,
};
public static getDerivedStateFromProps(
nextProps: CalendarProps,
state: CalendarState
) {
if (!nextProps.utils.isEqual(nextProps.date, state.lastDate)) {
return {
lastDate: nextProps.date,
currentMonth: nextProps.utils.getStartOfMonth(nextProps.date),
};
}
return null;
}
public state: CalendarState = {
slideDirection: 'left',
currentMonth: this.props.utils.getStartOfMonth(this.props.date),
};
public componentDidMount() {
const {
date,
minDate,
maxDate,
utils,
disableFuture,
disablePast,
} = this.props;
if (this.shouldDisableDate(date)) {
this.onDateSelect(
findClosestEnabledDate({
date,
utils,
minDate,
maxDate,
disablePast: Boolean(disablePast),
disableFuture: Boolean(disablePast),
shouldDisableDate: this.shouldDisableDate,
}),
false
);
}
}
public onDateSelect = (day: MaterialUiPickersDate, isFinish = true) => {
const { date, utils } = this.props;
this.props.onChange(utils.mergeDateAndTime(day, date), isFinish);
};
public handleChangeMonth = (
newMonth: MaterialUiPickersDate,
slideDirection: SlideDirection
) => {
this.setState({ currentMonth: newMonth, slideDirection });
};
public validateMinMaxDate = (day: MaterialUiPickersDate) => {
const { minDate, maxDate, utils } = this.props;
return (
(minDate && utils.isBeforeDay(day, utils.date(minDate))) ||
(maxDate && utils.isAfterDay(day, utils.date(maxDate)))
);
};
public shouldDisablePrevMonth = () => {
const { utils, disablePast, minDate } = this.props;
const now = utils.date();
return !utils.isBefore(
utils.getStartOfMonth(
disablePast && utils.isAfter(now, minDate) ? now : utils.date(minDate)
),
this.state.currentMonth
);
};
public shouldDisableNextMonth = () => {
const { utils, disableFuture, maxDate } = this.props;
const now = utils.date();
return !utils.isAfter(
utils.getStartOfMonth(
disableFuture && utils.isBefore(now, maxDate)
? now
: utils.date(maxDate)
),
this.state.currentMonth
);
};
public shouldDisableDate = (day: MaterialUiPickersDate) => {
const { disablePast, disableFuture, shouldDisableDate, utils } = this.props;
return Boolean(
(disableFuture && utils.isAfterDay(day, utils.date())) ||
(disablePast && utils.isBeforeDay(day, utils.date())) ||
this.validateMinMaxDate(day) ||
(shouldDisableDate && shouldDisableDate(day))
);
};
public moveToDay = (day: MaterialUiPickersDate) => {
if (day && !this.shouldDisableDate(day)) {
this.onDateSelect(day, false);
}
};
public handleKeyDown = (event: KeyboardEvent) => {
const { theme, date, utils } = this.props;
switch (keycode(event)) {
case 'up':
this.moveToDay(utils.addDays(date, -7));
break;
case 'down':
this.moveToDay(utils.addDays(date, 7));
break;
case 'left':
theme.direction === 'ltr'
? this.moveToDay(utils.addDays(date, -1))
: this.moveToDay(utils.addDays(date, 1));
break;
case 'right':
theme.direction === 'ltr'
? this.moveToDay(utils.addDays(date, 1))
: this.moveToDay(utils.addDays(date, -1));
break;
default:
// if keycode is not handled, stop execution
return;
}
// if event was handled prevent other side effects (e.g. page scroll)
event.preventDefault();
};
public renderWeeks = () => {
const { utils } = this.props;
const { currentMonth } = this.state;
const weeks = utils.getWeekArray(currentMonth);
return weeks.map(week => (
<div
key={`week-${week[0].toString()}`}
className={this.props.classes.week}
>
{this.renderDays(week)}
</div>
));
};
public renderDays = (week: MaterialUiPickersDate[]) => {
const { date, renderDay, utils } = this.props;
const selectedDate = utils.startOfDay(date);
const currentMonthNumber = utils.getMonth(this.state.currentMonth);
const now = utils.date();
return week.map(day => {
const disabled = this.shouldDisableDate(day);
const dayInCurrentMonth = utils.getMonth(day) === currentMonthNumber;
let dayComponent = (
<Day
current={utils.isSameDay(day, now)}
hidden={!dayInCurrentMonth}
disabled={disabled}
selected={utils.isSameDay(selectedDate, day)}
>
{utils.getDayText(day)}
</Day>
);
if (renderDay) {
dayComponent = renderDay(
day,
selectedDate,
dayInCurrentMonth,
dayComponent
);
}
return (
<DayWrapper
key={day.toString()}
value={day}
dayInCurrentMonth={dayInCurrentMonth}
disabled={disabled}
onSelect={this.onDateSelect}
>
{dayComponent}
</DayWrapper>
);
});
};
public render() {
const { currentMonth, slideDirection } = this.state;
const { classes, utils, allowKeyboardControl } = this.props;
return (
<React.Fragment>
{allowKeyboardControl && (
<EventListener target="window" onKeyDown={this.handleKeyDown} />
)}
<CalendarHeader
slideDirection={slideDirection}
currentMonth={currentMonth}
onMonthChange={this.handleChangeMonth}
leftArrowIcon={this.props.leftArrowIcon}
rightArrowIcon={this.props.rightArrowIcon}
disablePrevMonth={this.shouldDisablePrevMonth()}
disableNextMonth={this.shouldDisableNextMonth()}
/>
<SlideTransition
slideDirection={slideDirection}
transKey={currentMonth.toString()}
className={classes.transitionContainer}
>
<div
// @ts-ignore Autofocus required for getting work keyboard navigation feature
autoFocus
>
{this.renderWeeks()}
</div>
</SlideTransition>
</React.Fragment>
);
}
}
const styles = (theme: Theme) => ({
transitionContainer: {
minHeight: 36 * 6,
marginTop: theme.spacing.unit * 1.5,
},
week: {
display: 'flex',
justifyContent: 'center',
},
});
export default withStyles(styles, {
name: 'MuiPickersCalendar',
withTheme: true,
})(withUtils()(Calendar));
| lib/src/DatePicker/components/Calendar.tsx | 1 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00017723826749715954,
0.00017057755030691624,
0.00016442326887045056,
0.00017031468451023102,
0.0000030628150398115395
] |
{
"id": 0,
"code_window": [
"import React, { PureComponent } from 'react';\n",
"import Paper from '@material-ui/core/Paper';\n",
"\n",
"// Make sure that for using static pickers you use path imports\n"
],
"labels": [
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export default `import React, { PureComponent } from 'react';\n"
],
"file_path": "docs/src/Examples/CodeSnippets/StaticPickers.jsx",
"type": "replace",
"edit_start_line_idx": 0
} | import { Theme } from '@material-ui/core';
import IconButton from '@material-ui/core/IconButton';
import createStyles from '@material-ui/core/styles/createStyles';
import withStyles, { WithStyles } from '@material-ui/core/styles/withStyles';
import classnames from 'classnames';
import * as PropTypes from 'prop-types';
import * as React from 'react';
export interface DayProps extends WithStyles<typeof styles> {
children: React.ReactNode;
current?: boolean;
disabled?: boolean;
hidden?: boolean;
selected?: boolean;
}
class Day extends React.PureComponent<DayProps> {
public static propTypes: any = {
children: PropTypes.node.isRequired,
classes: PropTypes.object.isRequired,
current: PropTypes.bool,
disabled: PropTypes.bool,
hidden: PropTypes.bool,
selected: PropTypes.bool,
innerRef: PropTypes.any,
};
public static defaultProps = {
disabled: false,
hidden: false,
current: false,
selected: false,
};
public render() {
const {
children,
classes,
disabled,
hidden,
current,
selected,
...other
} = this.props;
const className = classnames(classes.day, {
[classes.hidden]: hidden,
[classes.current]: current,
[classes.selected]: selected,
[classes.disabled]: disabled,
});
return (
<IconButton
className={className}
tabIndex={hidden || disabled ? -1 : 0}
{...other}
>
{children}
</IconButton>
);
}
}
const styles = (theme: Theme) =>
createStyles({
day: {
width: 36,
height: 36,
fontSize: theme.typography.caption.fontSize,
margin: '0 2px',
color: theme.palette.text.primary,
fontWeight: theme.typography.fontWeightMedium,
padding: 0,
},
hidden: {
opacity: 0,
pointerEvents: 'none',
},
current: {
color: theme.palette.primary.main,
fontWeight: 600,
},
selected: {
color: theme.palette.common.white,
backgroundColor: theme.palette.primary.main,
fontWeight: theme.typography.fontWeightMedium,
'&:hover': {
backgroundColor: theme.palette.primary.main,
},
},
disabled: {
pointerEvents: 'none',
color: theme.palette.text.hint,
},
});
export default withStyles(styles, { name: 'MuiPickersDay' })(
Day as React.ComponentType<DayProps>
);
| lib/src/DatePicker/components/Day.tsx | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.000191139304661192,
0.00017503835260868073,
0.0001685783063294366,
0.00017226938507519662,
0.000006228052370715886
] |
{
"id": 0,
"code_window": [
"import React, { PureComponent } from 'react';\n",
"import Paper from '@material-ui/core/Paper';\n",
"\n",
"// Make sure that for using static pickers you use path imports\n"
],
"labels": [
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export default `import React, { PureComponent } from 'react';\n"
],
"file_path": "docs/src/Examples/CodeSnippets/StaticPickers.jsx",
"type": "replace",
"edit_start_line_idx": 0
} | .text-light {
font-weight: 200 !important;
}
.title {
margin-top: 20px !important;
}
main {
margin-top: 55px;
}
@media (min-width: 600px) {
main {
margin-top: 64px;
}
}
.material-ui-logo {
width: 100%;
height: 40vw;
max-height: 230px;
}
.picker {
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
margin-bottom: 40px;
margin: 10px 40px 40px;
}
@media (max-width: 600px) {
.picker {
flex-basis: 100%;
}
}
| docs/src/Pages/Landing/Landing.css | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00017734544235281646,
0.00017338668112643063,
0.00016934436280280352,
0.00017342845967505127,
0.000002875508698707563
] |
{
"id": 0,
"code_window": [
"import React, { PureComponent } from 'react';\n",
"import Paper from '@material-ui/core/Paper';\n",
"\n",
"// Make sure that for using static pickers you use path imports\n"
],
"labels": [
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export default `import React, { PureComponent } from 'react';\n"
],
"file_path": "docs/src/Examples/CodeSnippets/StaticPickers.jsx",
"type": "replace",
"edit_start_line_idx": 0
} | import React, { PureComponent, Fragment } from 'react';
import { DateTimePicker } from 'material-ui-pickers';
import { IconButton, Icon, InputAdornment } from '@material-ui/core';
export default class CustomDateTimePicker extends PureComponent {
state = {
selectedDate: new Date('2018-01-01T18:54'),
clearedDate: null,
}
handleDateChange = (date) => {
this.setState({ selectedDate: date });
}
handleClearedDateChange = (date) => {
this.setState({ clearedDate: date });
}
render() {
const { selectedDate, clearedDate } = this.state;
return (
<Fragment>
<div className="picker">
<DateTimePicker
autoOk
ampm={false}
showTabs={false}
autoSubmit={false}
allowKeyboardControl={false}
disableFuture
value={selectedDate}
onChange={this.handleDateChange}
helperText="Hardcoded helper text"
leftArrowIcon={<Icon> add_alarm </Icon>}
rightArrowIcon={<Icon> snooze </Icon>}
InputProps={{
endAdornment: (
<InputAdornment position="end">
<IconButton>
<Icon>add_alarm</Icon>
</IconButton>
</InputAdornment>
),
}}
/>
</div>
<div className="picker">
<DateTimePicker
keyboard
label="Keyboard with error handler"
onError={console.log}
minDate={new Date('2018-01-01T00:00')}
value={selectedDate}
onChange={this.handleDateChange}
format="yyyy/MM/dd hh:mm A"
disableOpenOnEnter
mask={[/\d/, /\d/, /\d/, /\d/, '/', /\d/, /\d/, '/', /\d/, /\d/, ' ', /\d/, /\d/, ':', /\d/, /\d/, ' ', /a|p/i, 'M']}
/>
</div>
<div className="picker">
<DateTimePicker
value={clearedDate}
onChange={this.handleClearedDateChange}
helperText="Clear Initial State"
clearable
/>
</div>
</Fragment>
);
}
}
| docs/src/Examples/Demo/DateTimePicker/CustomDateTimePicker.jsx | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00020959749235771596,
0.0001771261595422402,
0.00016999214130919427,
0.00017185890465043485,
0.000012500855518737808
] |
{
"id": 1,
"code_window": [
" </MuiPickersUtilsProvider>\n",
" );\n",
" }\n",
"}\n",
"\n",
"export default StaticPickers;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace"
],
"after_edit": [
"export default StaticPickers;`;"
],
"file_path": "docs/src/Examples/CodeSnippets/StaticPickers.jsx",
"type": "replace",
"edit_start_line_idx": 57
} | {
"build/dist/material-ui-pickers.cjs.js": {
"bundled": 119585,
"minified": 72390,
"gzipped": 14601
},
"build/dist/material-ui-pickers.esm.js": {
"bundled": 114004,
"minified": 66935,
"gzipped": 14397,
"treeshaked": {
"rollup": {
"code": 49272,
"import_statements": 1245
},
"webpack": {
"code": 56057
}
}
},
"build/dist/material-ui-pickers.umd.js": {
"bundled": 230045,
"minified": 100210,
"gzipped": 25280
},
"build/dist/material-ui-pickers.umd.min.js": {
"bundled": 200849,
"minified": 90120,
"gzipped": 23620
}
}
| lib/.size-snapshot.json | 1 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.0001940436050062999,
0.00018504021863918751,
0.00017281212785746902,
0.00018665257084649056,
0.0000091756492111017
] |
{
"id": 1,
"code_window": [
" </MuiPickersUtilsProvider>\n",
" );\n",
" }\n",
"}\n",
"\n",
"export default StaticPickers;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace"
],
"after_edit": [
"export default StaticPickers;`;"
],
"file_path": "docs/src/Examples/CodeSnippets/StaticPickers.jsx",
"type": "replace",
"edit_start_line_idx": 57
} | import { ReactWrapper } from 'enzyme';
import * as React from 'react';
import TimePicker, { TimePickerProps } from '../../TimePicker/TimePicker';
import { mount, utilsToUse } from '../test-utils';
describe('e2e - TimePicker', () => {
let component: ReactWrapper<TimePickerProps>;
const onChangeMock = jest.fn();
beforeEach(() => {
jest.clearAllMocks();
component = mount(
<TimePicker
date={utilsToUse.date('2018-01-01T00:00:00.000Z')}
onChange={onChangeMock}
/>
);
});
it('Should renders', () => {
expect(component).toBeTruthy();
});
it('Should submit onChange on moving', () => {
component.find('Clock div[role="menu"]').simulate('mouseMove', {
buttons: 1,
nativeEvent: {
offsetX: 20,
offsetY: 15,
},
});
expect(onChangeMock).toHaveBeenCalled();
});
it('Should submit hourview (mouse move)', () => {
component.find('Clock div[role="menu"]').simulate('mouseUp', {
nativeEvent: {
offsetX: 20,
offsetY: 15,
},
});
expect(onChangeMock).toHaveBeenCalled();
});
it('Should change minutes (touch)', () => {
component.setState({ openView: 'minutes' });
component.find('Clock div[role="menu"]').simulate('touchMove', {
buttons: 1,
changedTouches: [
{
clientX: 20,
clientY: 15,
},
],
});
expect(onChangeMock).toHaveBeenCalled();
component.find('Clock div[role="menu"]').simulate('touchEnd', {
buttons: 1,
changedTouches: [
{
clientX: 20,
clientY: 15,
},
],
});
expect(onChangeMock).toHaveBeenCalled();
});
});
| lib/src/__tests__/e2e/TimePicker.test.tsx | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00017469353042542934,
0.00017179863061755896,
0.00016704622248653322,
0.00017226446652784944,
0.0000021950640984869096
] |
{
"id": 1,
"code_window": [
" </MuiPickersUtilsProvider>\n",
" );\n",
" }\n",
"}\n",
"\n",
"export default StaticPickers;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace"
],
"after_edit": [
"export default StaticPickers;`;"
],
"file_path": "docs/src/Examples/CodeSnippets/StaticPickers.jsx",
"type": "replace",
"edit_start_line_idx": 57
} | # Contributing
:raised_hands::tada: First off all, thanks for taking the time to contribute! :tada::raised_hands:
The following is a set of guidelines for contributing to material-ui-pickers. The purpose of these
guidelines is to maintain a high quality of code *and* traceability. Please respect these
guidelines.
## General
This repository use tests and a linter as automatic tools to maintain the quality of the code.
These two tasks are run locally on your machine before every commit (as a pre-commit git hook),
if any test fail or the linter gives an error the commit will not be created. They are also run on
a Travis CI machine when you create a pull request, and the PR will not be merged unless Travis
says all tests and the linting pass.
## Git Commit Messages
* Use the imperative mood ("Move pointer to..." not "Moves pointer to...")
* Think of it as you are *commanding* what your commit is doing
* Git itself uses the imperative whenever it creates a commit on your behalf, so it makes sense
for you to use it too
* Use the body to explain *what* and *why*
* If the commit is non-trivial, please provide more detailed information in the commit body
message
* *How* you made the change is visible in the code and is therefore rarely necessary to include
in the commit body message, but *why* you made the change is often harder to guess and is
therefore useful to include in the commit body message
[Here's a nice blog post on how to write great git messages.](http://chris.beams.io/posts/git-commit/)
## Pull Requests
* Follow the current code style
* Write tests for your changes
* Document your changes in the README if it's needed
* End files with a newline
* There's no need to create a new build for each pull request, we (the maintainers) do this when we
release a new version
## Issues
* Please be descriptive when you fill in the issue template, this will greatly help us maintainers
in helping you which will lead to your issue being resolved faster
* Feature requests are very welcomed, but not every feature that is requested can be guaranteed
to be implemented
| CONTRIBUTING.md | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00017655799456406385,
0.00017189826758112758,
0.00016878015594556928,
0.00017206024494953454,
0.000002662626002347679
] |
{
"id": 1,
"code_window": [
" </MuiPickersUtilsProvider>\n",
" );\n",
" }\n",
"}\n",
"\n",
"export default StaticPickers;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace"
],
"after_edit": [
"export default StaticPickers;`;"
],
"file_path": "docs/src/Examples/CodeSnippets/StaticPickers.jsx",
"type": "replace",
"edit_start_line_idx": 57
} | /* eslint-disable import/no-dynamic-require */
/* eslint-disable global-require */
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { Typography, IconButton, Icon, withStyles, Collapse } from '@material-ui/core';
import Code from './Code';
class SourcablePanel extends PureComponent {
static propTypes = {
classes: PropTypes.object.isRequired,
title: PropTypes.string.isRequired,
description: PropTypes.node,
sourceFile: PropTypes.string.isRequired,
}
static defaultProps = {
description: undefined,
}
state = {
sourceExpanded: false,
}
getSource = () => require(`!raw-loader!../Examples/${this.props.sourceFile}`)
getComponent = () => require(`../Examples/${this.props.sourceFile}`).default
toggleSource = () => {
this.setState({ sourceExpanded: !this.state.sourceExpanded });
}
render() {
const { sourceExpanded } = this.state;
const { classes, title, description } = this.props;
const Component = this.getComponent();
return (
<React.Fragment>
<Typography variant="h4" className={classes.exampleTitle}>
{ title }
</Typography>
{description}
<Collapse key="code" in={sourceExpanded}>
<Code className={classes.source} text={this.getSource()} />
</Collapse>
<div className={classes.pickers}>
<IconButton
className={classes.sourceBtn}
onClick={this.toggleSource}
>
<Icon>code</Icon>
</IconButton>
<Component />
</div>
</React.Fragment>
);
}
}
const styles = theme => ({
exampleTitle: {
marginTop: '40px',
marginBottom: '20px',
'@media(max-width: 600px)': {
marginLeft: 5,
},
},
pickers: {
display: 'flex',
justifyContent: 'center',
flexWrap: 'wrap',
minHeight: 160,
paddingTop: 40,
width: '100%',
margin: '0 auto 50px',
position: 'relative',
backgroundColor:
theme.palette.type === 'light' ? theme.palette.grey[200] : theme.palette.grey[900],
},
sourceBtn: {
position: 'absolute',
top: 10,
right: 5,
},
source: {
marginBottom: 0,
},
});
export default withStyles(styles)(SourcablePanel);
| docs/src/_shared/SourcablePanel.jsx | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.0002014352794503793,
0.00017720376490615308,
0.00016704270092304796,
0.00017132438370026648,
0.00001161186992248986
] |
{
"id": 2,
"code_window": [
"import Code from '_shared/Code';\n",
"import { Typography } from '@material-ui/core';\n",
"// eslint-disable-next-line\n",
"import StaticPickersCode from '!raw-loader!../../Examples/CodeSnippets/StaticPickers';\n",
"\n",
"const StaticPickers = () => (\n",
" <div>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import StaticPickersCode from 'Examples/CodeSnippets/StaticPickers';\n"
],
"file_path": "docs/src/Pages/Guides/StaticPickers.jsx",
"type": "replace",
"edit_start_line_idx": 4
} | import withStyles, { WithStyles } from '@material-ui/core/styles/withStyles';
import keycode from 'keycode';
import * as PropTypes from 'prop-types';
import * as React from 'react';
import EventListener from 'react-event-listener';
import { Theme } from '@material-ui/core';
import { IconButtonProps } from '@material-ui/core/IconButton';
import { findClosestEnabledDate } from '../../_helpers/date-utils';
import { withUtils, WithUtilsProps } from '../../_shared/WithUtils';
import DomainPropTypes, { DateType } from '../../constants/prop-types';
import { MaterialUiPickersDate } from '../../typings/date';
import CalendarHeader from './CalendarHeader';
import Day from './Day';
import DayWrapper from './DayWrapper';
import SlideTransition, { SlideDirection } from './SlideTransition';
export type DayComponent = React.ReactElement<IconButtonProps>;
export type RenderDay = (
day: MaterialUiPickersDate,
selectedDate: MaterialUiPickersDate,
dayInCurrentMonth: boolean,
dayComponent: DayComponent
) => JSX.Element;
export interface CalendarProps
extends WithUtilsProps,
WithStyles<typeof styles, true> {
date: MaterialUiPickersDate;
minDate: DateType;
maxDate: DateType;
onChange: (date: MaterialUiPickersDate, isFinish?: boolean) => void;
disablePast?: boolean;
disableFuture?: boolean;
leftArrowIcon?: React.ReactNode;
rightArrowIcon?: React.ReactNode;
renderDay?: RenderDay;
allowKeyboardControl?: boolean;
shouldDisableDate?: (day: MaterialUiPickersDate) => boolean;
}
export interface CalendarState {
slideDirection: SlideDirection;
currentMonth: MaterialUiPickersDate;
lastDate?: MaterialUiPickersDate;
}
export class Calendar extends React.Component<CalendarProps, CalendarState> {
public static propTypes: any = {
date: PropTypes.object.isRequired,
minDate: DomainPropTypes.date,
maxDate: DomainPropTypes.date,
classes: PropTypes.object.isRequired,
onChange: PropTypes.func.isRequired,
disablePast: PropTypes.bool,
disableFuture: PropTypes.bool,
leftArrowIcon: PropTypes.node,
rightArrowIcon: PropTypes.node,
renderDay: PropTypes.func,
theme: PropTypes.object.isRequired,
shouldDisableDate: PropTypes.func,
utils: PropTypes.object.isRequired,
allowKeyboardControl: PropTypes.bool,
innerRef: PropTypes.any,
};
public static defaultProps = {
minDate: '1900-01-01',
maxDate: '2100-01-01',
disablePast: false,
disableFuture: false,
leftArrowIcon: undefined,
rightArrowIcon: undefined,
renderDay: undefined,
allowKeyboardControl: false,
shouldDisableDate: () => false,
};
public static getDerivedStateFromProps(
nextProps: CalendarProps,
state: CalendarState
) {
if (!nextProps.utils.isEqual(nextProps.date, state.lastDate)) {
return {
lastDate: nextProps.date,
currentMonth: nextProps.utils.getStartOfMonth(nextProps.date),
};
}
return null;
}
public state: CalendarState = {
slideDirection: 'left',
currentMonth: this.props.utils.getStartOfMonth(this.props.date),
};
public componentDidMount() {
const {
date,
minDate,
maxDate,
utils,
disableFuture,
disablePast,
} = this.props;
if (this.shouldDisableDate(date)) {
this.onDateSelect(
findClosestEnabledDate({
date,
utils,
minDate,
maxDate,
disablePast: Boolean(disablePast),
disableFuture: Boolean(disablePast),
shouldDisableDate: this.shouldDisableDate,
}),
false
);
}
}
public onDateSelect = (day: MaterialUiPickersDate, isFinish = true) => {
const { date, utils } = this.props;
this.props.onChange(utils.mergeDateAndTime(day, date), isFinish);
};
public handleChangeMonth = (
newMonth: MaterialUiPickersDate,
slideDirection: SlideDirection
) => {
this.setState({ currentMonth: newMonth, slideDirection });
};
public validateMinMaxDate = (day: MaterialUiPickersDate) => {
const { minDate, maxDate, utils } = this.props;
return (
(minDate && utils.isBeforeDay(day, utils.date(minDate))) ||
(maxDate && utils.isAfterDay(day, utils.date(maxDate)))
);
};
public shouldDisablePrevMonth = () => {
const { utils, disablePast, minDate } = this.props;
const now = utils.date();
return !utils.isBefore(
utils.getStartOfMonth(
disablePast && utils.isAfter(now, minDate) ? now : utils.date(minDate)
),
this.state.currentMonth
);
};
public shouldDisableNextMonth = () => {
const { utils, disableFuture, maxDate } = this.props;
const now = utils.date();
return !utils.isAfter(
utils.getStartOfMonth(
disableFuture && utils.isBefore(now, maxDate)
? now
: utils.date(maxDate)
),
this.state.currentMonth
);
};
public shouldDisableDate = (day: MaterialUiPickersDate) => {
const { disablePast, disableFuture, shouldDisableDate, utils } = this.props;
return Boolean(
(disableFuture && utils.isAfterDay(day, utils.date())) ||
(disablePast && utils.isBeforeDay(day, utils.date())) ||
this.validateMinMaxDate(day) ||
(shouldDisableDate && shouldDisableDate(day))
);
};
public moveToDay = (day: MaterialUiPickersDate) => {
if (day && !this.shouldDisableDate(day)) {
this.onDateSelect(day, false);
}
};
public handleKeyDown = (event: KeyboardEvent) => {
const { theme, date, utils } = this.props;
switch (keycode(event)) {
case 'up':
this.moveToDay(utils.addDays(date, -7));
break;
case 'down':
this.moveToDay(utils.addDays(date, 7));
break;
case 'left':
theme.direction === 'ltr'
? this.moveToDay(utils.addDays(date, -1))
: this.moveToDay(utils.addDays(date, 1));
break;
case 'right':
theme.direction === 'ltr'
? this.moveToDay(utils.addDays(date, 1))
: this.moveToDay(utils.addDays(date, -1));
break;
default:
// if keycode is not handled, stop execution
return;
}
// if event was handled prevent other side effects (e.g. page scroll)
event.preventDefault();
};
public renderWeeks = () => {
const { utils } = this.props;
const { currentMonth } = this.state;
const weeks = utils.getWeekArray(currentMonth);
return weeks.map(week => (
<div
key={`week-${week[0].toString()}`}
className={this.props.classes.week}
>
{this.renderDays(week)}
</div>
));
};
public renderDays = (week: MaterialUiPickersDate[]) => {
const { date, renderDay, utils } = this.props;
const selectedDate = utils.startOfDay(date);
const currentMonthNumber = utils.getMonth(this.state.currentMonth);
const now = utils.date();
return week.map(day => {
const disabled = this.shouldDisableDate(day);
const dayInCurrentMonth = utils.getMonth(day) === currentMonthNumber;
let dayComponent = (
<Day
current={utils.isSameDay(day, now)}
hidden={!dayInCurrentMonth}
disabled={disabled}
selected={utils.isSameDay(selectedDate, day)}
>
{utils.getDayText(day)}
</Day>
);
if (renderDay) {
dayComponent = renderDay(
day,
selectedDate,
dayInCurrentMonth,
dayComponent
);
}
return (
<DayWrapper
key={day.toString()}
value={day}
dayInCurrentMonth={dayInCurrentMonth}
disabled={disabled}
onSelect={this.onDateSelect}
>
{dayComponent}
</DayWrapper>
);
});
};
public render() {
const { currentMonth, slideDirection } = this.state;
const { classes, utils, allowKeyboardControl } = this.props;
return (
<React.Fragment>
{allowKeyboardControl && (
<EventListener target="window" onKeyDown={this.handleKeyDown} />
)}
<CalendarHeader
slideDirection={slideDirection}
currentMonth={currentMonth}
onMonthChange={this.handleChangeMonth}
leftArrowIcon={this.props.leftArrowIcon}
rightArrowIcon={this.props.rightArrowIcon}
disablePrevMonth={this.shouldDisablePrevMonth()}
disableNextMonth={this.shouldDisableNextMonth()}
/>
<SlideTransition
slideDirection={slideDirection}
transKey={currentMonth.toString()}
className={classes.transitionContainer}
>
<div
// @ts-ignore Autofocus required for getting work keyboard navigation feature
autoFocus
>
{this.renderWeeks()}
</div>
</SlideTransition>
</React.Fragment>
);
}
}
const styles = (theme: Theme) => ({
transitionContainer: {
minHeight: 36 * 6,
marginTop: theme.spacing.unit * 1.5,
},
week: {
display: 'flex',
justifyContent: 'center',
},
});
export default withStyles(styles, {
name: 'MuiPickersCalendar',
withTheme: true,
})(withUtils()(Calendar));
| lib/src/DatePicker/components/Calendar.tsx | 1 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00020619251881726086,
0.0001746421621646732,
0.00016234786016866565,
0.0001735054247546941,
0.000009225015674019232
] |
{
"id": 2,
"code_window": [
"import Code from '_shared/Code';\n",
"import { Typography } from '@material-ui/core';\n",
"// eslint-disable-next-line\n",
"import StaticPickersCode from '!raw-loader!../../Examples/CodeSnippets/StaticPickers';\n",
"\n",
"const StaticPickers = () => (\n",
" <div>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import StaticPickersCode from 'Examples/CodeSnippets/StaticPickers';\n"
],
"file_path": "docs/src/Pages/Guides/StaticPickers.jsx",
"type": "replace",
"edit_start_line_idx": 4
} | import React, { PureComponent } from 'react';
import { DatePicker } from 'material-ui-pickers';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core';
import lightBlue from '@material-ui/core/colors/lightBlue';
const materialTheme = createMuiTheme({
overrides: {
MuiPickersToolbar: {
toolbar: {
backgroundColor: lightBlue.A200,
},
},
MuiPickersCalendarHeader: {
switchHeader: {
// backgroundColor: lightBlue.A200,
// color: 'white',
},
},
MuiPickersDay: {
day: {
color: lightBlue.A700,
},
selected: {
backgroundColor: lightBlue['400'],
},
current: {
color: lightBlue['900'],
},
},
MuiPickersModal: {
dialogAction: {
color: lightBlue['400'],
},
},
},
});
export default class BasicDatePicker extends PureComponent {
state = {
selectedDate: new Date(),
}
handleDateChange = (date) => {
this.setState({ selectedDate: date });
}
render() {
const { selectedDate } = this.state;
return (
<MuiThemeProvider theme={materialTheme}>
<div className="picker">
<DatePicker
label="Light blue picker"
value={selectedDate}
onChange={this.handleDateChange}
animateYearScrolling={false}
/>
</div>
</MuiThemeProvider>
);
}
}
| docs/src/Examples/Guides/CssTheme.jsx | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.0002593990066088736,
0.0001894742454169318,
0.00017295735597144812,
0.00017755627050064504,
0.000028744303563144058
] |
{
"id": 2,
"code_window": [
"import Code from '_shared/Code';\n",
"import { Typography } from '@material-ui/core';\n",
"// eslint-disable-next-line\n",
"import StaticPickersCode from '!raw-loader!../../Examples/CodeSnippets/StaticPickers';\n",
"\n",
"const StaticPickers = () => (\n",
" <div>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import StaticPickersCode from 'Examples/CodeSnippets/StaticPickers';\n"
],
"file_path": "docs/src/Pages/Guides/StaticPickers.jsx",
"type": "replace",
"edit_start_line_idx": 4
} | <svg viewBox="0 0 600 476.6" xmlns="http://www.w3.org/2000/svg">
<path d="m0 259.8v-259.8l225 129.9v86.6l-150-86.6v173.2z" fill="#5C6BC0"/>
<path d="m225 129.9 225-129.9v259.8l-150 86.6-75-43.3 150-86.6v-86.6l-150 86.6z" fill="#303F9F"/>
<path d="m225 303.1v86.6l150 86.6v-86.6z" fill="#5C6BC0"/>
<path d="m375 476.3 225-129.9v-173.2l-75 43.3v86.6l-150 86.6zm150-346.4v-86.6l75-43.3v86.6z" fill="#303F9F"/>
</svg> | docs/src/assets/mui-logo.svg | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00017627404304221272,
0.00017627404304221272,
0.00017627404304221272,
0.00017627404304221272,
0
] |
{
"id": 2,
"code_window": [
"import Code from '_shared/Code';\n",
"import { Typography } from '@material-ui/core';\n",
"// eslint-disable-next-line\n",
"import StaticPickersCode from '!raw-loader!../../Examples/CodeSnippets/StaticPickers';\n",
"\n",
"const StaticPickers = () => (\n",
" <div>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import StaticPickersCode from 'Examples/CodeSnippets/StaticPickers';\n"
],
"file_path": "docs/src/Pages/Guides/StaticPickers.jsx",
"type": "replace",
"edit_start_line_idx": 4
} | import React, { Component } from 'react';
import classnames from 'classnames';
import PropTypes from 'prop-types';
import Hidden from '@material-ui/core/Hidden';
import Drawer from '@material-ui/core/Drawer';
import { withRouter } from 'react-router-dom';
import {
AppBar,
Toolbar,
IconButton,
Icon,
withStyles,
Tooltip,
} from '@material-ui/core';
import Github from '_shared/GithubIcon';
import DrawerMenu from './DrawerMenu';
class Layout extends Component {
static propTypes = {
classes: PropTypes.object.isRequired,
toggleThemeType: PropTypes.func.isRequired,
toggleDirection: PropTypes.func.isRequired,
toggleFrench: PropTypes.func.isRequired,
theme: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
children: PropTypes.element.isRequired,
};
state = {
drawerOpen: false,
};
handleDrawerToggle = () => {
this.setState({ drawerOpen: !this.state.drawerOpen });
};
scrollToContent = () => {
const contentEl = document.getElementById('content');
contentEl.scrollIntoView({
behavior: 'smooth',
block: 'start',
});
};
render() {
const {
classes,
toggleThemeType,
toggleDirection,
toggleFrench,
theme,
location,
} = this.props;
const isLanding = location.pathname === '/';
return (
<React.Fragment>
<AppBar
position="fixed"
className={classnames(classes.appBar, {
[classes.landingAppBar]: isLanding,
})}
>
<Toolbar>
<IconButton
className={classes.menuButton}
color="inherit"
aria-label="Menu"
onClick={this.handleDrawerToggle}
>
<Icon>menu</Icon>
</IconButton>
<div className={classes.flex} />
<Tooltip
title="Toggle English/French locale for pickers"
enterDelay={300}
>
<IconButton color="inherit" onClick={toggleFrench}>
<Icon>language</Icon>
</IconButton>
</Tooltip>
<Tooltip title="Toggle light/dark theme" enterDelay={300}>
<IconButton color="inherit" onClick={toggleThemeType}>
<Icon>lightbulb_outline</Icon>
</IconButton>
</Tooltip>
<Tooltip title="Toggle direction" enterDelay={300}>
<IconButton color="inherit" onClick={toggleDirection}>
<Icon>format_textdirection_l_to_r</Icon>
</IconButton>
</Tooltip>
<Tooltip title="Github" enterDelay={300}>
<IconButton
color="inherit"
component="a"
href="https://github.com/dmtrKovalenko/material-ui-pickers"
>
<Github color="inherit" />
</IconButton>
</Tooltip>
</Toolbar>
</AppBar>
<Hidden mdUp>
<Drawer
variant="temporary"
anchor={theme.direction === 'rtl' ? 'right' : 'left'}
open={this.state.drawerOpen}
onClose={this.handleDrawerToggle}
onClick={this.handleDrawerToggle}
classes={{
paper: classes.drawerPaper,
}}
ModalProps={{
keepMounted: true, // Better open performance on mobile.
}}
>
<DrawerMenu />
</Drawer>
</Hidden>
<Hidden smDown implementation="css">
<Drawer
variant={isLanding ? 'temporary' : 'permanent'}
open={this.state.drawerOpen}
onClose={this.handleDrawerToggle}
classes={{
paper: classes.drawerPaper,
}}
>
<DrawerMenu />
</Drawer>
</Hidden>
<main
className={classnames(classes.main, {
[classes.landingMain]: isLanding,
})}
>
<div
className={classnames(classes.content, {
[classes.landingMain]: isLanding,
})}
>
{this.props.children}
</div>
</main>
</React.Fragment>
);
}
}
const styles = theme => ({
'@global': {
body: {
backgroundColor: theme.palette.background.default,
},
},
flex: {
flex: 1,
},
menuButton: {
marginLeft: -12,
marginRight: 20,
},
appBar: {
// boxShadow: 'unset',
[theme.breakpoints.up('md')]: {
left: 250,
width: 'calc(100% - 250px)',
},
},
main: {
marginTop: 55,
padding: '20px',
minHeight: 'calc(100vh - 55px)',
[theme.breakpoints.up('md')]: {
marginTop: 64,
minHeight: 'calc(100vh - 64px)',
marginLeft: 250,
},
},
content: {
[theme.breakpoints.up('lg')]: {
maxWidth: 960,
margin: '0 auto',
},
},
landingMain: {
padding: 0,
maxWidth: '100vw',
marginLeft: 0,
},
landingAppBar: {
left: 0,
width: '100vw',
boxShadow: 'unset',
},
});
export default withStyles(styles, { withTheme: true })(withRouter(Layout));
| docs/src/layout/Layout.jsx | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00019568626885302365,
0.00017231414676643908,
0.00016255045193247497,
0.00017189086065627635,
0.000006396841399691766
] |
{
"id": 3,
"code_window": [
"{\n",
" \"build/dist/material-ui-pickers.cjs.js\": {\n",
" \"bundled\": 119585,\n",
" \"minified\": 72390,\n",
" \"gzipped\": 14601\n",
" },\n",
" \"build/dist/material-ui-pickers.esm.js\": {\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"bundled\": 119488,\n",
" \"minified\": 72333,\n",
" \"gzipped\": 14584\n"
],
"file_path": "lib/.size-snapshot.json",
"type": "replace",
"edit_start_line_idx": 2
} | import React from 'react';
import Code from '_shared/Code';
import { Typography } from '@material-ui/core';
// eslint-disable-next-line
import StaticPickersCode from '!raw-loader!../../Examples/CodeSnippets/StaticPickers';
const StaticPickers = () => (
<div>
<Typography variant="h2" gutterBottom>
{' '}
Static pickers{' '}
</Typography>
<Typography variant="body1" gutterBottom>
Somewhere its required to use some internal control for calendar or some
timeinput. Here you are! You can use directly any sub-control of the
pickers. Please note - if you want to use internal controls ALL your
imports must be from the relative paths
</Typography>
<Typography variant="body1" gutterBottom>
Also you can use our own HOC that is using for any picker which provide
managing temporary chosen date and submitting state logic.
</Typography>
<Code text={StaticPickersCode} />
</div>
);
export default StaticPickers;
| docs/src/Pages/Guides/StaticPickers.jsx | 1 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.0004458911716938019,
0.00025200581876561046,
0.0001655739761190489,
0.00019827904179692268,
0.00011464327690191567
] |
{
"id": 3,
"code_window": [
"{\n",
" \"build/dist/material-ui-pickers.cjs.js\": {\n",
" \"bundled\": 119585,\n",
" \"minified\": 72390,\n",
" \"gzipped\": 14601\n",
" },\n",
" \"build/dist/material-ui-pickers.esm.js\": {\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"bundled\": 119488,\n",
" \"minified\": 72333,\n",
" \"gzipped\": 14584\n"
],
"file_path": "lib/.size-snapshot.json",
"type": "replace",
"edit_start_line_idx": 2
} | {
"name": "material-ui-pickers",
"version": "1.0.1",
"private": true,
"description": "React components, that implements material design pickers for material-ui v1",
"main": "build/dist/material-ui-pickers.cjs.js",
"module": "build/dist/material-ui-pickers.esm.js",
"types": "index.d.ts",
"keywords": [
"material-ui",
"pickers",
"material-ui-pickers",
"datepicker",
"timepicker",
"date-picker",
"time-picker",
"react",
"react-component",
"material design"
],
"license": "MIT",
"bugs": {
"url": "https://github.com/dmtrKovalenko/material-ui-pickers/issues"
},
"homepage": "https://material-ui-pickers.firebaseapp.com/",
"repository": {
"type": "git",
"url": "https://github.com/dmtrKovalenko/material-ui-pickers"
},
"author": {
"name": "Dmitriy Kovalenko",
"email": "[email protected]"
},
"peerDependencies": {
"@material-ui/core": "^3.2.0",
"prop-types": "^15.6.0",
"react": "^16.3.0",
"react-dom": "^16.3.0"
},
"dependencies": {
"classnames": "^2.2.6",
"keycode": "^2.2.0",
"react-event-listener": "^0.6.4",
"react-text-mask": "=5.4.1",
"react-transition-group": "^2.5.0",
"tslib": "^1.9.3"
},
"size-limit": [
{
"path": "build/dist/material-ui-pickers.cjs.js",
"limit": "30 KB"
}
],
"scripts": {
"test": "jest",
"test:date-fns": "UTILS=date-fns npm run test",
"test:luxon": "UTILS=luxon npm run test",
"test:moment": "UTILS=moment npm run test",
"start": "rollup --config --watch",
"prebuild": "rimraf build",
"build:copy": "node copy.js",
"build:bundle": "rollup --config",
"build:typescript": "tsc --project tsconfig.json",
"build": "npm run build:typescript && npm run build:bundle && npm run build:copy",
"build:analyze": "npm run build && npx size-limit",
"release": "np --no-publish --any-branch",
"postrelease": "npm run build && npm publish build",
"lint": "tslint --project tsconfig.json",
"postinstall": "node -e \"console.log('\\u001b[35m\\u001b[1mHave you installed one of peer libraries?\\u001b[22m\\u001b[39m\\n > date-fns \\n > luxon \\n > moment')\""
},
"devDependencies": {
"@babel/core": "^7.1.2",
"@material-ui/core": "^3.2.1",
"@types/classnames": "^2.2.6",
"@types/enzyme": "^3.1.14",
"@types/enzyme-adapter-react-16": "^1.0.3",
"@types/fs-extra": "^5.0.4",
"@types/glob": "^7.1.1",
"@types/jest": "^23.3.5",
"@types/jss": "^9.5.6",
"@types/luxon": "^1.4.0",
"@types/moment": "^2.13.0",
"@types/prettier": "^1.13.2",
"@types/prop-types": "^15.5.6",
"@types/react": "^16.4.16",
"@types/react-dom": "^16.0.9",
"@types/react-event-listener": "^0.4.7",
"@types/react-text-mask": "^5.4.2",
"@types/react-transition-group": "^2.0.14",
"classnames": "^2.2.6",
"codecov": "^3.1.0",
"cross-env": "^5.2.0",
"date-fns": "2.0.0-alpha.16",
"enzyme": "^3.7.0",
"enzyme-adapter-react-16": "^1.6.0",
"fs-extra": "^7.0.0",
"full-icu": "^1.2.1",
"glob": "^7.1.3",
"jest": "^23.6.0",
"luxon": "^1.4.3",
"moment": "^2.22.2",
"np": "^3.0.4",
"prop-types": "^15.6.2",
"react": "^16.5.2",
"react-dom": "^16.5.2",
"rollup": "^0.66.6",
"rollup-plugin-babel": "^4.0.3",
"rollup-plugin-commonjs": "^9.2.0",
"rollup-plugin-node-resolve": "^3.4.0",
"rollup-plugin-size-snapshot": "^0.7.0",
"rollup-plugin-typescript": "^1.0.0",
"rollup-plugin-uglify": "^6.0.0",
"size-limit": "^0.20.1",
"ts-jest": "^23.10.4",
"ts-lib": "0.0.5",
"tslint": "^5.11.0",
"tslint-config-prettier": "^1.15.0",
"typescript": "^3.1.3",
"@date-io/core": "^0.0.1",
"@date-io/luxon": "^0.0.1",
"@date-io/moment": "^0.0.1",
"@date-io/date-fns": "^0.0.1"
},
"jest": {
"setupTestFrameworkScriptFile": "<rootDir>/src/__tests__/setup.js",
"testRegex": "./src/__tests__/.*\\.test\\.(js|tsx)$",
"testURL": "http://localhost/",
"collectCoverage": true,
"transform": {
"^.+\\.tsx?$": "ts-jest"
},
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
],
"globals": {
"ts-jest": {
"tsConfig": "./tsconfig.json"
}
}
}
}
| lib/package.json | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.035095274448394775,
0.0026695183478295803,
0.00016643331036902964,
0.00017002844833768904,
0.008679848164319992
] |
{
"id": 3,
"code_window": [
"{\n",
" \"build/dist/material-ui-pickers.cjs.js\": {\n",
" \"bundled\": 119585,\n",
" \"minified\": 72390,\n",
" \"gzipped\": 14601\n",
" },\n",
" \"build/dist/material-ui-pickers.esm.js\": {\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"bundled\": 119488,\n",
" \"minified\": 72333,\n",
" \"gzipped\": 14584\n"
],
"file_path": "lib/.size-snapshot.json",
"type": "replace",
"edit_start_line_idx": 2
} | *.js text eol=lf
*.jsx text eol=lf
| .gitattributes | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00017345446394756436,
0.00017345446394756436,
0.00017345446394756436,
0.00017345446394756436,
0
] |
{
"id": 3,
"code_window": [
"{\n",
" \"build/dist/material-ui-pickers.cjs.js\": {\n",
" \"bundled\": 119585,\n",
" \"minified\": 72390,\n",
" \"gzipped\": 14601\n",
" },\n",
" \"build/dist/material-ui-pickers.esm.js\": {\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"bundled\": 119488,\n",
" \"minified\": 72333,\n",
" \"gzipped\": 14584\n"
],
"file_path": "lib/.size-snapshot.json",
"type": "replace",
"edit_start_line_idx": 2
} | import React from 'react';
import PropTypes from 'prop-types';
import { List } from '@material-ui/core';
import { withRouter } from 'react-router-dom';
import NavItem from './NavItem';
const navItems = [
{
title: 'Getting Started',
children: [
{ title: 'Installation', href: '/installation' },
{ title: 'Usage', href: '/usage' },
{ title: 'Parsing dates', href: '/parsing' },
],
},
{
title: 'Localization',
children: [
{ title: 'Using date-fns', href: '/localization/date-fns' },
{ title: 'Using moment', href: '/localization/moment' },
{ title: 'Persian Calendar System', href: '/localization/persian' },
],
},
{
title: 'Components',
children: [
{ title: 'Date Picker', href: '/demo/datepicker' },
{ title: 'Time Picker', href: '/demo/timepicker' },
{ title: 'Date & Time Picker', href: '/demo/datetimepicker' },
],
},
{
title: 'Guides',
children: [
{ title: 'CSS overrides', href: '/guides/css-overrides' },
{ title: 'Global format customization', href: '/guides/formats' },
{ title: 'Open pickers programmatically', href: '/guides/controlling-programmatically' },
{ title: 'Static picker`s components', href: '/guides/static-pickers' },
],
},
];
class NavigationMenu extends React.Component {
mapNavigation(depth) {
return ({ title, children, href }) => {
const { location } = this.props;
const open = children && children.length > 0
? children.some(item => item.href === location.pathname)
: false;
return (
<NavItem
key={href || title}
title={title}
depth={depth}
href={href}
open={open}
>
{children && children.length > 0 && children.map(this.mapNavigation(depth + 1))}
</NavItem>
);
};
}
render() {
return (
<List component="nav">
{navItems.map(this.mapNavigation(0))}
</List>
);
}
}
NavigationMenu.propTypes = {
location: PropTypes.object.isRequired,
};
export default withRouter(NavigationMenu);
| docs/src/layout/NavigationMenu.jsx | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00017383627709932625,
0.00017003163520712405,
0.00016537295596208423,
0.00017047071014530957,
0.0000027465971470519435
] |
{
"id": 4,
"code_window": [
" },\n",
" \"build/dist/material-ui-pickers.esm.js\": {\n",
" \"bundled\": 114004,\n",
" \"minified\": 66935,\n",
" \"gzipped\": 14397,\n",
" \"treeshaked\": {\n",
" \"rollup\": {\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"bundled\": 113907,\n",
" \"minified\": 66878,\n",
" \"gzipped\": 14383,\n"
],
"file_path": "lib/.size-snapshot.json",
"type": "replace",
"edit_start_line_idx": 7
} | {
"build/dist/material-ui-pickers.cjs.js": {
"bundled": 119585,
"minified": 72390,
"gzipped": 14601
},
"build/dist/material-ui-pickers.esm.js": {
"bundled": 114004,
"minified": 66935,
"gzipped": 14397,
"treeshaked": {
"rollup": {
"code": 49272,
"import_statements": 1245
},
"webpack": {
"code": 56057
}
}
},
"build/dist/material-ui-pickers.umd.js": {
"bundled": 230045,
"minified": 100210,
"gzipped": 25280
},
"build/dist/material-ui-pickers.umd.min.js": {
"bundled": 200849,
"minified": 90120,
"gzipped": 23620
}
}
| lib/.size-snapshot.json | 1 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.9393505454063416,
0.23522315919399261,
0.0001722432643873617,
0.0006849212804809213,
0.40652820467948914
] |
{
"id": 4,
"code_window": [
" },\n",
" \"build/dist/material-ui-pickers.esm.js\": {\n",
" \"bundled\": 114004,\n",
" \"minified\": 66935,\n",
" \"gzipped\": 14397,\n",
" \"treeshaked\": {\n",
" \"rollup\": {\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"bundled\": 113907,\n",
" \"minified\": 66878,\n",
" \"gzipped\": 14383,\n"
],
"file_path": "lib/.size-snapshot.json",
"type": "replace",
"edit_start_line_idx": 7
} | import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { Divider, Toolbar, Typography, withStyles } from '@material-ui/core';
import NavigationMenu from './NavigationMenu';
import { version } from '../../package.json';
const DrawerMenu = ({ classes }) => (
<div className={classes.drawerRoot}>
<Toolbar className={classes.drawerToolbar}>
<Link to="/">
<Typography variant="subtitle1" className={classes.headerLink}>
Material-UI pickers
</Typography>
</Link>
<a
target="_blank"
rel="noopener noreferrer"
href="https://github.com/dmtrKovalenko/material-ui-pickers/releases"
>
<Typography variant="caption" className={classes.headerLink}>
{' '}
{version}{' '}
</Typography>
</a>
</Toolbar>
<Divider />
<NavigationMenu />
</div>
);
DrawerMenu.propTypes = {
classes: PropTypes.object.isRequired,
};
const styles = theme => ({
drawerRoot: {
width: 250,
},
drawerToolbar: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'flex-start',
},
headerLink: {
transition: 'color .2s ease-in-out',
'&:hover': {
color: theme.palette.primary.dark,
textDecoration: 'underline',
},
},
});
export default withStyles(styles)(DrawerMenu);
| docs/src/layout/DrawerMenu.jsx | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.0002510426566004753,
0.00018860296404454857,
0.00016670745390001684,
0.0001703332964098081,
0.00003083433330175467
] |
{
"id": 4,
"code_window": [
" },\n",
" \"build/dist/material-ui-pickers.esm.js\": {\n",
" \"bundled\": 114004,\n",
" \"minified\": 66935,\n",
" \"gzipped\": 14397,\n",
" \"treeshaked\": {\n",
" \"rollup\": {\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"bundled\": 113907,\n",
" \"minified\": 66878,\n",
" \"gzipped\": 14383,\n"
],
"file_path": "lib/.size-snapshot.json",
"type": "replace",
"edit_start_line_idx": 7
} | import fs from 'fs';
import path from 'path';
import nodeResolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import replace from 'rollup-plugin-replace';
import typescriptPlugin from 'rollup-plugin-typescript';
import typescript from 'typescript';
import babel from 'rollup-plugin-babel';
import { uglify } from 'rollup-plugin-uglify';
import { sizeSnapshot } from 'rollup-plugin-size-snapshot';
import pkg from './package.json';
const tsconfig = path.join(__dirname, 'tsconfig.json');
console.info(`Using tsconfig: ${tsconfig}`);
// treat as externals not relative and not absolute paths
const external = id => !id.startsWith('.') && !id.startsWith('/');
const input = './src/index.ts';
const globals = {
react: 'React',
'react-dom': 'ReactDOM',
'prop-types': 'PropTypes',
'@material-ui/core/Icon': 'material-ui.Icon',
'@material-ui/core/IconButton': 'material-ui.IconButton',
'@material-ui/core/InputAdornment': 'material-ui.InputAdornment',
'@material-ui/core/TextField': 'material-ui.TextField',
'@material-ui/core/Button': 'material-ui.Button',
'@material-ui/core/Dialog': 'material-ui.Dialog',
'@material-ui/core/DialogActions': 'material-ui.DialogActions',
'@material-ui/core/DialogContent': 'material-ui.DialogContent',
'@material-ui/core/styles/withStyles': 'material-ui.withStyles',
'@material-ui/core/styles/createStyles': 'material-ui.createStyles',
'@material-ui/core/Toolbar': 'material-ui.Toolbar',
'@material-ui/core/Typography': 'material-ui.Typography',
'@material-ui/core/Popover': 'material-ui.Popover',
'@material-ui/core/Paper': 'material-ui.Paper',
'@material-ui/core/styles/withTheme': 'material-ui.withTheme',
'@material-ui/core/Tab': 'material-ui.Tab',
'@material-ui/core/Tabs': 'material-ui.Tabs',
};
const extensions = ['.ts', '.tsx'];
const babelOptions = {
babelrc: false,
extensions,
plugins: ['./remove-prop-types.js'],
};
const commonjsOptions = {
include: 'node_modules/**',
};
export default [
{
input,
external,
output: {
file: pkg.main,
format: 'cjs',
sourcemap: true,
},
plugins: [
nodeResolve({ extensions }),
typescriptPlugin({ typescript, tsconfig }),
babel(babelOptions),
sizeSnapshot(),
],
},
{
input,
external,
output: {
file: pkg.module,
format: 'esm',
sourcemap: true,
},
plugins: [
nodeResolve({ extensions }),
typescriptPlugin({ typescript, tsconfig }),
babel(babelOptions),
{
transform(code) {
if (code.includes('/** @class */')) {
return code.replace(/\/\*\* @class \*\//g, '/*@__PURE__*/');
}
},
},
sizeSnapshot(),
],
},
{
input,
external: Object.keys(globals),
output: {
globals,
format: 'umd',
name: pkg.name,
file: 'build/dist/material-ui-pickers.umd.js',
},
plugins: [
nodeResolve({ extensions }),
typescriptPlugin({ typescript, tsconfig }),
babel(babelOptions),
commonjs(commonjsOptions),
replace({ 'process.env.NODE_ENV': JSON.stringify('development') }),
sizeSnapshot(),
],
},
{
input,
external: Object.keys(globals),
output: {
globals,
format: 'umd',
name: pkg.name,
file: 'build/dist/material-ui-pickers.umd.min.js',
},
plugins: [
nodeResolve({ extensions }),
typescriptPlugin({ typescript, tsconfig }),
babel(babelOptions),
commonjs(commonjsOptions),
replace({ 'process.env.NODE_ENV': JSON.stringify('production') }),
sizeSnapshot(),
uglify(),
],
},
];
| lib/rollup.config.js | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00037357723340392113,
0.00019875934231095016,
0.0001629368489375338,
0.00016996034537442029,
0.00005888905798201449
] |
{
"id": 4,
"code_window": [
" },\n",
" \"build/dist/material-ui-pickers.esm.js\": {\n",
" \"bundled\": 114004,\n",
" \"minified\": 66935,\n",
" \"gzipped\": 14397,\n",
" \"treeshaked\": {\n",
" \"rollup\": {\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"bundled\": 113907,\n",
" \"minified\": 66878,\n",
" \"gzipped\": 14383,\n"
],
"file_path": "lib/.size-snapshot.json",
"type": "replace",
"edit_start_line_idx": 7
} | import { ShallowWrapper } from 'enzyme';
import * as React from 'react';
import {
YearSelection,
YearSelectionProps,
} from '../../DatePicker/components/YearSelection';
import { shallow, utilsToUse } from '../test-utils';
describe('YearSelection', () => {
let component: ShallowWrapper<YearSelectionProps>;
beforeEach(() => {
component = shallow(
<YearSelection
classes={{} as any}
date={utilsToUse.date('01-01-2017')}
onChange={jest.fn()}
utils={utilsToUse}
/>
);
});
it('Should renders', () => {
// console.log(component.debug());
expect(component).toBeTruthy();
});
});
| lib/src/__tests__/DatePicker/YearSelection.test.tsx | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.0001726391928968951,
0.00017138064140453935,
0.0001706731563899666,
0.00017082958947867155,
8.922154393076198e-7
] |
{
"id": 5,
"code_window": [
" \"treeshaked\": {\n",
" \"rollup\": {\n",
" \"code\": 49272,\n",
" \"import_statements\": 1245\n",
" },\n",
" \"webpack\": {\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"code\": 49215,\n"
],
"file_path": "lib/.size-snapshot.json",
"type": "replace",
"edit_start_line_idx": 12
} | import React, { PureComponent } from 'react';
import Paper from '@material-ui/core/Paper';
// Make sure that for using static pickers you use path imports
import BasePicker from 'material-ui-pickers/_shared/BasePicker';
import Calendar from 'material-ui-pickers/DatePicker/components/Calendar';
import TimePickerView from 'material-ui-pickers/TimePicker/components/TimePickerView';
import MuiPickersUtilsProvider from 'material-ui-pickers/MuiPickersUtilsProvider';
import DateFnsUtils from 'material-ui-pickers/utils/date-fns-utils';
class StaticPickers extends PureComponent {
state = {
selectedDate: new Date(),
};
handleDateChange = date => {
this.setState({ selectedDate: date });
};
render() {
const { selectedDate } = this.state;
return (
// Also important to use path import for provider
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<BasePicker value={selectedDate} onChange={this.handleDateChange}>
{({
date,
handleAccept,
handleChange,
handleClear,
handleDismiss,
handleSetTodayDate,
handleTextFieldChange,
pick12hOr24hFormat,
}) => (
<div>
<div className="picker">
<Paper style={{ overflow: 'hidden' }}>
<Calendar date={date} onChange={handleChange} />
</Paper>
</div>
<TimePickerView
date={date}
ampm={false}
onHourChange={handleChange}
type="hours"
/>
</div>
)}
</BasePicker>
</MuiPickersUtilsProvider>
);
}
}
export default StaticPickers;
| docs/src/Examples/CodeSnippets/StaticPickers.jsx | 1 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00017604813911020756,
0.00017174455570057034,
0.0001685275201452896,
0.0001717947598081082,
0.0000026135583084396785
] |
{
"id": 5,
"code_window": [
" \"treeshaked\": {\n",
" \"rollup\": {\n",
" \"code\": 49272,\n",
" \"import_statements\": 1245\n",
" },\n",
" \"webpack\": {\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"code\": 49215,\n"
],
"file_path": "lib/.size-snapshot.json",
"type": "replace",
"edit_start_line_idx": 12
} | import { Theme } from '@material-ui/core';
import createStyles from '@material-ui/core/styles/createStyles';
import withStyles, { WithStyles } from '@material-ui/core/styles/withStyles';
import Toolbar, { ToolbarProps } from '@material-ui/core/Toolbar';
import classnames from 'classnames';
import * as PropTypes from 'prop-types';
import * as React from 'react';
import { ExtendMui } from '../typings/extendMui';
export interface PickerToolbarProps
extends ExtendMui<ToolbarProps>,
WithStyles<typeof styles> {
children: React.ReactNodeArray;
}
const PickerToolbar: React.SFC<PickerToolbarProps> = ({
children,
className,
classes,
...other
}) => {
return (
<Toolbar className={classnames(classes.toolbar, className)} {...other}>
{children}
</Toolbar>
);
};
(PickerToolbar as any).propTypes = {
children: PropTypes.arrayOf(PropTypes.node).isRequired,
className: PropTypes.string,
classes: PropTypes.any.isRequired,
innerRef: PropTypes.any,
};
PickerToolbar.defaultProps = {
className: '',
};
const styles = (theme: Theme) =>
createStyles({
toolbar: {
display: 'flex',
flexDirection: 'column',
alignItems: 'flex-start',
justifyContent: 'center',
height: 100,
backgroundColor:
theme.palette.type === 'light'
? theme.palette.primary.main
: theme.palette.background.default,
},
});
export default withStyles(styles, { name: 'MuiPickersToolbar' })(PickerToolbar);
| lib/src/_shared/PickerToolbar.tsx | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00017613997624721378,
0.00016969762509688735,
0.00016610100283287466,
0.00016872536798473448,
0.0000031982783639250556
] |
{
"id": 5,
"code_window": [
" \"treeshaked\": {\n",
" \"rollup\": {\n",
" \"code\": 49272,\n",
" \"import_statements\": 1245\n",
" },\n",
" \"webpack\": {\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"code\": 49215,\n"
],
"file_path": "lib/.size-snapshot.json",
"type": "replace",
"edit_start_line_idx": 12
} | import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { Divider, Toolbar, Typography, withStyles } from '@material-ui/core';
import NavigationMenu from './NavigationMenu';
import { version } from '../../package.json';
const DrawerMenu = ({ classes }) => (
<div className={classes.drawerRoot}>
<Toolbar className={classes.drawerToolbar}>
<Link to="/">
<Typography variant="subtitle1" className={classes.headerLink}>
Material-UI pickers
</Typography>
</Link>
<a
target="_blank"
rel="noopener noreferrer"
href="https://github.com/dmtrKovalenko/material-ui-pickers/releases"
>
<Typography variant="caption" className={classes.headerLink}>
{' '}
{version}{' '}
</Typography>
</a>
</Toolbar>
<Divider />
<NavigationMenu />
</div>
);
DrawerMenu.propTypes = {
classes: PropTypes.object.isRequired,
};
const styles = theme => ({
drawerRoot: {
width: 250,
},
drawerToolbar: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'flex-start',
},
headerLink: {
transition: 'color .2s ease-in-out',
'&:hover': {
color: theme.palette.primary.dark,
textDecoration: 'underline',
},
},
});
export default withStyles(styles)(DrawerMenu);
| docs/src/layout/DrawerMenu.jsx | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00017438978829886764,
0.0001725948095554486,
0.00017104735889006406,
0.0001722638262435794,
0.000001226943140864023
] |
{
"id": 5,
"code_window": [
" \"treeshaked\": {\n",
" \"rollup\": {\n",
" \"code\": 49272,\n",
" \"import_statements\": 1245\n",
" },\n",
" \"webpack\": {\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"code\": 49215,\n"
],
"file_path": "lib/.size-snapshot.json",
"type": "replace",
"edit_start_line_idx": 12
} | import { WithStyles } from '@material-ui/core';
import { ShallowWrapper } from 'enzyme';
import * as React from 'react';
import {
ModalDialog,
ModalDialogProps,
styles,
} from '../../_shared/ModalDialog';
import { shallow } from '../test-utils';
const initialProps: ModalDialogProps & WithStyles<typeof styles> = {
onAccept: jest.fn(),
onDismiss: jest.fn(),
onClear: jest.fn(),
onKeyDown: jest.fn(),
okLabel: 'OK',
open: false,
cancelLabel: 'Cancel',
clearLabel: 'Clear',
clearable: false,
todayLabel: 'Today',
showTodayButton: false,
onSetToday: jest.fn(),
children: 'Test',
classes: {} as any,
};
describe('ModalDialog', () => {
let component: ShallowWrapper<ModalDialogProps>;
const props = { ...initialProps };
beforeEach(() => {
component = shallow(<ModalDialog {...props} />);
});
it('Should renders', () => {
// console.log(component.debug());
expect(component).toBeTruthy();
});
it('Should render dialog content', () => {
expect(component.find('WithStyles(DialogContent)').props().children).toBe(
props.children
);
});
it('Should render dialog actions with 2 buttons', () => {
expect(component.find('WithStyles(DialogActions)').length).toBe(1);
expect(
component
.find('WithStyles(Button)')
.at(0)
.props().children
).toBe('Cancel');
expect(
component
.find('WithStyles(Button)')
.at(1)
.props().children
).toBe('OK');
});
it('Should handle on OK button click', () => {
component
.find('WithStyles(Button)')
.at(1)
.simulate('click');
expect(props.onAccept).toHaveBeenCalled();
});
it('Should handle on Cancel button click', () => {
component
.find('WithStyles(Button)')
.at(0)
.simulate('click');
expect(props.onDismiss).toHaveBeenCalled();
});
});
describe('ModalDialog with Clear Button', () => {
let component: ShallowWrapper<ModalDialogProps>;
const props = {
...initialProps,
clearable: true,
};
beforeEach(() => {
component = shallow(<ModalDialog {...props} />);
});
it('Should handle on Clear button click', () => {
component
.find('WithStyles(Button)')
.at(0)
.simulate('click');
expect(props.onClear).toHaveBeenCalled();
});
});
describe('ModalDialog with Today Button', () => {
let component: ShallowWrapper<ModalDialogProps>;
const props = {
...initialProps,
showTodayButton: true,
};
beforeEach(() => {
component = shallow(<ModalDialog {...props} />);
});
it('Should handle on Clear button click', () => {
component
.find('WithStyles(Button)')
.at(0)
.simulate('click');
expect(props.onSetToday).toHaveBeenCalled();
});
});
| lib/src/__tests__/_shared/ModalDialog.test.tsx | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00017864479741547257,
0.00017448484140913934,
0.0001698905398370698,
0.00017504769493825734,
0.0000020988240976294037
] |
{
"id": 6,
"code_window": [
" \"import_statements\": 1245\n",
" },\n",
" \"webpack\": {\n",
" \"code\": 56057\n",
" }\n",
" }\n",
" },\n",
" \"build/dist/material-ui-pickers.umd.js\": {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"code\": 56000\n"
],
"file_path": "lib/.size-snapshot.json",
"type": "replace",
"edit_start_line_idx": 16
} | {
"build/dist/material-ui-pickers.cjs.js": {
"bundled": 119585,
"minified": 72390,
"gzipped": 14601
},
"build/dist/material-ui-pickers.esm.js": {
"bundled": 114004,
"minified": 66935,
"gzipped": 14397,
"treeshaked": {
"rollup": {
"code": 49272,
"import_statements": 1245
},
"webpack": {
"code": 56057
}
}
},
"build/dist/material-ui-pickers.umd.js": {
"bundled": 230045,
"minified": 100210,
"gzipped": 25280
},
"build/dist/material-ui-pickers.umd.min.js": {
"bundled": 200849,
"minified": 90120,
"gzipped": 23620
}
}
| lib/.size-snapshot.json | 1 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.7426214814186096,
0.18773417174816132,
0.00017127289902418852,
0.004071979783475399,
0.3203760087490082
] |
{
"id": 6,
"code_window": [
" \"import_statements\": 1245\n",
" },\n",
" \"webpack\": {\n",
" \"code\": 56057\n",
" }\n",
" }\n",
" },\n",
" \"build/dist/material-ui-pickers.umd.js\": {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"code\": 56000\n"
],
"file_path": "lib/.size-snapshot.json",
"type": "replace",
"edit_start_line_idx": 16
} | import { ShallowWrapper } from 'enzyme';
import * as React from 'react';
import {
DatePickerModal,
DatePickerModalProps,
} from '../../DatePicker/DatePickerModal';
import { shallow, utilsToUse } from '../test-utils';
const spy = jest.fn();
const props = {
keyboard: true,
format: 'YYYY',
onChange: spy,
value: utilsToUse.date('2018'),
};
describe('DatePickerModal', () => {
let component: ShallowWrapper<DatePickerModalProps>;
beforeEach(() => {
component = shallow(<DatePickerModal {...props} />);
});
it('Should renders', () => {
// console.log(component.debug());
expect(component).toBeTruthy();
});
});
| lib/src/__tests__/DatePicker/DatePickerModal.test.tsx | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00021780178940389305,
0.00018384297436568886,
0.00016661209519952536,
0.00016711503849364817,
0.000024013384972931817
] |
{
"id": 6,
"code_window": [
" \"import_statements\": 1245\n",
" },\n",
" \"webpack\": {\n",
" \"code\": 56057\n",
" }\n",
" }\n",
" },\n",
" \"build/dist/material-ui-pickers.umd.js\": {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"code\": 56000\n"
],
"file_path": "lib/.size-snapshot.json",
"type": "replace",
"edit_start_line_idx": 16
} | import fs from 'fs';
import path from 'path';
import nodeResolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import replace from 'rollup-plugin-replace';
import typescriptPlugin from 'rollup-plugin-typescript';
import typescript from 'typescript';
import babel from 'rollup-plugin-babel';
import { uglify } from 'rollup-plugin-uglify';
import { sizeSnapshot } from 'rollup-plugin-size-snapshot';
import pkg from './package.json';
const tsconfig = path.join(__dirname, 'tsconfig.json');
console.info(`Using tsconfig: ${tsconfig}`);
// treat as externals not relative and not absolute paths
const external = id => !id.startsWith('.') && !id.startsWith('/');
const input = './src/index.ts';
const globals = {
react: 'React',
'react-dom': 'ReactDOM',
'prop-types': 'PropTypes',
'@material-ui/core/Icon': 'material-ui.Icon',
'@material-ui/core/IconButton': 'material-ui.IconButton',
'@material-ui/core/InputAdornment': 'material-ui.InputAdornment',
'@material-ui/core/TextField': 'material-ui.TextField',
'@material-ui/core/Button': 'material-ui.Button',
'@material-ui/core/Dialog': 'material-ui.Dialog',
'@material-ui/core/DialogActions': 'material-ui.DialogActions',
'@material-ui/core/DialogContent': 'material-ui.DialogContent',
'@material-ui/core/styles/withStyles': 'material-ui.withStyles',
'@material-ui/core/styles/createStyles': 'material-ui.createStyles',
'@material-ui/core/Toolbar': 'material-ui.Toolbar',
'@material-ui/core/Typography': 'material-ui.Typography',
'@material-ui/core/Popover': 'material-ui.Popover',
'@material-ui/core/Paper': 'material-ui.Paper',
'@material-ui/core/styles/withTheme': 'material-ui.withTheme',
'@material-ui/core/Tab': 'material-ui.Tab',
'@material-ui/core/Tabs': 'material-ui.Tabs',
};
const extensions = ['.ts', '.tsx'];
const babelOptions = {
babelrc: false,
extensions,
plugins: ['./remove-prop-types.js'],
};
const commonjsOptions = {
include: 'node_modules/**',
};
export default [
{
input,
external,
output: {
file: pkg.main,
format: 'cjs',
sourcemap: true,
},
plugins: [
nodeResolve({ extensions }),
typescriptPlugin({ typescript, tsconfig }),
babel(babelOptions),
sizeSnapshot(),
],
},
{
input,
external,
output: {
file: pkg.module,
format: 'esm',
sourcemap: true,
},
plugins: [
nodeResolve({ extensions }),
typescriptPlugin({ typescript, tsconfig }),
babel(babelOptions),
{
transform(code) {
if (code.includes('/** @class */')) {
return code.replace(/\/\*\* @class \*\//g, '/*@__PURE__*/');
}
},
},
sizeSnapshot(),
],
},
{
input,
external: Object.keys(globals),
output: {
globals,
format: 'umd',
name: pkg.name,
file: 'build/dist/material-ui-pickers.umd.js',
},
plugins: [
nodeResolve({ extensions }),
typescriptPlugin({ typescript, tsconfig }),
babel(babelOptions),
commonjs(commonjsOptions),
replace({ 'process.env.NODE_ENV': JSON.stringify('development') }),
sizeSnapshot(),
],
},
{
input,
external: Object.keys(globals),
output: {
globals,
format: 'umd',
name: pkg.name,
file: 'build/dist/material-ui-pickers.umd.min.js',
},
plugins: [
nodeResolve({ extensions }),
typescriptPlugin({ typescript, tsconfig }),
babel(babelOptions),
commonjs(commonjsOptions),
replace({ 'process.env.NODE_ENV': JSON.stringify('production') }),
sizeSnapshot(),
uglify(),
],
},
];
| lib/rollup.config.js | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.0005228357040323317,
0.00022173099569045007,
0.0001658977853367105,
0.00016980718646664172,
0.00012076504935976118
] |
{
"id": 6,
"code_window": [
" \"import_statements\": 1245\n",
" },\n",
" \"webpack\": {\n",
" \"code\": 56057\n",
" }\n",
" }\n",
" },\n",
" \"build/dist/material-ui-pickers.umd.js\": {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"code\": 56000\n"
],
"file_path": "lib/.size-snapshot.json",
"type": "replace",
"edit_start_line_idx": 16
} | import React, { PureComponent } from 'react';
import moment from 'moment';
import 'moment/locale/fr';
import 'moment/locale/ru';
import MomentUtils from '@date-io/moment';
import { Icon, IconButton, Menu, MenuItem } from '@material-ui/core';
import { DatePicker, MuiPickersUtilsProvider } from 'material-ui-pickers';
moment.locale('fr');
const localeMap = {
en: 'en',
fr: 'fr',
ru: 'ru',
};
export default class MomentLocalizationExample extends PureComponent {
state = {
selectedDate: new Date(),
anchorEl: null,
currentLocale: 'fr',
}
handleDateChange = (date) => {
this.setState({ selectedDate: date.toDate() });
}
handleMenuOpen = (event) => {
event.stopPropagation();
this.setState({ anchorEl: event.currentTarget });
}
handleMenuClose = () => {
this.setState({ anchorEl: null });
};
selectLocale = (selectedLocale) => {
moment.locale(selectedLocale);
this.setState({
currentLocale: selectedLocale,
anchorEl: null,
});
}
render() {
const { selectedDate } = this.state;
const locale = localeMap[this.state.currentLocale];
return (
<MuiPickersUtilsProvider utils={MomentUtils} locale={locale} moment={moment}>
<div className="picker">
<DatePicker
value={selectedDate}
onChange={this.handleDateChange}
InputProps={{
endAdornment: (
<IconButton
aria-label="Select locale"
aria-owns={this.state.anchorEl ? 'locale-menu' : null}
onClick={this.handleMenuOpen}
>
<Icon> more_vert </Icon>
</IconButton>
),
}}
/>
</div>
<Menu
id="locale-menu"
anchorEl={this.state.anchorEl}
open={Boolean(this.state.anchorEl)}
onClose={this.handleMenuClose}
>
{
Object.keys(localeMap).map(localeItem => (
<MenuItem
key={localeItem}
selected={localeItem === this.state.locale}
onClick={() => this.selectLocale(localeItem)}
>
{localeItem}
</MenuItem>
))
}
</Menu>
</MuiPickersUtilsProvider>
);
}
}
| docs/src/Examples/Localization/MomentLocalizationExample.jsx | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.0002536335086915642,
0.00018770669703371823,
0.00016630307072773576,
0.0001702115114312619,
0.0000308129056065809
] |
{
"id": 7,
"code_window": [
" }\n",
" },\n",
" \"build/dist/material-ui-pickers.umd.js\": {\n",
" \"bundled\": 230045,\n",
" \"minified\": 100210,\n",
" \"gzipped\": 25280\n",
" },\n",
" \"build/dist/material-ui-pickers.umd.min.js\": {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"bundled\": 229940,\n",
" \"minified\": 100153,\n",
" \"gzipped\": 25269\n"
],
"file_path": "lib/.size-snapshot.json",
"type": "replace",
"edit_start_line_idx": 21
} | {
"build/dist/material-ui-pickers.cjs.js": {
"bundled": 119585,
"minified": 72390,
"gzipped": 14601
},
"build/dist/material-ui-pickers.esm.js": {
"bundled": 114004,
"minified": 66935,
"gzipped": 14397,
"treeshaked": {
"rollup": {
"code": 49272,
"import_statements": 1245
},
"webpack": {
"code": 56057
}
}
},
"build/dist/material-ui-pickers.umd.js": {
"bundled": 230045,
"minified": 100210,
"gzipped": 25280
},
"build/dist/material-ui-pickers.umd.min.js": {
"bundled": 200849,
"minified": 90120,
"gzipped": 23620
}
}
| lib/.size-snapshot.json | 1 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.9945632815361023,
0.2494153380393982,
0.00016874089487828314,
0.0014646464260295033,
0.43021267652511597
] |
{
"id": 7,
"code_window": [
" }\n",
" },\n",
" \"build/dist/material-ui-pickers.umd.js\": {\n",
" \"bundled\": 230045,\n",
" \"minified\": 100210,\n",
" \"gzipped\": 25280\n",
" },\n",
" \"build/dist/material-ui-pickers.umd.min.js\": {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"bundled\": 229940,\n",
" \"minified\": 100153,\n",
" \"gzipped\": 25269\n"
],
"file_path": "lib/.size-snapshot.json",
"type": "replace",
"edit_start_line_idx": 21
} | import { IUtils } from '@date-io/core/IUtils';
import * as React from 'react';
import { MaterialUiPickersDate } from '../../typings/date';
import ClockNumber from './ClockNumber';
export const getHourNumbers = ({
ampm,
utils,
date,
}: {
ampm: boolean;
utils: IUtils<MaterialUiPickersDate>;
date: MaterialUiPickersDate;
}) => {
const currentHours = utils.getHours(date);
const hourNumbers: JSX.Element[] = [];
const startHour = ampm ? 1 : 0;
const endHour = ampm ? 12 : 23;
const isSelected = (hour: number) => {
if (ampm) {
if (hour === 12) {
return currentHours === 12 || currentHours === 0;
}
return currentHours === hour || currentHours - 12 === hour;
}
return currentHours === hour;
};
for (let hour = startHour; hour <= endHour; hour += 1) {
let label = hour.toString();
if (hour === 0) {
label = '00';
}
const props = {
index: hour,
label: utils.formatNumber(label),
selected: isSelected(hour),
isInner: !ampm && (hour === 0 || hour > 12),
};
hourNumbers.push(<ClockNumber key={hour} {...props} />);
}
return hourNumbers;
};
export const getMinutesNumbers = ({
value,
utils,
}: {
value: number;
utils: IUtils<MaterialUiPickersDate>;
}) => {
const f = utils.formatNumber;
return [
<ClockNumber label={f('00')} selected={value === 0} index={12} key={12} />,
<ClockNumber label={f('05')} selected={value === 5} index={1} key={1} />,
<ClockNumber label={f('10')} selected={value === 10} index={2} key={2} />,
<ClockNumber label={f('15')} selected={value === 15} index={3} key={3} />,
<ClockNumber label={f('20')} selected={value === 20} index={4} key={4} />,
<ClockNumber label={f('25')} selected={value === 25} index={5} key={5} />,
<ClockNumber label={f('30')} selected={value === 30} index={6} key={6} />,
<ClockNumber label={f('35')} selected={value === 35} index={7} key={7} />,
<ClockNumber label={f('40')} selected={value === 40} index={8} key={8} />,
<ClockNumber label={f('45')} selected={value === 45} index={9} key={9} />,
<ClockNumber label={f('50')} selected={value === 50} index={10} key={10} />,
<ClockNumber label={f('55')} selected={value === 55} index={11} key={11} />,
];
};
| lib/src/TimePicker/components/ClockNumbers.tsx | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.000348469679011032,
0.00019800479640252888,
0.00016860129835549742,
0.00017324372311122715,
0.0000576097663724795
] |
{
"id": 7,
"code_window": [
" }\n",
" },\n",
" \"build/dist/material-ui-pickers.umd.js\": {\n",
" \"bundled\": 230045,\n",
" \"minified\": 100210,\n",
" \"gzipped\": 25280\n",
" },\n",
" \"build/dist/material-ui-pickers.umd.min.js\": {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"bundled\": 229940,\n",
" \"minified\": 100153,\n",
" \"gzipped\": 25269\n"
],
"file_path": "lib/.size-snapshot.json",
"type": "replace",
"edit_start_line_idx": 21
} | import DateFnsUtils from '@date-io/date-fns';
import LuxonUtils from '@date-io/luxon';
import MomentUtils from '@date-io/moment';
import createMuiTheme from '@material-ui/core/styles/createMuiTheme';
import MuiThemeProvider from '@material-ui/core/styles/MuiThemeProvider';
import * as enzyme from 'enzyme';
import * as React from 'react';
import { WithUtilsProps } from '../_shared/WithUtils';
import MuiPickersUtilsProvider from '../MuiPickersUtilsProvider';
const theme = createMuiTheme({
typography: {
useNextVariants: true,
},
});
const getUtilClass = () => {
switch (process.env.UTILS) {
case 'moment':
return MomentUtils;
case 'date-fns':
return DateFnsUtils;
case 'luxon':
return LuxonUtils;
default:
return DateFnsUtils;
}
};
export const UtilClassToUse: any = getUtilClass();
export const utilsToUse = new UtilClassToUse();
// jest.doMock('../_shared/WithUtils', () => {
// const WithUtils = () => (Component: React.ComponentType<WithUtilsProps>) => {
// const withUtils: React.SFC<any> = props => (
// <Component utils={utilsToUse} {...props} />
// );
// withUtils.displayName = `WithUtils(${Component.displayName ||
// Component.name})`;
//
// return withUtils;
// };
//
// return { default: WithUtils };
// });
const getComponentWithUtils = <P extends WithUtilsProps>(
element: React.ReactElement<P>
) => React.cloneElement(element, { utils: utilsToUse } as any);
export const shallow = <P extends WithUtilsProps>(
element: React.ReactElement<P>
) => enzyme.shallow(getComponentWithUtils(element));
export const mount = <P extends WithUtilsProps>(
element: React.ReactElement<P>
) =>
enzyme.mount(
<MuiPickersUtilsProvider utils={UtilClassToUse}>
<MuiThemeProvider theme={theme}>{element}</MuiThemeProvider>
</MuiPickersUtilsProvider>
);
export const shallowRender = (
render: (props: any) => React.ReactElement<any>
) => {
return enzyme.shallow(
render({ utils: utilsToUse, classes: {} as any, theme: {} as any })
);
};
| lib/src/__tests__/test-utils.tsx | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00016815080016385764,
0.0001667207106947899,
0.00016462062194477767,
0.00016687023162376136,
0.0000011506785995152313
] |
{
"id": 7,
"code_window": [
" }\n",
" },\n",
" \"build/dist/material-ui-pickers.umd.js\": {\n",
" \"bundled\": 230045,\n",
" \"minified\": 100210,\n",
" \"gzipped\": 25280\n",
" },\n",
" \"build/dist/material-ui-pickers.umd.min.js\": {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"bundled\": 229940,\n",
" \"minified\": 100153,\n",
" \"gzipped\": 25269\n"
],
"file_path": "lib/.size-snapshot.json",
"type": "replace",
"edit_start_line_idx": 21
} | import { TimePickerInlineProps } from './TimePickerInline';
import { TimePickerModalProps } from './TimePickerModal';
export { default } from './TimePickerModal';
export { default as InlineTimePicker } from './TimePickerInline';
export type TimePickerProps = TimePickerModalProps;
export type TimePickerInlineProps = TimePickerInlineProps;
| lib/src/TimePicker/index.tsx | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00016963591042440385,
0.00016963591042440385,
0.00016963591042440385,
0.00016963591042440385,
0
] |
{
"id": 8,
"code_window": [
" },\n",
" \"build/dist/material-ui-pickers.umd.min.js\": {\n",
" \"bundled\": 200849,\n",
" \"minified\": 90120,\n",
" \"gzipped\": 23620\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"bundled\": 200576,\n",
" \"minified\": 90033,\n",
" \"gzipped\": 23583\n"
],
"file_path": "lib/.size-snapshot.json",
"type": "replace",
"edit_start_line_idx": 26
} | {
"build/dist/material-ui-pickers.cjs.js": {
"bundled": 119585,
"minified": 72390,
"gzipped": 14601
},
"build/dist/material-ui-pickers.esm.js": {
"bundled": 114004,
"minified": 66935,
"gzipped": 14397,
"treeshaked": {
"rollup": {
"code": 49272,
"import_statements": 1245
},
"webpack": {
"code": 56057
}
}
},
"build/dist/material-ui-pickers.umd.js": {
"bundled": 230045,
"minified": 100210,
"gzipped": 25280
},
"build/dist/material-ui-pickers.umd.min.js": {
"bundled": 200849,
"minified": 90120,
"gzipped": 23620
}
}
| lib/.size-snapshot.json | 1 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.9910411238670349,
0.24809584021568298,
0.00017122637655120343,
0.00058551604161039,
0.4289397895336151
] |
{
"id": 8,
"code_window": [
" },\n",
" \"build/dist/material-ui-pickers.umd.min.js\": {\n",
" \"bundled\": 200849,\n",
" \"minified\": 90120,\n",
" \"gzipped\": 23620\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"bundled\": 200576,\n",
" \"minified\": 90033,\n",
" \"gzipped\": 23583\n"
],
"file_path": "lib/.size-snapshot.json",
"type": "replace",
"edit_start_line_idx": 26
} | enum DateTimePickerView {
YEAR = 'year',
DATE = 'date',
HOUR = 'hours',
MINUTES = 'minutes',
}
export type DateTimePickerViewType = 'year' | 'date' | 'hours' | 'minutes';
export default DateTimePickerView;
| lib/src/constants/DateTimePickerView.ts | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00032874656608328223,
0.00024638237664476037,
0.00016401817265432328,
0.00024638237664476037,
0.00008236419671447948
] |
{
"id": 8,
"code_window": [
" },\n",
" \"build/dist/material-ui-pickers.umd.min.js\": {\n",
" \"bundled\": 200849,\n",
" \"minified\": 90120,\n",
" \"gzipped\": 23620\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"bundled\": 200576,\n",
" \"minified\": 90033,\n",
" \"gzipped\": 23583\n"
],
"file_path": "lib/.size-snapshot.json",
"type": "replace",
"edit_start_line_idx": 26
} | import createStyles from '@material-ui/core/styles/createStyles';
import withStyles, { WithStyles } from '@material-ui/core/styles/withStyles';
import * as PropTypes from 'prop-types';
import * as React from 'react';
export interface DateTimePickerViewProps extends WithStyles<typeof styles> {
selected: boolean;
children: React.ReactChild;
}
export const DateTimePickerView: React.SFC<DateTimePickerViewProps> = ({
selected,
children,
classes,
}) => {
if (!selected) {
return null;
}
return <div className={classes.view}>{children}</div>;
};
(DateTimePickerView as any).propTypes = {
selected: PropTypes.bool.isRequired,
children: PropTypes.node.isRequired,
classes: PropTypes.object.isRequired,
};
const styles = createStyles({
view: {
zIndex: 1,
position: 'absolute',
left: 0,
right: 0,
},
});
export default withStyles(styles, { name: 'MuiPickerDTPickerView ' })(
DateTimePickerView
);
| lib/src/DateTimePicker/components/DateTimePickerView.tsx | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00022486422676593065,
0.00018316999194212258,
0.00016773059905972332,
0.00017437149654142559,
0.000021092509996378794
] |
{
"id": 8,
"code_window": [
" },\n",
" \"build/dist/material-ui-pickers.umd.min.js\": {\n",
" \"bundled\": 200849,\n",
" \"minified\": 90120,\n",
" \"gzipped\": 23620\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"bundled\": 200576,\n",
" \"minified\": 90033,\n",
" \"gzipped\": 23583\n"
],
"file_path": "lib/.size-snapshot.json",
"type": "replace",
"edit_start_line_idx": 26
} | import React from 'react';
import PropTypes from 'prop-types';
import { ListItem, withStyles, Collapse } from '@material-ui/core';
import Button from '@material-ui/core/Button';
import { NavLink } from 'react-router-dom';
const styles = theme => ({
listItem: {
display: 'block',
paddingTop: 0,
paddingBottom: 0,
},
bold: {
fontWeight: 500,
},
button: {
justifyContent: 'flex-start',
textTransform: 'none',
width: '100%',
...theme.typography.body1,
},
selected: {
color: theme.palette.primary.main,
fontWeight: 500,
},
collapse: {
padding: 0,
margin: 0,
},
});
class NavItem extends React.Component {
constructor(props) {
super(props);
this.state = {
open: this.props.open,
};
}
handleClick = (e) => {
if (this.props.depth === 0) {
e.stopPropagation();
}
this.setState({ open: !this.state.open });
};
render() {
const {
href, title, children, classes, depth, ...props
} = this.props;
const style = { paddingLeft: `${(depth + 1) * 16}px` };
if (depth === 0) {
style.fontWeight = 500;
}
if (href) {
return (
<ListItem
disableGutters
className={classes.listItem}
{...props}
>
<Button
disableRipple
component={NavLink}
activeClassName={classes.selected}
to={href}
onClick={this.handleClick}
style={style}
classes={{
root: classes.button,
}}
>
{title}
</Button>
</ListItem>
);
}
return (
<ListItem
disableGutters
className={classes.listItem}
{...props}
>
<Button
onClick={this.handleClick}
style={style}
classes={{
root: classes.button,
}}
>
{title}
</Button>
<Collapse
in={this.state.open}
unmountOnExit
component="ul"
className={classes.collapse}
>
{children}
</Collapse>
</ListItem>
);
}
}
NavItem.propTypes = {
classes: PropTypes.object.isRequired,
open: PropTypes.bool.isRequired,
href: PropTypes.string,
title: PropTypes.string.isRequired,
children: PropTypes.arrayOf(PropTypes.object),
depth: PropTypes.number,
};
NavItem.defaultProps = {
depth: 0,
children: undefined,
href: undefined,
};
export default withStyles(styles)(NavItem);
| docs/src/layout/NavItem.jsx | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00018130567332264036,
0.00017031528113875538,
0.0001669756748015061,
0.00016953614249359816,
0.0000033382148103555664
] |
{
"id": 9,
"code_window": [
" public state = {\n",
" showYearSelection: Boolean(this.props.openToYearSelection),\n",
" };\n",
"\n",
" get date() {\n",
" return this.props.utils.startOfDay(this.props.date);\n",
" }\n",
"\n",
" get minDate() {\n",
" return this.props.utils.date(this.props.minDate);\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return this.props.date;\n"
],
"file_path": "lib/src/DatePicker/DatePicker.tsx",
"type": "replace",
"edit_start_line_idx": 89
} | import React from 'react';
import Code from '_shared/Code';
import { Typography } from '@material-ui/core';
// eslint-disable-next-line
import StaticPickersCode from '!raw-loader!../../Examples/CodeSnippets/StaticPickers';
const StaticPickers = () => (
<div>
<Typography variant="h2" gutterBottom>
{' '}
Static pickers{' '}
</Typography>
<Typography variant="body1" gutterBottom>
Somewhere its required to use some internal control for calendar or some
timeinput. Here you are! You can use directly any sub-control of the
pickers. Please note - if you want to use internal controls ALL your
imports must be from the relative paths
</Typography>
<Typography variant="body1" gutterBottom>
Also you can use our own HOC that is using for any picker which provide
managing temporary chosen date and submitting state logic.
</Typography>
<Code text={StaticPickersCode} />
</div>
);
export default StaticPickers;
| docs/src/Pages/Guides/StaticPickers.jsx | 1 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00017399150237906724,
0.0001708253112155944,
0.00016591216262895614,
0.0001716987753752619,
0.0000030246731057559373
] |
{
"id": 9,
"code_window": [
" public state = {\n",
" showYearSelection: Boolean(this.props.openToYearSelection),\n",
" };\n",
"\n",
" get date() {\n",
" return this.props.utils.startOfDay(this.props.date);\n",
" }\n",
"\n",
" get minDate() {\n",
" return this.props.utils.date(this.props.minDate);\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return this.props.date;\n"
],
"file_path": "lib/src/DatePicker/DatePicker.tsx",
"type": "replace",
"edit_start_line_idx": 89
} | import { ShallowWrapper } from 'enzyme';
import * as React from 'react';
import {
DatePickerModal,
DatePickerModalProps,
} from '../../DatePicker/DatePickerModal';
import { shallow, utilsToUse } from '../test-utils';
const spy = jest.fn();
const props = {
keyboard: true,
format: 'YYYY',
onChange: spy,
value: utilsToUse.date('2018'),
};
describe('DatePickerModal', () => {
let component: ShallowWrapper<DatePickerModalProps>;
beforeEach(() => {
component = shallow(<DatePickerModal {...props} />);
});
it('Should renders', () => {
// console.log(component.debug());
expect(component).toBeTruthy();
});
});
| lib/src/__tests__/DatePicker/DatePickerModal.test.tsx | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.9743853211402893,
0.3249073326587677,
0.00016767415218055248,
0.00016906591190490872,
0.459250271320343
] |
{
"id": 9,
"code_window": [
" public state = {\n",
" showYearSelection: Boolean(this.props.openToYearSelection),\n",
" };\n",
"\n",
" get date() {\n",
" return this.props.utils.startOfDay(this.props.date);\n",
" }\n",
"\n",
" get minDate() {\n",
" return this.props.utils.date(this.props.minDate);\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return this.props.date;\n"
],
"file_path": "lib/src/DatePicker/DatePicker.tsx",
"type": "replace",
"edit_start_line_idx": 89
} | import { ShallowWrapper } from 'enzyme';
import * as React from 'react';
import {
DateTimePickerInlineProps,
InlineDateTimePicker,
} from '../../DateTimePicker';
import { shallow, utilsToUse } from '../test-utils';
const spy = jest.fn();
const props = {
keyboard: true,
format: 'YYYY',
onChange: spy,
value: utilsToUse.date('2018'),
};
describe('DatePickerModal', () => {
let component: ShallowWrapper<DateTimePickerInlineProps>;
beforeEach(() => {
component = shallow(<InlineDateTimePicker variant="outlined" {...props} />);
});
it('Should renders', () => {
// console.log(component.debug());
expect(component).toBeTruthy();
});
});
| lib/src/__tests__/DateTimePicker/DateTimePickerInline.test.tsx | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.9759814143180847,
0.32543957233428955,
0.00016829291416797787,
0.00016904978838283569,
0.4600025415420532
] |
{
"id": 9,
"code_window": [
" public state = {\n",
" showYearSelection: Boolean(this.props.openToYearSelection),\n",
" };\n",
"\n",
" get date() {\n",
" return this.props.utils.startOfDay(this.props.date);\n",
" }\n",
"\n",
" get minDate() {\n",
" return this.props.utils.date(this.props.minDate);\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" return this.props.date;\n"
],
"file_path": "lib/src/DatePicker/DatePicker.tsx",
"type": "replace",
"edit_start_line_idx": 89
} | {
"packages": ["docs", "lib"],
"version": "0.0.0"
}
| lerna.json | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00016892135317903012,
0.00016892135317903012,
0.00016892135317903012,
0.00016892135317903012,
0
] |
{
"id": 10,
"code_window": [
" currentMonth: this.props.utils.getStartOfMonth(this.props.date),\n",
" };\n",
"\n",
" public componentDidMount() {\n",
" const {\n",
" date,\n",
" minDate,\n",
" maxDate,\n",
" utils,\n",
" disableFuture,\n",
" disablePast,\n",
" } = this.props;\n",
"\n",
" if (this.shouldDisableDate(date)) {\n",
" this.onDateSelect(\n",
" findClosestEnabledDate({\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { date, minDate, maxDate, utils, disablePast } = this.props;\n"
],
"file_path": "lib/src/DatePicker/components/Calendar.tsx",
"type": "replace",
"edit_start_line_idx": 98
} | {
"build/dist/material-ui-pickers.cjs.js": {
"bundled": 119585,
"minified": 72390,
"gzipped": 14601
},
"build/dist/material-ui-pickers.esm.js": {
"bundled": 114004,
"minified": 66935,
"gzipped": 14397,
"treeshaked": {
"rollup": {
"code": 49272,
"import_statements": 1245
},
"webpack": {
"code": 56057
}
}
},
"build/dist/material-ui-pickers.umd.js": {
"bundled": 230045,
"minified": 100210,
"gzipped": 25280
},
"build/dist/material-ui-pickers.umd.min.js": {
"bundled": 200849,
"minified": 90120,
"gzipped": 23620
}
}
| lib/.size-snapshot.json | 1 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00017406069673597813,
0.00017317401943728328,
0.00017265962378587574,
0.00017298784223385155,
5.768167170572269e-7
] |
{
"id": 10,
"code_window": [
" currentMonth: this.props.utils.getStartOfMonth(this.props.date),\n",
" };\n",
"\n",
" public componentDidMount() {\n",
" const {\n",
" date,\n",
" minDate,\n",
" maxDate,\n",
" utils,\n",
" disableFuture,\n",
" disablePast,\n",
" } = this.props;\n",
"\n",
" if (this.shouldDisableDate(date)) {\n",
" this.onDateSelect(\n",
" findClosestEnabledDate({\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { date, minDate, maxDate, utils, disablePast } = this.props;\n"
],
"file_path": "lib/src/DatePicker/components/Calendar.tsx",
"type": "replace",
"edit_start_line_idx": 98
} | import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { withStyles } from '@material-ui/core/styles';
import prism from 'utils/prism';
const anchorLinkStyle = (theme, size) => ({
'& .anchor-link-style': {
opacity: 0,
// To prevent the link to get the focus.
display: 'none',
},
'&:hover .anchor-link-style': {
display: 'inline-block',
opacity: 1,
padding: `0 ${theme.spacing.unit}px`,
color: theme.palette.text.hint,
'&:hover': {
color: theme.palette.text.secondary,
},
'& svg': {
width: size,
fill: 'currentColor',
},
},
});
const styles = theme => ({
root: {
margin: 0,
fontFamily: theme.typography.fontFamily,
fontSize: '0.9em',
color: theme.palette.text.primary,
backgroundColor: theme.palette.background.paper,
padding: 10,
'& .anchor-link': {
marginTop: -theme.spacing.unit * 12, // Offset for the anchor.
position: 'absolute',
},
'& pre': {
borderRadius: 3,
overflow: 'auto',
margin: 0,
backgroundColor: theme.palette.background.paper,
},
'& code': {
display: 'inline-block',
lineHeight: 1.6,
fontFamily: 'Consolas, "Liberation Mono", Menlo, Courier, monospace',
padding: '3px 6px',
color: theme.palette.text.primary,
fontSize: '0.9em',
backgroundColor: theme.palette.background.paper,
},
'& p code, & ul code, & pre code': {
fontSize: '0.9em',
lineHeight: 1.6,
},
'& h1 code, & h2 code, & h3 code, & h4 code': {
fontSize: 'inherit',
lineHeight: 'inherit',
},
'& h1': {
...theme.typography.h3,
color: theme.palette.text.secondary,
margin: '0.7em 0',
...anchorLinkStyle(theme, 20),
},
'& h2': {
...theme.typography.h4,
color: theme.palette.text.secondary,
margin: '1em 0 0.7em',
...anchorLinkStyle(theme, 18),
},
'& h3': {
...theme.typography.h5,
color: theme.palette.text.secondary,
margin: '1em 0 0.7em',
...anchorLinkStyle(theme, 16),
},
'& h4': {
...theme.typography.h6,
color: theme.palette.text.secondary,
margin: '1em 0 0.7em',
...anchorLinkStyle(theme, 14),
},
'& p, & ul, & ol': {
lineHeight: 1.6,
},
'& table': {
width: '100%',
display: 'block',
overflowX: 'auto',
borderCollapse: 'collapse',
borderSpacing: 0,
overflow: 'hidden',
},
'& thead': {
fontSize: 12,
fontWeight: theme.typography.fontWeightMedium,
color: theme.palette.text.secondary,
},
'& tbody': {
fontSize: 13,
lineHeight: 1.5,
color: theme.palette.text.primary,
},
'& td': {
borderBottom: `1px solid ${theme.palette.text.lightDivider}`,
padding: `${theme.spacing.unit}px ${theme.spacing.unit * 5}px ${
theme.spacing.unit
}px ${theme.spacing.unit * 3}px`,
textAlign: 'left',
},
'& td:last-child': {
paddingRight: theme.spacing.unit * 3,
},
'& td compact': {
paddingRight: theme.spacing.unit * 3,
},
'& td code': {
fontSize: 13,
lineHeight: 1.6,
},
'& th': {
whiteSpace: 'pre',
borderBottom: `1px solid ${theme.palette.text.lightDivider}`,
padding: `0 ${theme.spacing.unit * 5}px 0 ${theme.spacing.unit * 3}px`,
textAlign: 'left',
},
'& th:last-child': {
paddingRight: theme.spacing.unit * 3,
},
'& tr': {
height: 48,
},
'& thead tr': {
height: 64,
},
'& strong': {
fontWeight: theme.typography.fontWeightMedium,
},
'& blockquote': {
borderLeft: `5px solid ${theme.palette.text.hint}`,
background: theme.palette.background.paper,
padding: `${theme.spacing.unit / 2}px ${theme.spacing.unit * 3}px`,
margin: `${theme.spacing.unit * 3}px 0`,
},
'& a, & a code': {
// Style taken from the Link component
color: theme.palette.secondary.A400,
textDecoration: 'none',
'&:hover': {
textDecoration: 'underline',
},
},
},
margin: {
margin: '10px 0 30px',
},
});
const Code = ({ classes, language, text, withMargin }) => {
const hightlightedCode = prism.highlight(text, prism.languages[language]);
return (
<div className={classnames(classes.root, { [classes.margin]: withMargin })}>
<pre>
<code dangerouslySetInnerHTML={{ __html: hightlightedCode }} />
</pre>
</div>
);
};
Code.propTypes = {
classes: PropTypes.object.isRequired,
language: PropTypes.string,
text: PropTypes.string.isRequired,
withMargin: PropTypes.bool,
};
Code.defaultProps = {
withMargin: false,
language: 'jsx',
};
export default withStyles(styles)(Code);
| docs/src/_shared/Code.jsx | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00017803229275159538,
0.00017438923532608896,
0.00016803076141513884,
0.00017480681708548218,
0.0000021878261122765252
] |
{
"id": 10,
"code_window": [
" currentMonth: this.props.utils.getStartOfMonth(this.props.date),\n",
" };\n",
"\n",
" public componentDidMount() {\n",
" const {\n",
" date,\n",
" minDate,\n",
" maxDate,\n",
" utils,\n",
" disableFuture,\n",
" disablePast,\n",
" } = this.props;\n",
"\n",
" if (this.shouldDisableDate(date)) {\n",
" this.onDateSelect(\n",
" findClosestEnabledDate({\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { date, minDate, maxDate, utils, disablePast } = this.props;\n"
],
"file_path": "lib/src/DatePicker/components/Calendar.tsx",
"type": "replace",
"edit_start_line_idx": 98
} | import { ShallowWrapper } from 'enzyme';
import * as React from 'react';
import {
DateTimePickerView,
DateTimePickerViewProps,
} from '../../DateTimePicker/components/DateTimePickerView';
import { shallow } from '../test-utils';
describe('DateTimePickerView', () => {
let component: ShallowWrapper<DateTimePickerViewProps>;
beforeEach(() => {
component = shallow(
<DateTimePickerView classes={{} as any} selected={true}>
foo
</DateTimePickerView>
);
});
it('Should renders', () => {
// console.log(component.debug());
expect(component).toBeTruthy();
});
});
| lib/src/__tests__/DateTimePicker/DateTimePickerView.test.tsx | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.0001862543576862663,
0.0001723606837913394,
0.0001644511939957738,
0.0001663764996919781,
0.000009855703865468968
] |
{
"id": 10,
"code_window": [
" currentMonth: this.props.utils.getStartOfMonth(this.props.date),\n",
" };\n",
"\n",
" public componentDidMount() {\n",
" const {\n",
" date,\n",
" minDate,\n",
" maxDate,\n",
" utils,\n",
" disableFuture,\n",
" disablePast,\n",
" } = this.props;\n",
"\n",
" if (this.shouldDisableDate(date)) {\n",
" this.onDateSelect(\n",
" findClosestEnabledDate({\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { date, minDate, maxDate, utils, disablePast } = this.props;\n"
],
"file_path": "lib/src/DatePicker/components/Calendar.tsx",
"type": "replace",
"edit_start_line_idx": 98
} | /* eslint-disable */
// In production, we register a service worker to serve assets from local cache.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the "N+1" visit to a page, since previously
// cached resources are updated in the background.
// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
// This link also includes instructions on opting out of this behavior.
const isLocalhost = Boolean(window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/,),);
export default function register() {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (!isLocalhost) {
// Is not local host. Just register service worker
registerValidSW(swUrl);
} else {
// This is running on localhost. Lets check if a service worker still exists or not.
checkValidServiceWorker(swUrl);
}
});
}
}
function registerValidSW(swUrl) {
navigator.serviceWorker
.register(swUrl)
.then((registration) => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and
// the fresh content will have been added to the cache.
// It's the perfect time to display a "New content is
// available; please refresh." message in your web app.
console.log('New content is available; please refresh.');
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
}
}
};
};
})
.catch((error) => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then((response) => {
// Ensure service worker exists, and that we really are getting a JS file.
if (
response.status === 404 ||
response.headers.get('content-type').indexOf('javascript') === -1
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then((registration) => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl);
}
})
.catch(() => {
console.log('No internet connection found. App is running in offline mode.',);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then((registration) => {
registration.unregister();
});
}
}
| docs/src/registerServiceWorker.js | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.00017370206478517503,
0.00017043593106791377,
0.00016458594473078847,
0.00017135622329078615,
0.0000024746061626501614
] |
{
"id": 11,
"code_window": [
"\n",
" public render() {\n",
" const { currentMonth, slideDirection } = this.state;\n",
" const { classes, utils, allowKeyboardControl } = this.props;\n",
"\n",
" return (\n",
" <React.Fragment>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { classes, allowKeyboardControl } = this.props;\n"
],
"file_path": "lib/src/DatePicker/components/Calendar.tsx",
"type": "replace",
"edit_start_line_idx": 277
} | {
"build/dist/material-ui-pickers.cjs.js": {
"bundled": 119585,
"minified": 72390,
"gzipped": 14601
},
"build/dist/material-ui-pickers.esm.js": {
"bundled": 114004,
"minified": 66935,
"gzipped": 14397,
"treeshaked": {
"rollup": {
"code": 49272,
"import_statements": 1245
},
"webpack": {
"code": 56057
}
}
},
"build/dist/material-ui-pickers.umd.js": {
"bundled": 230045,
"minified": 100210,
"gzipped": 25280
},
"build/dist/material-ui-pickers.umd.min.js": {
"bundled": 200849,
"minified": 90120,
"gzipped": 23620
}
}
| lib/.size-snapshot.json | 1 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.0001780261954991147,
0.0001747770729707554,
0.00017276847211178392,
0.00017415679758414626,
0.0000019772367068071617
] |
{
"id": 11,
"code_window": [
"\n",
" public render() {\n",
" const { currentMonth, slideDirection } = this.state;\n",
" const { classes, utils, allowKeyboardControl } = this.props;\n",
"\n",
" return (\n",
" <React.Fragment>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { classes, allowKeyboardControl } = this.props;\n"
],
"file_path": "lib/src/DatePicker/components/Calendar.tsx",
"type": "replace",
"edit_start_line_idx": 277
} | import React from 'react';
import SourcablePanel from '_shared/SourcablePanel';
import { Typography } from '@material-ui/core';
const ControllingProgrammatically = () => (
<div>
<Typography variant="h2" gutterBottom>
{' '}
Control programmatically{' '}
</Typography>
<Typography variant="body1" gutterBottom>
Any picker can be controlled by <span className="inline-code"> ref </span>{' '}
property which add an ability open any picker from the code. See an
example below
</Typography>
<SourcablePanel
title="Open from button"
sourceFile="Guides/ControllingProgrammatically.jsx"
/>
</div>
);
export default ControllingProgrammatically;
| docs/src/Pages/Guides/ControllingProgrammatically.jsx | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.0001728063652990386,
0.0001708254567347467,
0.00016941913054324687,
0.00017025087436195463,
0.0000014412838709176867
] |
{
"id": 11,
"code_window": [
"\n",
" public render() {\n",
" const { currentMonth, slideDirection } = this.state;\n",
" const { classes, utils, allowKeyboardControl } = this.props;\n",
"\n",
" return (\n",
" <React.Fragment>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { classes, allowKeyboardControl } = this.props;\n"
],
"file_path": "lib/src/DatePicker/components/Calendar.tsx",
"type": "replace",
"edit_start_line_idx": 277
} | MIT License
Copyright (c) 2017 Dmitriy Kovalenko
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/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.0001761112653184682,
0.00017330907576251775,
0.00017187937919516116,
0.0001719365973258391,
0.0000019815815903712064
] |
{
"id": 11,
"code_window": [
"\n",
" public render() {\n",
" const { currentMonth, slideDirection } = this.state;\n",
" const { classes, utils, allowKeyboardControl } = this.props;\n",
"\n",
" return (\n",
" <React.Fragment>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { classes, allowKeyboardControl } = this.props;\n"
],
"file_path": "lib/src/DatePicker/components/Calendar.tsx",
"type": "replace",
"edit_start_line_idx": 277
} | import React, { Fragment, PureComponent } from 'react';
import { TimePicker } from 'material-ui-pickers';
export default class BasicUsage extends PureComponent {
state = {
selectedDate: new Date(),
}
handleDateChange = (date) => {
this.setState({ selectedDate: date });
}
render() {
const { selectedDate } = this.state;
return (
<Fragment>
<div className="picker">
<TimePicker
seconds
format="hh:mm:ss A"
label="With seconds"
value={selectedDate}
onChange={this.handleDateChange}
/>
</div>
<div className="picker">
<TimePicker
ampm={false}
seconds
format="HH:mm:ss"
label="24 hours with seconds"
value={selectedDate}
onChange={this.handleDateChange}
/>
</div>
</Fragment>
);
}
}
| docs/src/Examples/Demo/TimePicker/SecondsTimePicker.jsx | 0 | https://github.com/mui/material-ui/commit/22d8246b2c6bd65d199c9e6507cc20db2fc5cd1e | [
0.016950711607933044,
0.0035953656770288944,
0.0001671559875831008,
0.0001780261954991147,
0.006678930949419737
] |
{
"id": 0,
"code_window": [
"\n",
"\t\t\tcell.state = CellState.Editing;\n",
"\t\t\tcell.focusMode = CellFocusMode.Editor;\n",
"\t\t} else {\n",
"\t\t\tlet itemDOM = this.list?.domElementAtIndex(index);\n",
"\t\t\tif (document.activeElement && itemDOM && itemDOM.contains(document.activeElement)) {\n",
"\t\t\t\t(document.activeElement as HTMLElement).blur();\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tthis.revealInCenterIfOutsideViewport(cell);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/notebookEditor.ts",
"type": "add",
"edit_start_line_idx": 624
} | /*---------------------------------------------------------------------------------------------
* 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 { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { getResizesObserver } from 'vs/workbench/contrib/notebook/browser/view/renderers/sizeObserver';
import { IOutput, ITransformedDisplayOutputDto, IRenderOutput, CellOutputKind } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { CellRenderTemplate, INotebookEditor, CellFocusMode } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { raceCancellation } from 'vs/base/common/async';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
import { IQuickInputService, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';
import { INotebookService } from 'vs/workbench/contrib/notebook/browser/notebookService';
import { CellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel';
import { CELL_MARGIN, EDITOR_TOP_PADDING, EDITOR_BOTTOM_PADDING } from 'vs/workbench/contrib/notebook/browser/constants';
interface IMimeTypeRenderer extends IQuickPickItem {
index: number;
}
export class CodeCell extends Disposable {
private outputResizeListeners = new Map<IOutput, DisposableStore>();
private outputElements = new Map<IOutput, HTMLElement>();
constructor(
private notebookEditor: INotebookEditor,
private viewCell: CellViewModel,
private templateData: CellRenderTemplate,
@INotebookService private notebookService: INotebookService,
@IQuickInputService private readonly quickInputService: IQuickInputService
) {
super();
let width: number;
const listDimension = notebookEditor.getLayoutInfo();
width = listDimension.width - CELL_MARGIN * 2;
// if (listDimension) {
// } else {
// width = templateData.container.clientWidth - 24 /** for scrollbar and margin right */;
// }
const lineNum = viewCell.lineCount;
const lineHeight = notebookEditor.getLayoutInfo().fontInfo.lineHeight;
const totalHeight = lineNum * lineHeight + EDITOR_TOP_PADDING + EDITOR_BOTTOM_PADDING;
templateData.editor?.layout(
{
width: width,
height: totalHeight
}
);
viewCell.editorHeight = totalHeight;
const cts = new CancellationTokenSource();
this._register({ dispose() { cts.dispose(true); } });
raceCancellation(viewCell.resolveTextModel(), cts.token).then(model => {
if (model && templateData.editor) {
templateData.editor.setModel(model);
viewCell.attachTextEditor(templateData.editor);
if (notebookEditor.getActiveCell() === viewCell) {
templateData.editor?.focus();
}
let realContentHeight = templateData.editor?.getContentHeight();
let width: number;
const listDimension = notebookEditor.getLayoutInfo();
width = listDimension.width - CELL_MARGIN * 2;
// if (listDimension) {
// } else {
// width = templateData.container.clientWidth - 24 /** for scrollbar and margin right */;
// }
if (realContentHeight !== undefined && realContentHeight !== totalHeight) {
templateData.editor?.layout(
{
width: width,
height: realContentHeight
}
);
viewCell.editorHeight = realContentHeight;
}
if (this.notebookEditor.getActiveCell() === this.viewCell) {
templateData.editor?.focus();
}
}
});
this._register(viewCell.onDidChangeFocusMode(() => {
if (viewCell.focusMode === CellFocusMode.Editor) {
templateData.editor?.focus();
}
}));
let cellWidthResizeObserver = getResizesObserver(templateData.cellContainer, {
width: width,
height: totalHeight
}, () => {
let newWidth = cellWidthResizeObserver.getWidth();
let realContentHeight = templateData.editor!.getContentHeight();
templateData.editor?.layout(
{
width: newWidth,
height: realContentHeight
}
);
viewCell.editorHeight = realContentHeight;
});
cellWidthResizeObserver.startObserving();
this._register(cellWidthResizeObserver);
this._register(templateData.editor!.onDidContentSizeChange((e) => {
if (e.contentHeightChanged) {
if (this.viewCell.editorHeight !== e.contentHeight) {
let viewLayout = templateData.editor!.getLayoutInfo();
templateData.editor?.layout(
{
width: viewLayout.width,
height: e.contentHeight
}
);
this.viewCell.editorHeight = e.contentHeight;
notebookEditor.layoutNotebookCell(this.viewCell, viewCell.getCellTotalHeight());
}
}
}));
this._register(templateData.editor!.onDidChangeCursorSelection(() => {
const primarySelection = templateData.editor!.getSelection();
if (primarySelection) {
this.notebookEditor.revealLineInView(viewCell, primarySelection!.positionLineNumber);
}
}));
this._register(viewCell.onDidChangeOutputs((splices) => {
if (!splices.length) {
return;
}
if (this.viewCell.outputs.length) {
this.templateData.outputContainer!.style.display = 'block';
} else {
this.templateData.outputContainer!.style.display = 'none';
}
let reversedSplices = splices.reverse();
reversedSplices.forEach(splice => {
viewCell.spliceOutputHeights(splice[0], splice[1], splice[2].map(_ => 0));
});
let removedKeys: IOutput[] = [];
this.outputElements.forEach((value, key) => {
if (viewCell.outputs.indexOf(key) < 0) {
// already removed
removedKeys.push(key);
// remove element from DOM
this.templateData?.outputContainer?.removeChild(value);
this.notebookEditor.removeInset(key);
}
});
removedKeys.forEach(key => {
// remove element cache
this.outputElements.delete(key);
// remove elment resize listener if there is one
this.outputResizeListeners.delete(key);
});
let prevElement: HTMLElement | undefined = undefined;
this.viewCell.outputs.reverse().forEach(output => {
if (this.outputElements.has(output)) {
// already exist
prevElement = this.outputElements.get(output);
return;
}
// newly added element
let currIndex = this.viewCell.outputs.indexOf(output);
this.renderOutput(output, currIndex, prevElement);
prevElement = this.outputElements.get(output);
});
let editorHeight = templateData.editor!.getContentHeight();
viewCell.editorHeight = editorHeight;
notebookEditor.layoutNotebookCell(viewCell, viewCell.getCellTotalHeight());
}));
if (viewCell.outputs.length > 0) {
this.templateData.outputContainer!.style.display = 'block';
// there are outputs, we need to calcualte their sizes and trigger relayout
// @todo, if there is no resizable output, we should not check their height individually, which hurts the performance
for (let index = 0; index < this.viewCell.outputs.length; index++) {
const currOutput = this.viewCell.outputs[index];
// always add to the end
this.renderOutput(currOutput, index, undefined);
}
viewCell.editorHeight = totalHeight;
this.notebookEditor.layoutNotebookCell(viewCell, viewCell.getCellTotalHeight());
} else {
// noop
this.templateData.outputContainer!.style.display = 'none';
}
}
renderOutput(currOutput: IOutput, index: number, beforeElement?: HTMLElement) {
if (!this.outputResizeListeners.has(currOutput)) {
this.outputResizeListeners.set(currOutput, new DisposableStore());
}
let outputItemDiv = document.createElement('div');
let result: IRenderOutput | undefined = undefined;
if (currOutput.outputKind === CellOutputKind.Rich) {
let transformedDisplayOutput = currOutput as ITransformedDisplayOutputDto;
if (transformedDisplayOutput.orderedMimeTypes.length > 1) {
outputItemDiv.style.position = 'relative';
const mimeTypePicker = DOM.$('.multi-mimetype-output');
DOM.addClasses(mimeTypePicker, 'codicon', 'codicon-list-selection');
outputItemDiv.appendChild(mimeTypePicker);
this.outputResizeListeners.get(currOutput)!.add(DOM.addStandardDisposableListener(mimeTypePicker, 'mousedown', async e => {
e.preventDefault();
e.stopPropagation();
await this.pickActiveMimeTypeRenderer(transformedDisplayOutput);
}));
}
let pickedMimeTypeRenderer = currOutput.orderedMimeTypes[currOutput.pickedMimeTypeIndex];
if (pickedMimeTypeRenderer.isResolved) {
// html
result = this.notebookEditor.getOutputRenderer().render({ outputKind: CellOutputKind.Rich, data: { 'text/html': pickedMimeTypeRenderer.output! } } as any, outputItemDiv, 'text/html');
} else {
result = this.notebookEditor.getOutputRenderer().render(currOutput, outputItemDiv, pickedMimeTypeRenderer.mimeType);
}
} else {
// for text and error, there is no mimetype
result = this.notebookEditor.getOutputRenderer().render(currOutput, outputItemDiv, undefined);
}
if (!result) {
this.viewCell.updateOutputHeight(index, 0);
return;
}
this.outputElements.set(currOutput, outputItemDiv);
if (beforeElement) {
this.templateData.outputContainer?.insertBefore(outputItemDiv, beforeElement);
} else {
this.templateData.outputContainer?.appendChild(outputItemDiv);
}
if (result.shadowContent) {
this.viewCell.selfSizeMonitoring = true;
let editorHeight = this.viewCell.editorHeight;
this.notebookEditor.createInset(this.viewCell, currOutput, result.shadowContent, editorHeight + 8 + this.viewCell.getOutputOffset(index));
} else {
DOM.addClass(outputItemDiv, 'foreground');
}
let hasDynamicHeight = result.hasDynamicHeight;
if (hasDynamicHeight) {
let clientHeight = outputItemDiv.clientHeight;
let listDimension = this.notebookEditor.getLayoutInfo();
let dimension = listDimension ? {
width: listDimension.width - CELL_MARGIN * 2,
height: clientHeight
} : undefined;
const elementSizeObserver = getResizesObserver(outputItemDiv, dimension, () => {
if (this.templateData.outputContainer && document.body.contains(this.templateData.outputContainer!)) {
let height = elementSizeObserver.getHeight() + 8 * 2; // include padding
if (clientHeight === height) {
// console.log(this.viewCell.outputs);
return;
}
const currIndex = this.viewCell.outputs.indexOf(currOutput);
if (currIndex < 0) {
return;
}
this.viewCell.updateOutputHeight(currIndex, height);
this.notebookEditor.layoutNotebookCell(this.viewCell, this.viewCell.getCellTotalHeight());
}
});
elementSizeObserver.startObserving();
this.outputResizeListeners.get(currOutput)!.add(elementSizeObserver);
this.viewCell.updateOutputHeight(index, clientHeight);
} else {
if (result.shadowContent) {
// webview
// noop
// let cachedHeight = this.viewCell.getOutputHeight(currOutput);
} else {
// static output
// @TODO, if we stop checking output height, we need to evaluate it later when checking the height of output container
let clientHeight = outputItemDiv.clientHeight;
this.viewCell.updateOutputHeight(index, clientHeight);
}
}
}
generateRendererInfo(renderId: number | undefined): string {
if (renderId === undefined || renderId === -1) {
return 'builtin';
}
let renderInfo = this.notebookService.getRendererInfo(renderId);
if (renderInfo) {
return renderInfo.id.value;
}
return 'builtin';
}
async pickActiveMimeTypeRenderer(output: ITransformedDisplayOutputDto) {
let currIndex = output.pickedMimeTypeIndex;
const items = output.orderedMimeTypes.map((mimeType, index): IMimeTypeRenderer => ({
label: mimeType.mimeType,
id: mimeType.mimeType,
index: index,
picked: index === currIndex,
description: this.generateRendererInfo(mimeType.rendererId) + (index === currIndex
? nls.localize('curruentActiveMimeType', " (Currently Active)")
: ''),
}));
const picker = this.quickInputService.createQuickPick();
picker.items = items;
picker.activeItems = items.filter(item => !!item.picked);
picker.placeholder = nls.localize('promptChooseMimeType.placeHolder', "Select output mimetype to render for current output");
const pick = await new Promise<number | undefined>(resolve => {
picker.onDidAccept(() => {
resolve(picker.selectedItems.length === 1 ? (picker.selectedItems[0] as IMimeTypeRenderer).index : undefined);
picker.dispose();
});
picker.show();
});
if (pick === undefined) {
return;
}
if (pick !== currIndex) {
// user chooses another mimetype
let index = this.viewCell.outputs.indexOf(output);
let nextElement = index + 1 < this.viewCell.outputs.length ? this.outputElements.get(this.viewCell.outputs[index + 1]) : undefined;
this.outputResizeListeners.get(output)?.clear();
let element = this.outputElements.get(output);
if (element) {
this.templateData?.outputContainer?.removeChild(element);
this.notebookEditor.removeInset(output);
}
output.pickedMimeTypeIndex = pick;
this.renderOutput(output, index, nextElement);
this.notebookEditor.layoutNotebookCell(this.viewCell, this.viewCell.getCellTotalHeight());
}
}
dispose() {
this.viewCell.detachTextEditor();
this.outputResizeListeners.forEach((value) => {
value.dispose();
});
super.dispose();
}
}
| src/vs/workbench/contrib/notebook/browser/view/renderers/codeCell.ts | 1 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.000767202116549015,
0.0002200846647610888,
0.00016503302322234958,
0.00017036031931638718,
0.00013125623809173703
] |
{
"id": 0,
"code_window": [
"\n",
"\t\t\tcell.state = CellState.Editing;\n",
"\t\t\tcell.focusMode = CellFocusMode.Editor;\n",
"\t\t} else {\n",
"\t\t\tlet itemDOM = this.list?.domElementAtIndex(index);\n",
"\t\t\tif (document.activeElement && itemDOM && itemDOM.contains(document.activeElement)) {\n",
"\t\t\t\t(document.activeElement as HTMLElement).blur();\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tthis.revealInCenterIfOutsideViewport(cell);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/notebookEditor.ts",
"type": "add",
"edit_start_line_idx": 624
} | {
"name": "gulp",
"publisher": "vscode",
"description": "%description%",
"displayName": "%displayName%",
"version": "1.0.0",
"icon": "images/gulp.png",
"license": "MIT",
"engines": {
"vscode": "*"
},
"categories": [
"Other"
],
"scripts": {
"compile": "gulp compile-extension:gulp",
"watch": "gulp watch-extension:gulp"
},
"dependencies": {
"vscode-nls": "^4.0.0"
},
"devDependencies": {
"@types/node": "^12.11.7"
},
"main": "./out/main",
"activationEvents": [
"onCommand:workbench.action.tasks.runTask"
],
"contributes": {
"configuration": {
"id": "gulp",
"type": "object",
"title": "Gulp",
"properties": {
"gulp.autoDetect": {
"scope": "resource",
"type": "string",
"enum": [
"off",
"on"
],
"default": "on",
"description": "%config.gulp.autoDetect%"
}
}
},
"taskDefinitions": [
{
"type": "gulp",
"required": [
"task"
],
"properties": {
"task": {
"type": "string",
"description": "%gulp.taskDefinition.type.description%"
},
"file": {
"type": "string",
"description": "%gulp.taskDefinition.file.description%"
}
}
}
]
}
}
| extensions/gulp/package.json | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.0001802531915018335,
0.00017757939349394292,
0.00017504533752799034,
0.00017784262308850884,
0.0000015410106470881146
] |
{
"id": 0,
"code_window": [
"\n",
"\t\t\tcell.state = CellState.Editing;\n",
"\t\t\tcell.focusMode = CellFocusMode.Editor;\n",
"\t\t} else {\n",
"\t\t\tlet itemDOM = this.list?.domElementAtIndex(index);\n",
"\t\t\tif (document.activeElement && itemDOM && itemDOM.contains(document.activeElement)) {\n",
"\t\t\t\t(document.activeElement as HTMLElement).blur();\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tthis.revealInCenterIfOutsideViewport(cell);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/notebookEditor.ts",
"type": "add",
"edit_start_line_idx": 624
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as eslint from 'eslint';
import { TSESTree } from '@typescript-eslint/experimental-utils';
export = new class ApiInterfaceNaming implements eslint.Rule.RuleModule {
private static _nameRegExp = /I[A-Z]/;
readonly meta: eslint.Rule.RuleMetaData = {
messages: {
naming: 'Interfaces must not be prefixed with uppercase `I`',
}
};
create(context: eslint.Rule.RuleContext): eslint.Rule.RuleListener {
return {
['TSInterfaceDeclaration Identifier']: (node: any) => {
const name = (<TSESTree.Identifier>node).name;
if (ApiInterfaceNaming._nameRegExp.test(name)) {
context.report({
node,
messageId: 'naming'
});
}
}
};
}
};
| build/lib/eslint/vscode-dts-interface-naming.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.00017640789155848324,
0.0001750075607560575,
0.00017316990124527365,
0.0001752262469381094,
0.0000012130153663747478
] |
{
"id": 0,
"code_window": [
"\n",
"\t\t\tcell.state = CellState.Editing;\n",
"\t\t\tcell.focusMode = CellFocusMode.Editor;\n",
"\t\t} else {\n",
"\t\t\tlet itemDOM = this.list?.domElementAtIndex(index);\n",
"\t\t\tif (document.activeElement && itemDOM && itemDOM.contains(document.activeElement)) {\n",
"\t\t\t\t(document.activeElement as HTMLElement).blur();\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tthis.revealInCenterIfOutsideViewport(cell);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/notebookEditor.ts",
"type": "add",
"edit_start_line_idx": 624
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import assert = require('assert');
import i18n = require('../i18n');
suite('XLF Parser Tests', () => {
const sampleXlf = '<?xml version="1.0" encoding="utf-8"?><xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"><file original="vs/base/common/keybinding" source-language="en" datatype="plaintext"><body><trans-unit id="key1"><source xml:lang="en">Key #1</source></trans-unit><trans-unit id="key2"><source xml:lang="en">Key #2 &</source></trans-unit></body></file></xliff>';
const sampleTranslatedXlf = '<?xml version="1.0" encoding="utf-8"?><xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"><file original="vs/base/common/keybinding" source-language="en" target-language="ru" datatype="plaintext"><body><trans-unit id="key1"><source xml:lang="en">Key #1</source><target>Кнопка #1</target></trans-unit><trans-unit id="key2"><source xml:lang="en">Key #2 &</source><target>Кнопка #2 &</target></trans-unit></body></file></xliff>';
const originalFilePath = 'vs/base/common/keybinding';
const keys = ['key1', 'key2'];
const messages = ['Key #1', 'Key #2 &'];
const translatedMessages = { key1: 'Кнопка #1', key2: 'Кнопка #2 &' };
test('Keys & messages to XLF conversion', () => {
const xlf = new i18n.XLF('vscode-workbench');
xlf.addFile(originalFilePath, keys, messages);
const xlfString = xlf.toString();
assert.strictEqual(xlfString.replace(/\s{2,}/g, ''), sampleXlf);
});
test('XLF to keys & messages conversion', () => {
i18n.XLF.parse(sampleTranslatedXlf).then(function(resolvedFiles) {
assert.deepEqual(resolvedFiles[0].messages, translatedMessages);
assert.strictEqual(resolvedFiles[0].originalFilePath, originalFilePath);
});
});
test('JSON file source path to Transifex resource match', () => {
const editorProject: string = 'vscode-editor',
workbenchProject: string = 'vscode-workbench';
const platform: i18n.Resource = { name: 'vs/platform', project: editorProject },
editorContrib = { name: 'vs/editor/contrib', project: editorProject },
editor = { name: 'vs/editor', project: editorProject },
base = { name: 'vs/base', project: editorProject },
code = { name: 'vs/code', project: workbenchProject },
workbenchParts = { name: 'vs/workbench/contrib/html', project: workbenchProject },
workbenchServices = { name: 'vs/workbench/services/textfile', project: workbenchProject },
workbench = { name: 'vs/workbench', project: workbenchProject};
assert.deepEqual(i18n.getResource('vs/platform/actions/browser/menusExtensionPoint'), platform);
assert.deepEqual(i18n.getResource('vs/editor/contrib/clipboard/browser/clipboard'), editorContrib);
assert.deepEqual(i18n.getResource('vs/editor/common/modes/modesRegistry'), editor);
assert.deepEqual(i18n.getResource('vs/base/common/errorMessage'), base);
assert.deepEqual(i18n.getResource('vs/code/electron-main/window'), code);
assert.deepEqual(i18n.getResource('vs/workbench/contrib/html/browser/webview'), workbenchParts);
assert.deepEqual(i18n.getResource('vs/workbench/services/textfile/node/testFileService'), workbenchServices);
assert.deepEqual(i18n.getResource('vs/workbench/browser/parts/panel/panelActions'), workbench);
});
}); | build/lib/test/i18n.test.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.00017878743528854102,
0.00017523094720672816,
0.00017130117339547724,
0.00017542279965709895,
0.000002511668526494759
] |
{
"id": 1,
"code_window": [
"\n",
"\t\t\tthis.list?.setFocus([index]);\n",
"\t\t\tthis.list?.setSelection([index]);\n",
"\t\t\tthis.list?.focusView();\n",
"\t\t}\n",
"\t}\n",
"\n",
"\t//#endregion\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tthis.revealInCenterIfOutsideViewport(cell);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/notebookEditor.ts",
"type": "add",
"edit_start_line_idx": 635
} | /*---------------------------------------------------------------------------------------------
* 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 { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { getResizesObserver } from 'vs/workbench/contrib/notebook/browser/view/renderers/sizeObserver';
import { IOutput, ITransformedDisplayOutputDto, IRenderOutput, CellOutputKind } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { CellRenderTemplate, INotebookEditor, CellFocusMode } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { raceCancellation } from 'vs/base/common/async';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
import { IQuickInputService, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';
import { INotebookService } from 'vs/workbench/contrib/notebook/browser/notebookService';
import { CellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel';
import { CELL_MARGIN, EDITOR_TOP_PADDING, EDITOR_BOTTOM_PADDING } from 'vs/workbench/contrib/notebook/browser/constants';
interface IMimeTypeRenderer extends IQuickPickItem {
index: number;
}
export class CodeCell extends Disposable {
private outputResizeListeners = new Map<IOutput, DisposableStore>();
private outputElements = new Map<IOutput, HTMLElement>();
constructor(
private notebookEditor: INotebookEditor,
private viewCell: CellViewModel,
private templateData: CellRenderTemplate,
@INotebookService private notebookService: INotebookService,
@IQuickInputService private readonly quickInputService: IQuickInputService
) {
super();
let width: number;
const listDimension = notebookEditor.getLayoutInfo();
width = listDimension.width - CELL_MARGIN * 2;
// if (listDimension) {
// } else {
// width = templateData.container.clientWidth - 24 /** for scrollbar and margin right */;
// }
const lineNum = viewCell.lineCount;
const lineHeight = notebookEditor.getLayoutInfo().fontInfo.lineHeight;
const totalHeight = lineNum * lineHeight + EDITOR_TOP_PADDING + EDITOR_BOTTOM_PADDING;
templateData.editor?.layout(
{
width: width,
height: totalHeight
}
);
viewCell.editorHeight = totalHeight;
const cts = new CancellationTokenSource();
this._register({ dispose() { cts.dispose(true); } });
raceCancellation(viewCell.resolveTextModel(), cts.token).then(model => {
if (model && templateData.editor) {
templateData.editor.setModel(model);
viewCell.attachTextEditor(templateData.editor);
if (notebookEditor.getActiveCell() === viewCell) {
templateData.editor?.focus();
}
let realContentHeight = templateData.editor?.getContentHeight();
let width: number;
const listDimension = notebookEditor.getLayoutInfo();
width = listDimension.width - CELL_MARGIN * 2;
// if (listDimension) {
// } else {
// width = templateData.container.clientWidth - 24 /** for scrollbar and margin right */;
// }
if (realContentHeight !== undefined && realContentHeight !== totalHeight) {
templateData.editor?.layout(
{
width: width,
height: realContentHeight
}
);
viewCell.editorHeight = realContentHeight;
}
if (this.notebookEditor.getActiveCell() === this.viewCell) {
templateData.editor?.focus();
}
}
});
this._register(viewCell.onDidChangeFocusMode(() => {
if (viewCell.focusMode === CellFocusMode.Editor) {
templateData.editor?.focus();
}
}));
let cellWidthResizeObserver = getResizesObserver(templateData.cellContainer, {
width: width,
height: totalHeight
}, () => {
let newWidth = cellWidthResizeObserver.getWidth();
let realContentHeight = templateData.editor!.getContentHeight();
templateData.editor?.layout(
{
width: newWidth,
height: realContentHeight
}
);
viewCell.editorHeight = realContentHeight;
});
cellWidthResizeObserver.startObserving();
this._register(cellWidthResizeObserver);
this._register(templateData.editor!.onDidContentSizeChange((e) => {
if (e.contentHeightChanged) {
if (this.viewCell.editorHeight !== e.contentHeight) {
let viewLayout = templateData.editor!.getLayoutInfo();
templateData.editor?.layout(
{
width: viewLayout.width,
height: e.contentHeight
}
);
this.viewCell.editorHeight = e.contentHeight;
notebookEditor.layoutNotebookCell(this.viewCell, viewCell.getCellTotalHeight());
}
}
}));
this._register(templateData.editor!.onDidChangeCursorSelection(() => {
const primarySelection = templateData.editor!.getSelection();
if (primarySelection) {
this.notebookEditor.revealLineInView(viewCell, primarySelection!.positionLineNumber);
}
}));
this._register(viewCell.onDidChangeOutputs((splices) => {
if (!splices.length) {
return;
}
if (this.viewCell.outputs.length) {
this.templateData.outputContainer!.style.display = 'block';
} else {
this.templateData.outputContainer!.style.display = 'none';
}
let reversedSplices = splices.reverse();
reversedSplices.forEach(splice => {
viewCell.spliceOutputHeights(splice[0], splice[1], splice[2].map(_ => 0));
});
let removedKeys: IOutput[] = [];
this.outputElements.forEach((value, key) => {
if (viewCell.outputs.indexOf(key) < 0) {
// already removed
removedKeys.push(key);
// remove element from DOM
this.templateData?.outputContainer?.removeChild(value);
this.notebookEditor.removeInset(key);
}
});
removedKeys.forEach(key => {
// remove element cache
this.outputElements.delete(key);
// remove elment resize listener if there is one
this.outputResizeListeners.delete(key);
});
let prevElement: HTMLElement | undefined = undefined;
this.viewCell.outputs.reverse().forEach(output => {
if (this.outputElements.has(output)) {
// already exist
prevElement = this.outputElements.get(output);
return;
}
// newly added element
let currIndex = this.viewCell.outputs.indexOf(output);
this.renderOutput(output, currIndex, prevElement);
prevElement = this.outputElements.get(output);
});
let editorHeight = templateData.editor!.getContentHeight();
viewCell.editorHeight = editorHeight;
notebookEditor.layoutNotebookCell(viewCell, viewCell.getCellTotalHeight());
}));
if (viewCell.outputs.length > 0) {
this.templateData.outputContainer!.style.display = 'block';
// there are outputs, we need to calcualte their sizes and trigger relayout
// @todo, if there is no resizable output, we should not check their height individually, which hurts the performance
for (let index = 0; index < this.viewCell.outputs.length; index++) {
const currOutput = this.viewCell.outputs[index];
// always add to the end
this.renderOutput(currOutput, index, undefined);
}
viewCell.editorHeight = totalHeight;
this.notebookEditor.layoutNotebookCell(viewCell, viewCell.getCellTotalHeight());
} else {
// noop
this.templateData.outputContainer!.style.display = 'none';
}
}
renderOutput(currOutput: IOutput, index: number, beforeElement?: HTMLElement) {
if (!this.outputResizeListeners.has(currOutput)) {
this.outputResizeListeners.set(currOutput, new DisposableStore());
}
let outputItemDiv = document.createElement('div');
let result: IRenderOutput | undefined = undefined;
if (currOutput.outputKind === CellOutputKind.Rich) {
let transformedDisplayOutput = currOutput as ITransformedDisplayOutputDto;
if (transformedDisplayOutput.orderedMimeTypes.length > 1) {
outputItemDiv.style.position = 'relative';
const mimeTypePicker = DOM.$('.multi-mimetype-output');
DOM.addClasses(mimeTypePicker, 'codicon', 'codicon-list-selection');
outputItemDiv.appendChild(mimeTypePicker);
this.outputResizeListeners.get(currOutput)!.add(DOM.addStandardDisposableListener(mimeTypePicker, 'mousedown', async e => {
e.preventDefault();
e.stopPropagation();
await this.pickActiveMimeTypeRenderer(transformedDisplayOutput);
}));
}
let pickedMimeTypeRenderer = currOutput.orderedMimeTypes[currOutput.pickedMimeTypeIndex];
if (pickedMimeTypeRenderer.isResolved) {
// html
result = this.notebookEditor.getOutputRenderer().render({ outputKind: CellOutputKind.Rich, data: { 'text/html': pickedMimeTypeRenderer.output! } } as any, outputItemDiv, 'text/html');
} else {
result = this.notebookEditor.getOutputRenderer().render(currOutput, outputItemDiv, pickedMimeTypeRenderer.mimeType);
}
} else {
// for text and error, there is no mimetype
result = this.notebookEditor.getOutputRenderer().render(currOutput, outputItemDiv, undefined);
}
if (!result) {
this.viewCell.updateOutputHeight(index, 0);
return;
}
this.outputElements.set(currOutput, outputItemDiv);
if (beforeElement) {
this.templateData.outputContainer?.insertBefore(outputItemDiv, beforeElement);
} else {
this.templateData.outputContainer?.appendChild(outputItemDiv);
}
if (result.shadowContent) {
this.viewCell.selfSizeMonitoring = true;
let editorHeight = this.viewCell.editorHeight;
this.notebookEditor.createInset(this.viewCell, currOutput, result.shadowContent, editorHeight + 8 + this.viewCell.getOutputOffset(index));
} else {
DOM.addClass(outputItemDiv, 'foreground');
}
let hasDynamicHeight = result.hasDynamicHeight;
if (hasDynamicHeight) {
let clientHeight = outputItemDiv.clientHeight;
let listDimension = this.notebookEditor.getLayoutInfo();
let dimension = listDimension ? {
width: listDimension.width - CELL_MARGIN * 2,
height: clientHeight
} : undefined;
const elementSizeObserver = getResizesObserver(outputItemDiv, dimension, () => {
if (this.templateData.outputContainer && document.body.contains(this.templateData.outputContainer!)) {
let height = elementSizeObserver.getHeight() + 8 * 2; // include padding
if (clientHeight === height) {
// console.log(this.viewCell.outputs);
return;
}
const currIndex = this.viewCell.outputs.indexOf(currOutput);
if (currIndex < 0) {
return;
}
this.viewCell.updateOutputHeight(currIndex, height);
this.notebookEditor.layoutNotebookCell(this.viewCell, this.viewCell.getCellTotalHeight());
}
});
elementSizeObserver.startObserving();
this.outputResizeListeners.get(currOutput)!.add(elementSizeObserver);
this.viewCell.updateOutputHeight(index, clientHeight);
} else {
if (result.shadowContent) {
// webview
// noop
// let cachedHeight = this.viewCell.getOutputHeight(currOutput);
} else {
// static output
// @TODO, if we stop checking output height, we need to evaluate it later when checking the height of output container
let clientHeight = outputItemDiv.clientHeight;
this.viewCell.updateOutputHeight(index, clientHeight);
}
}
}
generateRendererInfo(renderId: number | undefined): string {
if (renderId === undefined || renderId === -1) {
return 'builtin';
}
let renderInfo = this.notebookService.getRendererInfo(renderId);
if (renderInfo) {
return renderInfo.id.value;
}
return 'builtin';
}
async pickActiveMimeTypeRenderer(output: ITransformedDisplayOutputDto) {
let currIndex = output.pickedMimeTypeIndex;
const items = output.orderedMimeTypes.map((mimeType, index): IMimeTypeRenderer => ({
label: mimeType.mimeType,
id: mimeType.mimeType,
index: index,
picked: index === currIndex,
description: this.generateRendererInfo(mimeType.rendererId) + (index === currIndex
? nls.localize('curruentActiveMimeType', " (Currently Active)")
: ''),
}));
const picker = this.quickInputService.createQuickPick();
picker.items = items;
picker.activeItems = items.filter(item => !!item.picked);
picker.placeholder = nls.localize('promptChooseMimeType.placeHolder', "Select output mimetype to render for current output");
const pick = await new Promise<number | undefined>(resolve => {
picker.onDidAccept(() => {
resolve(picker.selectedItems.length === 1 ? (picker.selectedItems[0] as IMimeTypeRenderer).index : undefined);
picker.dispose();
});
picker.show();
});
if (pick === undefined) {
return;
}
if (pick !== currIndex) {
// user chooses another mimetype
let index = this.viewCell.outputs.indexOf(output);
let nextElement = index + 1 < this.viewCell.outputs.length ? this.outputElements.get(this.viewCell.outputs[index + 1]) : undefined;
this.outputResizeListeners.get(output)?.clear();
let element = this.outputElements.get(output);
if (element) {
this.templateData?.outputContainer?.removeChild(element);
this.notebookEditor.removeInset(output);
}
output.pickedMimeTypeIndex = pick;
this.renderOutput(output, index, nextElement);
this.notebookEditor.layoutNotebookCell(this.viewCell, this.viewCell.getCellTotalHeight());
}
}
dispose() {
this.viewCell.detachTextEditor();
this.outputResizeListeners.forEach((value) => {
value.dispose();
});
super.dispose();
}
}
| src/vs/workbench/contrib/notebook/browser/view/renderers/codeCell.ts | 1 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.001851900015026331,
0.000247406103881076,
0.00016399644664488733,
0.00017123454017564654,
0.0003102315531577915
] |
{
"id": 1,
"code_window": [
"\n",
"\t\t\tthis.list?.setFocus([index]);\n",
"\t\t\tthis.list?.setSelection([index]);\n",
"\t\t\tthis.list?.focusView();\n",
"\t\t}\n",
"\t}\n",
"\n",
"\t//#endregion\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tthis.revealInCenterIfOutsideViewport(cell);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/notebookEditor.ts",
"type": "add",
"edit_start_line_idx": 635
} | #!/usr/bin/env bash
set -e
echo 'noop' | build/azure-pipelines/linux/multiarch/alpine/build.sh | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.00017107265011873096,
0.00017107265011873096,
0.00017107265011873096,
0.00017107265011873096,
0
] |
{
"id": 1,
"code_window": [
"\n",
"\t\t\tthis.list?.setFocus([index]);\n",
"\t\t\tthis.list?.setSelection([index]);\n",
"\t\t\tthis.list?.focusView();\n",
"\t\t}\n",
"\t}\n",
"\n",
"\t//#endregion\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tthis.revealInCenterIfOutsideViewport(cell);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/notebookEditor.ts",
"type": "add",
"edit_start_line_idx": 635
} | /*---------------------------------------------------------------------------------------------
* 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 { CommandsRegistry } from 'vs/platform/commands/common/commands';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IModeService } from 'vs/editor/common/services/modeService';
import { extname } from 'vs/base/common/path';
import { MenuRegistry, MenuId } from 'vs/platform/actions/common/actions';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { URI } from 'vs/base/common/uri';
import { ISnippetsService } from 'vs/workbench/contrib/snippets/browser/snippets.contribution';
import { IQuickPickItem, IQuickInputService, QuickPickInput } from 'vs/platform/quickinput/common/quickInput';
import { SnippetSource } from 'vs/workbench/contrib/snippets/browser/snippetsFile';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IFileService } from 'vs/platform/files/common/files';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { isValidBasename } from 'vs/base/common/extpath';
import { joinPath, basename } from 'vs/base/common/resources';
const id = 'workbench.action.openSnippets';
namespace ISnippetPick {
export function is(thing: object): thing is ISnippetPick {
return thing && URI.isUri((<ISnippetPick>thing).filepath);
}
}
interface ISnippetPick extends IQuickPickItem {
filepath: URI;
hint?: true;
}
async function computePicks(snippetService: ISnippetsService, envService: IEnvironmentService, modeService: IModeService) {
const existing: ISnippetPick[] = [];
const future: ISnippetPick[] = [];
const seen = new Set<string>();
for (const file of await snippetService.getSnippetFiles()) {
if (file.source === SnippetSource.Extension) {
// skip extension snippets
continue;
}
if (file.isGlobalSnippets) {
await file.load();
// list scopes for global snippets
const names = new Set<string>();
outer: for (const snippet of file.data) {
for (const scope of snippet.scopes) {
const name = modeService.getLanguageName(scope);
if (name) {
if (names.size >= 4) {
names.add(`${name}...`);
break outer;
} else {
names.add(name);
}
}
}
}
existing.push({
label: basename(file.location),
filepath: file.location,
description: names.size === 0
? nls.localize('global.scope', "(global)")
: nls.localize('global.1', "({0})", [...names].join(', '))
});
} else {
// language snippet
const mode = basename(file.location).replace(/\.json$/, '');
existing.push({
label: basename(file.location),
description: `(${modeService.getLanguageName(mode)})`,
filepath: file.location
});
seen.add(mode);
}
}
const dir = joinPath(envService.userRoamingDataHome, 'snippets');
for (const mode of modeService.getRegisteredModes()) {
const label = modeService.getLanguageName(mode);
if (label && !seen.has(mode)) {
future.push({
label: mode,
description: `(${label})`,
filepath: joinPath(dir, `${mode}.json`),
hint: true
});
}
}
existing.sort((a, b) => {
let a_ext = extname(a.filepath.path);
let b_ext = extname(b.filepath.path);
if (a_ext === b_ext) {
return a.label.localeCompare(b.label);
} else if (a_ext === '.code-snippets') {
return -1;
} else {
return 1;
}
});
future.sort((a, b) => {
return a.label.localeCompare(b.label);
});
return { existing, future };
}
async function createSnippetFile(scope: string, defaultPath: URI, quickInputService: IQuickInputService, fileService: IFileService, textFileService: ITextFileService, opener: IOpenerService) {
function createSnippetUri(input: string) {
const filename = extname(input) !== '.code-snippets'
? `${input}.code-snippets`
: input;
return joinPath(defaultPath, filename);
}
await fileService.createFolder(defaultPath);
const input = await quickInputService.input({
placeHolder: nls.localize('name', "Type snippet file name"),
async validateInput(input) {
if (!input) {
return nls.localize('bad_name1', "Invalid file name");
}
if (!isValidBasename(input)) {
return nls.localize('bad_name2', "'{0}' is not a valid file name", input);
}
if (await fileService.exists(createSnippetUri(input))) {
return nls.localize('bad_name3', "'{0}' already exists", input);
}
return undefined;
}
});
if (!input) {
return undefined;
}
const resource = createSnippetUri(input);
await textFileService.write(resource, [
'{',
'\t// Place your ' + scope + ' snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and ',
'\t// description. Add comma separated ids of the languages where the snippet is applicable in the scope field. If scope ',
'\t// is left empty or omitted, the snippet gets applied to all languages. The prefix is what is ',
'\t// used to trigger the snippet and the body will be expanded and inserted. Possible variables are: ',
'\t// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. ',
'\t// Placeholders with the same ids are connected.',
'\t// Example:',
'\t// "Print to console": {',
'\t// \t"scope": "javascript,typescript",',
'\t// \t"prefix": "log",',
'\t// \t"body": [',
'\t// \t\t"console.log(\'$1\');",',
'\t// \t\t"$2"',
'\t// \t],',
'\t// \t"description": "Log output to console"',
'\t// }',
'}'
].join('\n'));
await opener.open(resource);
return undefined;
}
async function createLanguageSnippetFile(pick: ISnippetPick, fileService: IFileService, textFileService: ITextFileService) {
if (await fileService.exists(pick.filepath)) {
return;
}
const contents = [
'{',
'\t// Place your snippets for ' + pick.label + ' here. Each snippet is defined under a snippet name and has a prefix, body and ',
'\t// description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:',
'\t// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the ',
'\t// same ids are connected.',
'\t// Example:',
'\t// "Print to console": {',
'\t// \t"prefix": "log",',
'\t// \t"body": [',
'\t// \t\t"console.log(\'$1\');",',
'\t// \t\t"$2"',
'\t// \t],',
'\t// \t"description": "Log output to console"',
'\t// }',
'}'
].join('\n');
await textFileService.write(pick.filepath, contents);
}
CommandsRegistry.registerCommand(id, async (accessor): Promise<any> => {
const snippetService = accessor.get(ISnippetsService);
const quickInputService = accessor.get(IQuickInputService);
const opener = accessor.get(IOpenerService);
const modeService = accessor.get(IModeService);
const envService = accessor.get(IEnvironmentService);
const workspaceService = accessor.get(IWorkspaceContextService);
const fileService = accessor.get(IFileService);
const textFileService = accessor.get(ITextFileService);
const picks = await computePicks(snippetService, envService, modeService);
const existing: QuickPickInput[] = picks.existing;
type SnippetPick = IQuickPickItem & { uri: URI } & { scope: string };
const globalSnippetPicks: SnippetPick[] = [{
scope: nls.localize('new.global_scope', 'global'),
label: nls.localize('new.global', "New Global Snippets file..."),
uri: joinPath(envService.userRoamingDataHome, 'snippets')
}];
const workspaceSnippetPicks: SnippetPick[] = [];
for (const folder of workspaceService.getWorkspace().folders) {
workspaceSnippetPicks.push({
scope: nls.localize('new.workspace_scope', "{0} workspace", folder.name),
label: nls.localize('new.folder', "New Snippets file for '{0}'...", folder.name),
uri: folder.toResource('.vscode')
});
}
if (existing.length > 0) {
existing.unshift({ type: 'separator', label: nls.localize('group.global', "Existing Snippets") });
existing.push({ type: 'separator', label: nls.localize('new.global.sep', "New Snippets") });
} else {
existing.push({ type: 'separator', label: nls.localize('new.global.sep', "New Snippets") });
}
const pick = await quickInputService.pick(([] as QuickPickInput[]).concat(existing, globalSnippetPicks, workspaceSnippetPicks, picks.future), {
placeHolder: nls.localize('openSnippet.pickLanguage', "Select Snippets File or Create Snippets"),
matchOnDescription: true
});
if (globalSnippetPicks.indexOf(pick as SnippetPick) >= 0) {
return createSnippetFile((pick as SnippetPick).scope, (pick as SnippetPick).uri, quickInputService, fileService, textFileService, opener);
} else if (workspaceSnippetPicks.indexOf(pick as SnippetPick) >= 0) {
return createSnippetFile((pick as SnippetPick).scope, (pick as SnippetPick).uri, quickInputService, fileService, textFileService, opener);
} else if (ISnippetPick.is(pick)) {
if (pick.hint) {
await createLanguageSnippetFile(pick, fileService, textFileService);
}
return opener.open(pick.filepath);
}
});
MenuRegistry.appendMenuItem(MenuId.CommandPalette, {
command: {
id,
title: { value: nls.localize('openSnippet.label', "Configure User Snippets"), original: 'Configure User Snippets' },
category: { value: nls.localize('preferences', "Preferences"), original: 'Preferences' }
}
});
MenuRegistry.appendMenuItem(MenuId.MenubarPreferencesMenu, {
group: '3_snippets',
command: {
id,
title: nls.localize({ key: 'miOpenSnippets', comment: ['&& denotes a mnemonic'] }, "User &&Snippets")
},
order: 1
});
MenuRegistry.appendMenuItem(MenuId.GlobalActivity, {
group: '3_snippets',
command: {
id,
title: nls.localize('userSnippets', "User Snippets")
},
order: 1
});
| src/vs/workbench/contrib/snippets/browser/configureSnippets.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.0001783217885531485,
0.0001734063698677346,
0.00016792328096926212,
0.00017382104124408215,
0.0000025257672859879676
] |
{
"id": 1,
"code_window": [
"\n",
"\t\t\tthis.list?.setFocus([index]);\n",
"\t\t\tthis.list?.setSelection([index]);\n",
"\t\t\tthis.list?.focusView();\n",
"\t\t}\n",
"\t}\n",
"\n",
"\t//#endregion\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tthis.revealInCenterIfOutsideViewport(cell);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/notebookEditor.ts",
"type": "add",
"edit_start_line_idx": 635
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { delta as arrayDelta, mapArrayOrNot } from 'vs/base/common/arrays';
import { Barrier } from 'vs/base/common/async';
import { CancellationToken } from 'vs/base/common/cancellation';
import { Emitter, Event } from 'vs/base/common/event';
import { TernarySearchTree } from 'vs/base/common/map';
import { Schemas } from 'vs/base/common/network';
import { Counter } from 'vs/base/common/numbers';
import { basename, basenameOrAuthority, dirname, isEqual, relativePath } from 'vs/base/common/resources';
import { compare } from 'vs/base/common/strings';
import { withUndefinedAsNull } from 'vs/base/common/types';
import { URI } from 'vs/base/common/uri';
import { localize } from 'vs/nls';
import { ExtensionIdentifier, IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { ILogService } from 'vs/platform/log/common/log';
import { Severity } from 'vs/platform/notification/common/notification';
import { Workspace, WorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { IExtHostInitDataService } from 'vs/workbench/api/common/extHostInitDataService';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
import { Range, RelativePattern } from 'vs/workbench/api/common/extHostTypes';
import { ITextQueryBuilderOptions } from 'vs/workbench/contrib/search/common/queryBuilder';
import { IRawFileMatch2, resultIsMatch } from 'vs/workbench/services/search/common/search';
import * as vscode from 'vscode';
import { ExtHostWorkspaceShape, IWorkspaceData, MainContext, MainThreadMessageServiceShape, MainThreadWorkspaceShape } from './extHost.protocol';
export interface IExtHostWorkspaceProvider {
getWorkspaceFolder2(uri: vscode.Uri, resolveParent?: boolean): Promise<vscode.WorkspaceFolder | undefined>;
resolveWorkspaceFolder(uri: vscode.Uri): Promise<vscode.WorkspaceFolder | undefined>;
getWorkspaceFolders2(): Promise<vscode.WorkspaceFolder[] | undefined>;
resolveProxy(url: string): Promise<string | undefined>;
}
function isFolderEqual(folderA: URI, folderB: URI): boolean {
return isEqual(folderA, folderB);
}
function compareWorkspaceFolderByUri(a: vscode.WorkspaceFolder, b: vscode.WorkspaceFolder): number {
return isFolderEqual(a.uri, b.uri) ? 0 : compare(a.uri.toString(), b.uri.toString());
}
function compareWorkspaceFolderByUriAndNameAndIndex(a: vscode.WorkspaceFolder, b: vscode.WorkspaceFolder): number {
if (a.index !== b.index) {
return a.index < b.index ? -1 : 1;
}
return isFolderEqual(a.uri, b.uri) ? compare(a.name, b.name) : compare(a.uri.toString(), b.uri.toString());
}
function delta(oldFolders: vscode.WorkspaceFolder[], newFolders: vscode.WorkspaceFolder[], compare: (a: vscode.WorkspaceFolder, b: vscode.WorkspaceFolder) => number): { removed: vscode.WorkspaceFolder[], added: vscode.WorkspaceFolder[] } {
const oldSortedFolders = oldFolders.slice(0).sort(compare);
const newSortedFolders = newFolders.slice(0).sort(compare);
return arrayDelta(oldSortedFolders, newSortedFolders, compare);
}
interface MutableWorkspaceFolder extends vscode.WorkspaceFolder {
name: string;
index: number;
}
class ExtHostWorkspaceImpl extends Workspace {
static toExtHostWorkspace(data: IWorkspaceData | null, previousConfirmedWorkspace?: ExtHostWorkspaceImpl, previousUnconfirmedWorkspace?: ExtHostWorkspaceImpl): { workspace: ExtHostWorkspaceImpl | null, added: vscode.WorkspaceFolder[], removed: vscode.WorkspaceFolder[] } {
if (!data) {
return { workspace: null, added: [], removed: [] };
}
const { id, name, folders, configuration, isUntitled } = data;
const newWorkspaceFolders: vscode.WorkspaceFolder[] = [];
// If we have an existing workspace, we try to find the folders that match our
// data and update their properties. It could be that an extension stored them
// for later use and we want to keep them "live" if they are still present.
const oldWorkspace = previousConfirmedWorkspace;
if (previousConfirmedWorkspace) {
folders.forEach((folderData, index) => {
const folderUri = URI.revive(folderData.uri);
const existingFolder = ExtHostWorkspaceImpl._findFolder(previousUnconfirmedWorkspace || previousConfirmedWorkspace, folderUri);
if (existingFolder) {
existingFolder.name = folderData.name;
existingFolder.index = folderData.index;
newWorkspaceFolders.push(existingFolder);
} else {
newWorkspaceFolders.push({ uri: folderUri, name: folderData.name, index });
}
});
} else {
newWorkspaceFolders.push(...folders.map(({ uri, name, index }) => ({ uri: URI.revive(uri), name, index })));
}
// make sure to restore sort order based on index
newWorkspaceFolders.sort((f1, f2) => f1.index < f2.index ? -1 : 1);
const workspace = new ExtHostWorkspaceImpl(id, name, newWorkspaceFolders, configuration ? URI.revive(configuration) : null, !!isUntitled);
const { added, removed } = delta(oldWorkspace ? oldWorkspace.workspaceFolders : [], workspace.workspaceFolders, compareWorkspaceFolderByUri);
return { workspace, added, removed };
}
private static _findFolder(workspace: ExtHostWorkspaceImpl, folderUriToFind: URI): MutableWorkspaceFolder | undefined {
for (let i = 0; i < workspace.folders.length; i++) {
const folder = workspace.workspaceFolders[i];
if (isFolderEqual(folder.uri, folderUriToFind)) {
return folder;
}
}
return undefined;
}
private readonly _workspaceFolders: vscode.WorkspaceFolder[] = [];
private readonly _structure = TernarySearchTree.forPaths<vscode.WorkspaceFolder>();
constructor(id: string, private _name: string, folders: vscode.WorkspaceFolder[], configuration: URI | null, private _isUntitled: boolean) {
super(id, folders.map(f => new WorkspaceFolder(f)), configuration);
// setup the workspace folder data structure
folders.forEach(folder => {
this._workspaceFolders.push(folder);
this._structure.set(folder.uri.toString(), folder);
});
}
get name(): string {
return this._name;
}
get isUntitled(): boolean {
return this._isUntitled;
}
get workspaceFolders(): vscode.WorkspaceFolder[] {
return this._workspaceFolders.slice(0);
}
getWorkspaceFolder(uri: URI, resolveParent?: boolean): vscode.WorkspaceFolder | undefined {
if (resolveParent && this._structure.get(uri.toString())) {
// `uri` is a workspace folder so we check for its parent
uri = dirname(uri);
}
return this._structure.findSubstr(uri.toString());
}
resolveWorkspaceFolder(uri: URI): vscode.WorkspaceFolder | undefined {
return this._structure.get(uri.toString());
}
}
export class ExtHostWorkspace implements ExtHostWorkspaceShape, IExtHostWorkspaceProvider {
readonly _serviceBrand: undefined;
private readonly _onDidChangeWorkspace = new Emitter<vscode.WorkspaceFoldersChangeEvent>();
readonly onDidChangeWorkspace: Event<vscode.WorkspaceFoldersChangeEvent> = this._onDidChangeWorkspace.event;
private readonly _logService: ILogService;
private readonly _requestIdProvider: Counter;
private readonly _barrier: Barrier;
private _confirmedWorkspace?: ExtHostWorkspaceImpl;
private _unconfirmedWorkspace?: ExtHostWorkspaceImpl;
private readonly _proxy: MainThreadWorkspaceShape;
private readonly _messageService: MainThreadMessageServiceShape;
private readonly _activeSearchCallbacks: ((match: IRawFileMatch2) => any)[] = [];
constructor(
@IExtHostRpcService extHostRpc: IExtHostRpcService,
@IExtHostInitDataService initData: IExtHostInitDataService,
@ILogService logService: ILogService,
) {
this._logService = logService;
this._requestIdProvider = new Counter();
this._barrier = new Barrier();
this._proxy = extHostRpc.getProxy(MainContext.MainThreadWorkspace);
this._messageService = extHostRpc.getProxy(MainContext.MainThreadMessageService);
const data = initData.workspace;
this._confirmedWorkspace = data ? new ExtHostWorkspaceImpl(data.id, data.name, [], data.configuration ? URI.revive(data.configuration) : null, !!data.isUntitled) : undefined;
}
$initializeWorkspace(data: IWorkspaceData | null): void {
this.$acceptWorkspaceData(data);
this._barrier.open();
}
waitForInitializeCall(): Promise<boolean> {
return this._barrier.wait();
}
// --- workspace ---
get workspace(): Workspace | undefined {
return this._actualWorkspace;
}
get name(): string | undefined {
return this._actualWorkspace ? this._actualWorkspace.name : undefined;
}
get workspaceFile(): vscode.Uri | undefined {
if (this._actualWorkspace) {
if (this._actualWorkspace.configuration) {
if (this._actualWorkspace.isUntitled) {
return URI.from({ scheme: Schemas.untitled, path: basename(dirname(this._actualWorkspace.configuration)) }); // Untitled Worspace: return untitled URI
}
return this._actualWorkspace.configuration; // Workspace: return the configuration location
}
}
return undefined;
}
private get _actualWorkspace(): ExtHostWorkspaceImpl | undefined {
return this._unconfirmedWorkspace || this._confirmedWorkspace;
}
getWorkspaceFolders(): vscode.WorkspaceFolder[] | undefined {
if (!this._actualWorkspace) {
return undefined;
}
return this._actualWorkspace.workspaceFolders.slice(0);
}
async getWorkspaceFolders2(): Promise<vscode.WorkspaceFolder[] | undefined> {
await this._barrier.wait();
if (!this._actualWorkspace) {
return undefined;
}
return this._actualWorkspace.workspaceFolders.slice(0);
}
updateWorkspaceFolders(extension: IExtensionDescription, index: number, deleteCount: number, ...workspaceFoldersToAdd: { uri: vscode.Uri, name?: string }[]): boolean {
const validatedDistinctWorkspaceFoldersToAdd: { uri: vscode.Uri, name?: string }[] = [];
if (Array.isArray(workspaceFoldersToAdd)) {
workspaceFoldersToAdd.forEach(folderToAdd => {
if (URI.isUri(folderToAdd.uri) && !validatedDistinctWorkspaceFoldersToAdd.some(f => isFolderEqual(f.uri, folderToAdd.uri))) {
validatedDistinctWorkspaceFoldersToAdd.push({ uri: folderToAdd.uri, name: folderToAdd.name || basenameOrAuthority(folderToAdd.uri) });
}
});
}
if (!!this._unconfirmedWorkspace) {
return false; // prevent accumulated calls without a confirmed workspace
}
if ([index, deleteCount].some(i => typeof i !== 'number' || i < 0)) {
return false; // validate numbers
}
if (deleteCount === 0 && validatedDistinctWorkspaceFoldersToAdd.length === 0) {
return false; // nothing to delete or add
}
const currentWorkspaceFolders: MutableWorkspaceFolder[] = this._actualWorkspace ? this._actualWorkspace.workspaceFolders : [];
if (index + deleteCount > currentWorkspaceFolders.length) {
return false; // cannot delete more than we have
}
// Simulate the updateWorkspaceFolders method on our data to do more validation
const newWorkspaceFolders = currentWorkspaceFolders.slice(0);
newWorkspaceFolders.splice(index, deleteCount, ...validatedDistinctWorkspaceFoldersToAdd.map(f => ({ uri: f.uri, name: f.name || basenameOrAuthority(f.uri), index: undefined! /* fixed later */ })));
for (let i = 0; i < newWorkspaceFolders.length; i++) {
const folder = newWorkspaceFolders[i];
if (newWorkspaceFolders.some((otherFolder, index) => index !== i && isFolderEqual(folder.uri, otherFolder.uri))) {
return false; // cannot add the same folder multiple times
}
}
newWorkspaceFolders.forEach((f, index) => f.index = index); // fix index
const { added, removed } = delta(currentWorkspaceFolders, newWorkspaceFolders, compareWorkspaceFolderByUriAndNameAndIndex);
if (added.length === 0 && removed.length === 0) {
return false; // nothing actually changed
}
// Trigger on main side
if (this._proxy) {
const extName = extension.displayName || extension.name;
this._proxy.$updateWorkspaceFolders(extName, index, deleteCount, validatedDistinctWorkspaceFoldersToAdd).then(undefined, error => {
// in case of an error, make sure to clear out the unconfirmed workspace
// because we cannot expect the acknowledgement from the main side for this
this._unconfirmedWorkspace = undefined;
// show error to user
this._messageService.$showMessage(Severity.Error, localize('updateerror', "Extension '{0}' failed to update workspace folders: {1}", extName, error.toString()), { extension }, []);
});
}
// Try to accept directly
this.trySetWorkspaceFolders(newWorkspaceFolders);
return true;
}
getWorkspaceFolder(uri: vscode.Uri, resolveParent?: boolean): vscode.WorkspaceFolder | undefined {
if (!this._actualWorkspace) {
return undefined;
}
return this._actualWorkspace.getWorkspaceFolder(uri, resolveParent);
}
async getWorkspaceFolder2(uri: vscode.Uri, resolveParent?: boolean): Promise<vscode.WorkspaceFolder | undefined> {
await this._barrier.wait();
if (!this._actualWorkspace) {
return undefined;
}
return this._actualWorkspace.getWorkspaceFolder(uri, resolveParent);
}
async resolveWorkspaceFolder(uri: vscode.Uri): Promise<vscode.WorkspaceFolder | undefined> {
await this._barrier.wait();
if (!this._actualWorkspace) {
return undefined;
}
return this._actualWorkspace.resolveWorkspaceFolder(uri);
}
getPath(): string | undefined {
// this is legacy from the days before having
// multi-root and we keep it only alive if there
// is just one workspace folder.
if (!this._actualWorkspace) {
return undefined;
}
const { folders } = this._actualWorkspace;
if (folders.length === 0) {
return undefined;
}
// #54483 @Joh Why are we still using fsPath?
return folders[0].uri.fsPath;
}
getRelativePath(pathOrUri: string | vscode.Uri, includeWorkspace?: boolean): string {
let resource: URI | undefined;
let path: string = '';
if (typeof pathOrUri === 'string') {
resource = URI.file(pathOrUri);
path = pathOrUri;
} else if (typeof pathOrUri !== 'undefined') {
resource = pathOrUri;
path = pathOrUri.fsPath;
}
if (!resource) {
return path;
}
const folder = this.getWorkspaceFolder(
resource,
true
);
if (!folder) {
return path;
}
if (typeof includeWorkspace === 'undefined' && this._actualWorkspace) {
includeWorkspace = this._actualWorkspace.folders.length > 1;
}
let result = relativePath(folder.uri, resource);
if (includeWorkspace && folder.name) {
result = `${folder.name}/${result}`;
}
return result!;
}
private trySetWorkspaceFolders(folders: vscode.WorkspaceFolder[]): void {
// Update directly here. The workspace is unconfirmed as long as we did not get an
// acknowledgement from the main side (via $acceptWorkspaceData)
if (this._actualWorkspace) {
this._unconfirmedWorkspace = ExtHostWorkspaceImpl.toExtHostWorkspace({
id: this._actualWorkspace.id,
name: this._actualWorkspace.name,
configuration: this._actualWorkspace.configuration,
folders,
isUntitled: this._actualWorkspace.isUntitled
} as IWorkspaceData, this._actualWorkspace).workspace || undefined;
}
}
$acceptWorkspaceData(data: IWorkspaceData | null): void {
const { workspace, added, removed } = ExtHostWorkspaceImpl.toExtHostWorkspace(data, this._confirmedWorkspace, this._unconfirmedWorkspace);
// Update our workspace object. We have a confirmed workspace, so we drop our
// unconfirmed workspace.
this._confirmedWorkspace = workspace || undefined;
this._unconfirmedWorkspace = undefined;
// Events
this._onDidChangeWorkspace.fire(Object.freeze({
added,
removed,
}));
}
// --- search ---
/**
* Note, null/undefined have different and important meanings for "exclude"
*/
findFiles(include: string | RelativePattern | undefined, exclude: vscode.GlobPattern | null | undefined, maxResults: number | undefined, extensionId: ExtensionIdentifier, token: vscode.CancellationToken = CancellationToken.None): Promise<vscode.Uri[]> {
this._logService.trace(`extHostWorkspace#findFiles: fileSearch, extension: ${extensionId.value}, entryPoint: findFiles`);
let excludePatternOrDisregardExcludes: string | false | undefined = undefined;
if (exclude === null) {
excludePatternOrDisregardExcludes = false;
} else if (exclude) {
if (typeof exclude === 'string') {
excludePatternOrDisregardExcludes = exclude;
} else {
excludePatternOrDisregardExcludes = exclude.pattern;
}
}
if (token && token.isCancellationRequested) {
return Promise.resolve([]);
}
const { includePattern, folder } = parseSearchInclude(include);
return this._proxy.$startFileSearch(
withUndefinedAsNull(includePattern),
withUndefinedAsNull(folder),
withUndefinedAsNull(excludePatternOrDisregardExcludes),
withUndefinedAsNull(maxResults),
token
)
.then(data => Array.isArray(data) ? data.map(d => URI.revive(d)) : []);
}
async findTextInFiles(query: vscode.TextSearchQuery, options: vscode.FindTextInFilesOptions, callback: (result: vscode.TextSearchResult) => void, extensionId: ExtensionIdentifier, token: vscode.CancellationToken = CancellationToken.None): Promise<vscode.TextSearchComplete> {
this._logService.trace(`extHostWorkspace#findTextInFiles: textSearch, extension: ${extensionId.value}, entryPoint: findTextInFiles`);
const requestId = this._requestIdProvider.getNext();
const previewOptions: vscode.TextSearchPreviewOptions = typeof options.previewOptions === 'undefined' ?
{
matchLines: 100,
charsPerLine: 10000
} :
options.previewOptions;
let includePattern: string | undefined;
let folder: URI | undefined;
if (options.include) {
if (typeof options.include === 'string') {
includePattern = options.include;
} else {
includePattern = options.include.pattern;
folder = (options.include as RelativePattern).baseFolder || URI.file(options.include.base);
}
}
const excludePattern = (typeof options.exclude === 'string') ? options.exclude :
options.exclude ? options.exclude.pattern : undefined;
const queryOptions: ITextQueryBuilderOptions = {
ignoreSymlinks: typeof options.followSymlinks === 'boolean' ? !options.followSymlinks : undefined,
disregardIgnoreFiles: typeof options.useIgnoreFiles === 'boolean' ? !options.useIgnoreFiles : undefined,
disregardGlobalIgnoreFiles: typeof options.useGlobalIgnoreFiles === 'boolean' ? !options.useGlobalIgnoreFiles : undefined,
disregardExcludeSettings: typeof options.useDefaultExcludes === 'boolean' ? !options.useDefaultExcludes : true,
fileEncoding: options.encoding,
maxResults: options.maxResults,
previewOptions,
afterContext: options.afterContext,
beforeContext: options.beforeContext,
includePattern: includePattern,
excludePattern: excludePattern
};
const isCanceled = false;
this._activeSearchCallbacks[requestId] = p => {
if (isCanceled) {
return;
}
const uri = URI.revive(p.resource);
p.results!.forEach(result => {
if (resultIsMatch(result)) {
callback(<vscode.TextSearchMatch>{
uri,
preview: {
text: result.preview.text,
matches: mapArrayOrNot(
result.preview.matches,
m => new Range(m.startLineNumber, m.startColumn, m.endLineNumber, m.endColumn))
},
ranges: mapArrayOrNot(
result.ranges,
r => new Range(r.startLineNumber, r.startColumn, r.endLineNumber, r.endColumn))
});
} else {
callback(<vscode.TextSearchContext>{
uri,
text: result.text,
lineNumber: result.lineNumber
});
}
});
};
if (token.isCancellationRequested) {
return {};
}
try {
const result = await this._proxy.$startTextSearch(
query,
withUndefinedAsNull(folder),
queryOptions,
requestId,
token);
delete this._activeSearchCallbacks[requestId];
return result || {};
} catch (err) {
delete this._activeSearchCallbacks[requestId];
throw err;
}
}
$handleTextSearchResult(result: IRawFileMatch2, requestId: number): void {
if (this._activeSearchCallbacks[requestId]) {
this._activeSearchCallbacks[requestId](result);
}
}
saveAll(includeUntitled?: boolean): Promise<boolean> {
return this._proxy.$saveAll(includeUntitled);
}
resolveProxy(url: string): Promise<string | undefined> {
return this._proxy.$resolveProxy(url);
}
}
export const IExtHostWorkspace = createDecorator<IExtHostWorkspace>('IExtHostWorkspace');
export interface IExtHostWorkspace extends ExtHostWorkspace, ExtHostWorkspaceShape, IExtHostWorkspaceProvider { }
function parseSearchInclude(include: RelativePattern | string | undefined): { includePattern?: string, folder?: URI } {
let includePattern: string | undefined;
let includeFolder: URI | undefined;
if (include) {
if (typeof include === 'string') {
includePattern = include;
} else {
includePattern = include.pattern;
// include.base must be an absolute path
includeFolder = include.baseFolder || URI.file(include.base);
}
}
return {
includePattern: includePattern,
folder: includeFolder
};
}
| src/vs/workbench/api/common/extHostWorkspace.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.00237483624368906,
0.00023982518177945167,
0.0001636418601265177,
0.00017213905812241137,
0.00032920550438575447
] |
{
"id": 2,
"code_window": [
"import { NOTEBOOK_EDITOR_CURSOR_BOUNDARY } from 'vs/workbench/contrib/notebook/common/notebookCommon';\n",
"import { Range } from 'vs/editor/common/core/range';\n",
"import { CellRevealType, CellRevealPosition, CursorAtBoundary } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';\n",
"import { IDisposable, DisposableStore } from 'vs/base/common/lifecycle';\n",
"import { CellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel';\n",
"import { EDITOR_TOP_PADDING } from 'vs/workbench/contrib/notebook/browser/constants';\n",
"\n",
"export class NotebookCellList extends WorkbenchList<CellViewModel> implements IDisposable {\n",
"\tget onWillScroll(): Event<ScrollEvent> { return this.view.onWillScroll; }\n",
"\n",
"\tget rowsContainer(): HTMLElement {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "replace",
"edit_start_line_idx": 21
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as DOM from 'vs/base/browser/dom';
import { IListRenderer, IListVirtualDelegate, ListError } from 'vs/base/browser/ui/list/list';
import { Event } from 'vs/base/common/event';
import { ScrollEvent } from 'vs/base/common/scrollable';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IListService, IWorkbenchListOptions, WorkbenchList } from 'vs/platform/list/browser/listService';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { IMouseWheelEvent } from 'vs/base/browser/mouseEvent';
import { isMacintosh } from 'vs/base/common/platform';
import { NOTEBOOK_EDITOR_CURSOR_BOUNDARY } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { Range } from 'vs/editor/common/core/range';
import { CellRevealType, CellRevealPosition, CursorAtBoundary } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { IDisposable, DisposableStore } from 'vs/base/common/lifecycle';
import { CellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel';
import { EDITOR_TOP_PADDING } from 'vs/workbench/contrib/notebook/browser/constants';
export class NotebookCellList extends WorkbenchList<CellViewModel> implements IDisposable {
get onWillScroll(): Event<ScrollEvent> { return this.view.onWillScroll; }
get rowsContainer(): HTMLElement {
return this.view.containerDomNode;
}
private _previousSelectedElements: CellViewModel[] = [];
private _localDisposableStore = new DisposableStore();
constructor(
private listUser: string,
container: HTMLElement,
delegate: IListVirtualDelegate<CellViewModel>,
renderers: IListRenderer<CellViewModel, any>[],
contextKeyService: IContextKeyService,
options: IWorkbenchListOptions<CellViewModel>,
@IListService listService: IListService,
@IThemeService themeService: IThemeService,
@IConfigurationService configurationService: IConfigurationService,
@IKeybindingService keybindingService: IKeybindingService
) {
super(listUser, container, delegate, renderers, options, contextKeyService, listService, themeService, configurationService, keybindingService);
this._previousSelectedElements = this.getSelectedElements();
this._localDisposableStore.add(this.onDidChangeSelection((e) => {
this._previousSelectedElements.forEach(element => {
if (e.elements.indexOf(element) < 0) {
element.onDeselect();
}
});
this._previousSelectedElements = e.elements;
}));
const notebookEditorCursorAtBoundaryContext = NOTEBOOK_EDITOR_CURSOR_BOUNDARY.bindTo(contextKeyService);
notebookEditorCursorAtBoundaryContext.set('none');
let cursorSelectionLisener: IDisposable | null = null;
const recomputeContext = (element: CellViewModel) => {
switch (element.cursorAtBoundary()) {
case CursorAtBoundary.Both:
notebookEditorCursorAtBoundaryContext.set('both');
break;
case CursorAtBoundary.Top:
notebookEditorCursorAtBoundaryContext.set('top');
break;
case CursorAtBoundary.Bottom:
notebookEditorCursorAtBoundaryContext.set('bottom');
break;
default:
notebookEditorCursorAtBoundaryContext.set('none');
break;
}
return;
};
// Cursor Boundary context
this._localDisposableStore.add(this.onDidChangeFocus((e) => {
cursorSelectionLisener?.dispose();
if (e.elements.length) {
// we only validate the first focused element
const focusedElement = e.elements[0];
cursorSelectionLisener = focusedElement.onDidChangeCursorSelection(() => {
recomputeContext(focusedElement);
});
recomputeContext(focusedElement);
return;
}
// reset context
notebookEditorCursorAtBoundaryContext.set('none');
}));
}
domElementAtIndex(index: number): HTMLElement | null {
return this.view.domElement(index);
}
focusView() {
this.view.domNode.focus();
}
getAbsoluteTop(index: number): number {
if (index < 0 || index >= this.length) {
throw new ListError(this.listUser, `Invalid index ${index}`);
}
return this.view.elementTop(index);
}
triggerScrollFromMouseWheelEvent(browserEvent: IMouseWheelEvent) {
this.view.triggerScrollFromMouseWheelEvent(browserEvent);
}
updateElementHeight(index: number, size: number): void {
const focused = this.getSelection();
this.view.updateElementHeight(index, size, focused.length ? focused[0] : null);
// this.view.updateElementHeight(index, size, null);
}
// override
domFocus() {
if (document.activeElement && this.view.domNode.contains(document.activeElement)) {
// for example, when focus goes into monaco editor, if we refocus the list view, the editor will lose focus.
return;
}
if (!isMacintosh && document.activeElement && isContextMenuFocused()) {
return;
}
super.domFocus();
}
private _revealRange(index: number, range: Range, revealType: CellRevealType, newlyCreated: boolean, alignToBottom: boolean) {
const element = this.view.element(index);
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const startLineNumber = range.startLineNumber;
const lineOffset = element.getLineScrollTopOffset(startLineNumber);
const elementTop = this.view.elementTop(index);
const lineTop = elementTop + lineOffset + EDITOR_TOP_PADDING;
// TODO@rebornix 30 ---> line height * 1.5
if (lineTop < scrollTop) {
this.view.setScrollTop(lineTop - 30);
} else if (lineTop > wrapperBottom) {
this.view.setScrollTop(scrollTop + lineTop - wrapperBottom + 30);
} else if (newlyCreated) {
// newly scrolled into view
if (alignToBottom) {
// align to the bottom
this.view.setScrollTop(scrollTop + lineTop - wrapperBottom + 30);
} else {
// align to to top
this.view.setScrollTop(lineTop - 30);
}
}
if (revealType === CellRevealType.Range) {
element.revealRangeInCenter(range);
}
}
// TODO@rebornix TEST & Fix potential bugs
// List items have real dynamic heights, which means after we set `scrollTop` based on the `elementTop(index)`, the element at `index` might still be removed from the view once all relayouting tasks are done.
// For example, we scroll item 10 into the view upwards, in the first round, items 7, 8, 9, 10 are all in the viewport. Then item 7 and 8 resize themselves to be larger and finally item 10 is removed from the view.
// To ensure that item 10 is always there, we need to scroll item 10 to the top edge of the viewport.
private _revealRangeInternal(index: number, range: Range, revealType: CellRevealType) {
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const elementTop = this.view.elementTop(index);
const element = this.view.element(index);
if (element.editorAttached) {
this._revealRange(index, range, revealType, false, false);
} else {
const elementHeight = this.view.elementHeight(index);
let upwards = false;
if (elementTop + elementHeight < scrollTop) {
// scroll downwards
this.view.setScrollTop(elementTop);
upwards = false;
} else if (elementTop > wrapperBottom) {
// scroll upwards
this.view.setScrollTop(elementTop - this.view.renderHeight / 2);
upwards = true;
}
const editorAttachedPromise = new Promise((resolve, reject) => {
element.onDidChangeEditorAttachState(state => state ? resolve() : reject());
});
editorAttachedPromise.then(() => {
this._revealRange(index, range, revealType, true, upwards);
});
}
}
revealLineInView(index: number, line: number) {
this._revealRangeInternal(index, new Range(line, 1, line, 1), CellRevealType.Line);
}
revealRangeInView(index: number, range: Range): void {
this._revealRangeInternal(index, range, CellRevealType.Range);
}
private _revealRangeInCenterInternal(index: number, range: Range, revealType: CellRevealType) {
const reveal = (index: number, range: Range, revealType: CellRevealType) => {
const element = this.view.element(index);
let lineOffset = element.getLineScrollTopOffset(range.startLineNumber);
let lineOffsetInView = this.view.elementTop(index) + lineOffset;
this.view.setScrollTop(lineOffsetInView - this.view.renderHeight / 2);
if (revealType === CellRevealType.Range) {
element.revealRangeInCenter(range);
}
};
const elementTop = this.view.elementTop(index);
const viewItemOffset = elementTop;
this.view.setScrollTop(viewItemOffset - this.view.renderHeight / 2);
const element = this.view.element(index);
if (!element.editorAttached) {
getEditorAttachedPromise(element).then(() => reveal(index, range, revealType));
} else {
reveal(index, range, revealType);
}
}
revealLineInCenter(index: number, line: number) {
this._revealRangeInCenterInternal(index, new Range(line, 1, line, 1), CellRevealType.Line);
}
revealRangeInCenter(index: number, range: Range): void {
this._revealRangeInCenterInternal(index, range, CellRevealType.Range);
}
private _revealRangeInCenterIfOutsideViewportInternal(index: number, range: Range, revealType: CellRevealType) {
const reveal = (index: number, range: Range, revealType: CellRevealType) => {
const element = this.view.element(index);
let lineOffset = element.getLineScrollTopOffset(range.startLineNumber);
let lineOffsetInView = this.view.elementTop(index) + lineOffset;
this.view.setScrollTop(lineOffsetInView - this.view.renderHeight / 2);
if (revealType === CellRevealType.Range) {
setTimeout(() => {
element.revealRangeInCenter(range);
}, 240);
}
};
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const elementTop = this.view.elementTop(index);
const viewItemOffset = elementTop;
const element = this.view.element(index);
if (viewItemOffset < scrollTop || viewItemOffset > wrapperBottom) {
// let it render
this.view.setScrollTop(viewItemOffset - this.view.renderHeight / 2);
// after rendering, it might be pushed down due to markdown cell dynamic height
const elementTop = this.view.elementTop(index);
this.view.setScrollTop(elementTop - this.view.renderHeight / 2);
// reveal editor
if (!element.editorAttached) {
getEditorAttachedPromise(element).then(() => reveal(index, range, revealType));
} else {
// for example markdown
}
} else {
if (element.editorAttached) {
element.revealRangeInCenter(range);
} else {
// for example, markdown cell in preview mode
getEditorAttachedPromise(element).then(() => reveal(index, range, revealType));
}
}
}
revealLineInCenterIfOutsideViewport(index: number, line: number) {
this._revealRangeInCenterIfOutsideViewportInternal(index, new Range(line, 1, line, 1), CellRevealType.Line);
}
revealRangeInCenterIfOutsideViewport(index: number, range: Range): void {
this._revealRangeInCenterIfOutsideViewportInternal(index, range, CellRevealType.Range);
}
private _revealInternal(index: number, ignoreIfInsideViewport: boolean, revealPosition: CellRevealPosition) {
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const elementTop = this.view.elementTop(index);
if (ignoreIfInsideViewport && elementTop >= scrollTop && elementTop < wrapperBottom) {
// inside the viewport
return;
}
// first render
const viewItemOffset = revealPosition === CellRevealPosition.Top ? elementTop : (elementTop - this.view.renderHeight / 2);
this.view.setScrollTop(viewItemOffset);
// second scroll as markdown cell is dynamic
const newElementTop = this.view.elementTop(index);
const newViewItemOffset = revealPosition === CellRevealPosition.Top ? newElementTop : (newElementTop - this.view.renderHeight / 2);
this.view.setScrollTop(newViewItemOffset);
}
revealInView(index: number) {
this._revealInternal(index, true, CellRevealPosition.Top);
}
revealInCenter(index: number) {
this._revealInternal(index, false, CellRevealPosition.Center);
}
revealInCenterIfOutsideViewport(index: number) {
this._revealInternal(index, true, CellRevealPosition.Center);
}
setCellSelection(index: number, range: Range) {
const element = this.view.element(index);
if (element.editorAttached) {
element.setSelection(range);
} else {
getEditorAttachedPromise(element).then(() => { element.setSelection(range); });
}
}
dispose() {
this._localDisposableStore.dispose();
super.dispose();
}
}
function getEditorAttachedPromise(element: CellViewModel) {
return new Promise((resolve, reject) => {
Event.once(element.onDidChangeEditorAttachState)(state => state ? resolve() : reject());
});
}
function isContextMenuFocused() {
return !!DOM.findParentWithClass(<HTMLElement>document.activeElement, 'context-view');
}
| src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts | 1 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.9937979578971863,
0.06471873074769974,
0.00016443425556644797,
0.0002824043040163815,
0.22909176349639893
] |
{
"id": 2,
"code_window": [
"import { NOTEBOOK_EDITOR_CURSOR_BOUNDARY } from 'vs/workbench/contrib/notebook/common/notebookCommon';\n",
"import { Range } from 'vs/editor/common/core/range';\n",
"import { CellRevealType, CellRevealPosition, CursorAtBoundary } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';\n",
"import { IDisposable, DisposableStore } from 'vs/base/common/lifecycle';\n",
"import { CellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel';\n",
"import { EDITOR_TOP_PADDING } from 'vs/workbench/contrib/notebook/browser/constants';\n",
"\n",
"export class NotebookCellList extends WorkbenchList<CellViewModel> implements IDisposable {\n",
"\tget onWillScroll(): Event<ScrollEvent> { return this.view.onWillScroll; }\n",
"\n",
"\tget rowsContainer(): HTMLElement {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "replace",
"edit_start_line_idx": 21
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { basename, posix, extname } from 'vs/base/common/path';
import { endsWith, startsWithUTF8BOM, startsWith } from 'vs/base/common/strings';
import { coalesce } from 'vs/base/common/arrays';
import { match } from 'vs/base/common/glob';
import { URI } from 'vs/base/common/uri';
import { Schemas } from 'vs/base/common/network';
import { DataUri } from 'vs/base/common/resources';
export const MIME_TEXT = 'text/plain';
export const MIME_BINARY = 'application/octet-stream';
export const MIME_UNKNOWN = 'application/unknown';
export interface ITextMimeAssociation {
readonly id: string;
readonly mime: string;
readonly filename?: string;
readonly extension?: string;
readonly filepattern?: string;
readonly firstline?: RegExp;
readonly userConfigured?: boolean;
}
interface ITextMimeAssociationItem extends ITextMimeAssociation {
readonly filenameLowercase?: string;
readonly extensionLowercase?: string;
readonly filepatternLowercase?: string;
readonly filepatternOnPath?: boolean;
}
let registeredAssociations: ITextMimeAssociationItem[] = [];
let nonUserRegisteredAssociations: ITextMimeAssociationItem[] = [];
let userRegisteredAssociations: ITextMimeAssociationItem[] = [];
/**
* Associate a text mime to the registry.
*/
export function registerTextMime(association: ITextMimeAssociation, warnOnOverwrite = false): void {
// Register
const associationItem = toTextMimeAssociationItem(association);
registeredAssociations.push(associationItem);
if (!associationItem.userConfigured) {
nonUserRegisteredAssociations.push(associationItem);
} else {
userRegisteredAssociations.push(associationItem);
}
// Check for conflicts unless this is a user configured association
if (warnOnOverwrite && !associationItem.userConfigured) {
registeredAssociations.forEach(a => {
if (a.mime === associationItem.mime || a.userConfigured) {
return; // same mime or userConfigured is ok
}
if (associationItem.extension && a.extension === associationItem.extension) {
console.warn(`Overwriting extension <<${associationItem.extension}>> to now point to mime <<${associationItem.mime}>>`);
}
if (associationItem.filename && a.filename === associationItem.filename) {
console.warn(`Overwriting filename <<${associationItem.filename}>> to now point to mime <<${associationItem.mime}>>`);
}
if (associationItem.filepattern && a.filepattern === associationItem.filepattern) {
console.warn(`Overwriting filepattern <<${associationItem.filepattern}>> to now point to mime <<${associationItem.mime}>>`);
}
if (associationItem.firstline && a.firstline === associationItem.firstline) {
console.warn(`Overwriting firstline <<${associationItem.firstline}>> to now point to mime <<${associationItem.mime}>>`);
}
});
}
}
function toTextMimeAssociationItem(association: ITextMimeAssociation): ITextMimeAssociationItem {
return {
id: association.id,
mime: association.mime,
filename: association.filename,
extension: association.extension,
filepattern: association.filepattern,
firstline: association.firstline,
userConfigured: association.userConfigured,
filenameLowercase: association.filename ? association.filename.toLowerCase() : undefined,
extensionLowercase: association.extension ? association.extension.toLowerCase() : undefined,
filepatternLowercase: association.filepattern ? association.filepattern.toLowerCase() : undefined,
filepatternOnPath: association.filepattern ? association.filepattern.indexOf(posix.sep) >= 0 : false
};
}
/**
* Clear text mimes from the registry.
*/
export function clearTextMimes(onlyUserConfigured?: boolean): void {
if (!onlyUserConfigured) {
registeredAssociations = [];
nonUserRegisteredAssociations = [];
userRegisteredAssociations = [];
} else {
registeredAssociations = registeredAssociations.filter(a => !a.userConfigured);
userRegisteredAssociations = [];
}
}
/**
* Given a file, return the best matching mime type for it
*/
export function guessMimeTypes(resource: URI | null, firstLine?: string): string[] {
let path: string | undefined;
if (resource) {
switch (resource.scheme) {
case Schemas.file:
path = resource.fsPath;
break;
case Schemas.data:
const metadata = DataUri.parseMetaData(resource);
path = metadata.get(DataUri.META_DATA_LABEL);
break;
default:
path = resource.path;
}
}
if (!path) {
return [MIME_UNKNOWN];
}
path = path.toLowerCase();
const filename = basename(path);
// 1.) User configured mappings have highest priority
const configuredMime = guessMimeTypeByPath(path, filename, userRegisteredAssociations);
if (configuredMime) {
return [configuredMime, MIME_TEXT];
}
// 2.) Registered mappings have middle priority
const registeredMime = guessMimeTypeByPath(path, filename, nonUserRegisteredAssociations);
if (registeredMime) {
return [registeredMime, MIME_TEXT];
}
// 3.) Firstline has lowest priority
if (firstLine) {
const firstlineMime = guessMimeTypeByFirstline(firstLine);
if (firstlineMime) {
return [firstlineMime, MIME_TEXT];
}
}
return [MIME_UNKNOWN];
}
function guessMimeTypeByPath(path: string, filename: string, associations: ITextMimeAssociationItem[]): string | null {
let filenameMatch: ITextMimeAssociationItem | null = null;
let patternMatch: ITextMimeAssociationItem | null = null;
let extensionMatch: ITextMimeAssociationItem | null = null;
// We want to prioritize associations based on the order they are registered so that the last registered
// association wins over all other. This is for https://github.com/Microsoft/vscode/issues/20074
for (let i = associations.length - 1; i >= 0; i--) {
const association = associations[i];
// First exact name match
if (filename === association.filenameLowercase) {
filenameMatch = association;
break; // take it!
}
// Longest pattern match
if (association.filepattern) {
if (!patternMatch || association.filepattern.length > patternMatch.filepattern!.length) {
const target = association.filepatternOnPath ? path : filename; // match on full path if pattern contains path separator
if (match(association.filepatternLowercase!, target)) {
patternMatch = association;
}
}
}
// Longest extension match
if (association.extension) {
if (!extensionMatch || association.extension.length > extensionMatch.extension!.length) {
if (endsWith(filename, association.extensionLowercase!)) {
extensionMatch = association;
}
}
}
}
// 1.) Exact name match has second highest prio
if (filenameMatch) {
return filenameMatch.mime;
}
// 2.) Match on pattern
if (patternMatch) {
return patternMatch.mime;
}
// 3.) Match on extension comes next
if (extensionMatch) {
return extensionMatch.mime;
}
return null;
}
function guessMimeTypeByFirstline(firstLine: string): string | null {
if (startsWithUTF8BOM(firstLine)) {
firstLine = firstLine.substr(1);
}
if (firstLine.length > 0) {
// We want to prioritize associations based on the order they are registered so that the last registered
// association wins over all other. This is for https://github.com/Microsoft/vscode/issues/20074
for (let i = registeredAssociations.length - 1; i >= 0; i--) {
const association = registeredAssociations[i];
if (!association.firstline) {
continue;
}
const matches = firstLine.match(association.firstline);
if (matches && matches.length > 0) {
return association.mime;
}
}
}
return null;
}
export function isUnspecific(mime: string[] | string): boolean {
if (!mime) {
return true;
}
if (typeof mime === 'string') {
return mime === MIME_BINARY || mime === MIME_TEXT || mime === MIME_UNKNOWN;
}
return mime.length === 1 && isUnspecific(mime[0]);
}
/**
* Returns a suggestion for the filename by the following logic:
* 1. If a relevant extension exists and is an actual filename extension (starting with a dot), suggest the prefix appended by the first one.
* 2. Otherwise, if there are other extensions, suggest the first one.
* 3. Otherwise, suggest the prefix.
*/
export function suggestFilename(mode: string | undefined, prefix: string): string {
const extensions = registeredAssociations
.filter(assoc => !assoc.userConfigured && assoc.extension && assoc.id === mode)
.map(assoc => assoc.extension);
const extensionsWithDotFirst = coalesce(extensions)
.filter(assoc => startsWith(assoc, '.'));
if (extensionsWithDotFirst.length > 0) {
const candidateExtension = extensionsWithDotFirst[0];
if (endsWith(prefix, candidateExtension)) {
// do not add the prefix if it already exists
// https://github.com/microsoft/vscode/issues/83603
return prefix;
}
return prefix + candidateExtension;
}
return extensions[0] || prefix;
}
interface MapExtToMediaMimes {
[index: string]: string;
}
// Known media mimes that we can handle
const mapExtToMediaMimes: MapExtToMediaMimes = {
'.aac': 'audio/x-aac',
'.avi': 'video/x-msvideo',
'.bmp': 'image/bmp',
'.flv': 'video/x-flv',
'.gif': 'image/gif',
'.ico': 'image/x-icon',
'.jpe': 'image/jpg',
'.jpeg': 'image/jpg',
'.jpg': 'image/jpg',
'.m1v': 'video/mpeg',
'.m2a': 'audio/mpeg',
'.m2v': 'video/mpeg',
'.m3a': 'audio/mpeg',
'.mid': 'audio/midi',
'.midi': 'audio/midi',
'.mk3d': 'video/x-matroska',
'.mks': 'video/x-matroska',
'.mkv': 'video/x-matroska',
'.mov': 'video/quicktime',
'.movie': 'video/x-sgi-movie',
'.mp2': 'audio/mpeg',
'.mp2a': 'audio/mpeg',
'.mp3': 'audio/mpeg',
'.mp4': 'video/mp4',
'.mp4a': 'audio/mp4',
'.mp4v': 'video/mp4',
'.mpe': 'video/mpeg',
'.mpeg': 'video/mpeg',
'.mpg': 'video/mpeg',
'.mpg4': 'video/mp4',
'.mpga': 'audio/mpeg',
'.oga': 'audio/ogg',
'.ogg': 'audio/ogg',
'.ogv': 'video/ogg',
'.png': 'image/png',
'.psd': 'image/vnd.adobe.photoshop',
'.qt': 'video/quicktime',
'.spx': 'audio/ogg',
'.svg': 'image/svg+xml',
'.tga': 'image/x-tga',
'.tif': 'image/tiff',
'.tiff': 'image/tiff',
'.wav': 'audio/x-wav',
'.webm': 'video/webm',
'.webp': 'image/webp',
'.wma': 'audio/x-ms-wma',
'.wmv': 'video/x-ms-wmv',
'.woff': 'application/font-woff',
};
export function getMediaMime(path: string): string | undefined {
const ext = extname(path);
return mapExtToMediaMimes[ext.toLowerCase()];
}
| src/vs/base/common/mime.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.0001753428514348343,
0.00017068114539142698,
0.00016469284310005605,
0.0001713052624836564,
0.000002393952172496938
] |
{
"id": 2,
"code_window": [
"import { NOTEBOOK_EDITOR_CURSOR_BOUNDARY } from 'vs/workbench/contrib/notebook/common/notebookCommon';\n",
"import { Range } from 'vs/editor/common/core/range';\n",
"import { CellRevealType, CellRevealPosition, CursorAtBoundary } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';\n",
"import { IDisposable, DisposableStore } from 'vs/base/common/lifecycle';\n",
"import { CellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel';\n",
"import { EDITOR_TOP_PADDING } from 'vs/workbench/contrib/notebook/browser/constants';\n",
"\n",
"export class NotebookCellList extends WorkbenchList<CellViewModel> implements IDisposable {\n",
"\tget onWillScroll(): Event<ScrollEvent> { return this.view.onWillScroll; }\n",
"\n",
"\tget rowsContainer(): HTMLElement {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "replace",
"edit_start_line_idx": 21
} | steps:
- script: |
mkdir -p .build
echo -n $BUILD_SOURCEVERSION > .build/commit
echo -n $VSCODE_QUALITY > .build/quality
displayName: Prepare cache flag
- task: 1ESLighthouseEng.PipelineArtifactCaching.RestoreCacheV1.RestoreCache@1
inputs:
keyfile: 'build/.cachesalt, .build/commit, .build/quality'
targetfolder: '.build, out-build, out-vscode-min, out-vscode-reh-min, out-vscode-reh-web-min'
vstsFeed: 'npm-vscode'
platformIndependent: true
alias: 'Compilation'
- script: |
set -e
exit 1
displayName: Check RestoreCache
condition: and(succeeded(), ne(variables['CacheRestored-Compilation'], 'true'))
- task: NodeTool@0
inputs:
versionSpec: "12.13.0"
- task: geeklearningio.gl-vsts-tasks-yarn.yarn-installer-task.YarnInstaller@2
inputs:
versionSpec: "1.x"
- task: AzureKeyVault@1
displayName: 'Azure Key Vault: Get Secrets'
inputs:
azureSubscription: 'vscode-builds-subscription'
KeyVaultName: vscode
- task: Docker@1
displayName: 'Pull image'
inputs:
azureSubscriptionEndpoint: 'vscode-builds-subscription'
azureContainerRegistry: vscodehub.azurecr.io
command: 'Run an image'
imageName: 'vscode-linux-build-agent:$(VSCODE_ARCH)'
containerCommand: uname
- script: |
set -e
cat << EOF > ~/.netrc
machine github.com
login vscode
password $(github-distro-mixin-password)
EOF
git config user.email "[email protected]"
git config user.name "VSCode"
displayName: Prepare tooling
- script: |
set -e
git remote add distro "https://github.com/$(VSCODE_MIXIN_REPO).git"
git fetch distro
git merge $(node -p "require('./package.json').distro")
displayName: Merge distro
- task: 1ESLighthouseEng.PipelineArtifactCaching.RestoreCacheV1.RestoreCache@1
inputs:
keyfile: 'build/.cachesalt, .yarnrc, remote/.yarnrc, **/yarn.lock, !**/node_modules/**/yarn.lock, !**/.*/**/yarn.lock'
targetfolder: '**/node_modules, !**/node_modules/**/node_modules'
vstsFeed: 'npm-vscode'
- script: |
set -e
CHILD_CONCURRENCY=1 yarn --frozen-lockfile
displayName: Install dependencies
condition: and(succeeded(), ne(variables['CacheRestored'], 'true'))
- task: 1ESLighthouseEng.PipelineArtifactCaching.SaveCacheV1.SaveCache@1
inputs:
keyfile: 'build/.cachesalt, .yarnrc, remote/.yarnrc, **/yarn.lock, !**/node_modules/**/yarn.lock, !**/.*/**/yarn.lock'
targetfolder: '**/node_modules, !**/node_modules/**/node_modules'
vstsFeed: 'npm-vscode'
condition: and(succeeded(), ne(variables['CacheRestored'], 'true'))
- script: |
set -e
yarn postinstall
displayName: Run postinstall scripts
condition: and(succeeded(), eq(variables['CacheRestored'], 'true'))
- script: |
set -e
node build/azure-pipelines/mixin
displayName: Mix in quality
- script: |
set -e
CHILD_CONCURRENCY=1 ./build/azure-pipelines/linux/multiarch/$(VSCODE_ARCH)/prebuild.sh
displayName: Prebuild
- script: |
set -e
./build/azure-pipelines/linux/multiarch/$(VSCODE_ARCH)/build.sh
displayName: Build
- script: |
set -e
AZURE_DOCUMENTDB_MASTERKEY="$(builds-docdb-key-readwrite)" \
AZURE_STORAGE_ACCESS_KEY_2="$(vscode-storage-key)" \
VSCODE_MIXIN_PASSWORD="$(github-distro-mixin-password)" \
VSCODE_HOCKEYAPP_TOKEN="$(vscode-hockeyapp-token)" \
./build/azure-pipelines/linux/multiarch/$(VSCODE_ARCH)/publish.sh
displayName: Publish
- task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0
displayName: 'Component Detection'
continueOnError: true
| build/azure-pipelines/linux/product-build-linux-multiarch.yml | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.00017739887698553503,
0.00017404650861863047,
0.00017085827130358666,
0.00017392451991327107,
0.0000018353720179220545
] |
{
"id": 2,
"code_window": [
"import { NOTEBOOK_EDITOR_CURSOR_BOUNDARY } from 'vs/workbench/contrib/notebook/common/notebookCommon';\n",
"import { Range } from 'vs/editor/common/core/range';\n",
"import { CellRevealType, CellRevealPosition, CursorAtBoundary } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';\n",
"import { IDisposable, DisposableStore } from 'vs/base/common/lifecycle';\n",
"import { CellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel';\n",
"import { EDITOR_TOP_PADDING } from 'vs/workbench/contrib/notebook/browser/constants';\n",
"\n",
"export class NotebookCellList extends WorkbenchList<CellViewModel> implements IDisposable {\n",
"\tget onWillScroll(): Event<ScrollEvent> { return this.view.onWillScroll; }\n",
"\n",
"\tget rowsContainer(): HTMLElement {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "replace",
"edit_start_line_idx": 21
} | [
{
"c": "#",
"t": "source.cpp keyword.control.directive.conditional.ifndef.cpp punctuation.definition.directive.cpp",
"r": {
"dark_plus": "keyword.control: #C586C0",
"light_plus": "keyword.control: #AF00DB",
"dark_vs": "keyword.control: #569CD6",
"light_vs": "keyword.control: #0000FF",
"hc_black": "keyword.control: #C586C0"
}
},
{
"c": "ifndef",
"t": "source.cpp keyword.control.directive.conditional.ifndef.cpp",
"r": {
"dark_plus": "keyword.control: #C586C0",
"light_plus": "keyword.control: #AF00DB",
"dark_vs": "keyword.control: #569CD6",
"light_vs": "keyword.control: #0000FF",
"hc_black": "keyword.control: #C586C0"
}
},
{
"c": " ",
"t": "source.cpp meta.preprocessor.conditional.cpp",
"r": {
"dark_plus": "meta.preprocessor: #569CD6",
"light_plus": "meta.preprocessor: #0000FF",
"dark_vs": "meta.preprocessor: #569CD6",
"light_vs": "meta.preprocessor: #0000FF",
"hc_black": "meta.preprocessor: #569CD6"
}
},
{
"c": "_UCRT",
"t": "source.cpp meta.preprocessor.conditional.cpp entity.name.function.preprocessor.cpp",
"r": {
"dark_plus": "entity.name.function.preprocessor: #569CD6",
"light_plus": "entity.name.function.preprocessor: #0000FF",
"dark_vs": "entity.name.function.preprocessor: #569CD6",
"light_vs": "entity.name.function.preprocessor: #0000FF",
"hc_black": "entity.name.function: #DCDCAA"
}
},
{
"c": " ",
"t": "source.cpp meta.preprocessor.macro.cpp",
"r": {
"dark_plus": "meta.preprocessor: #569CD6",
"light_plus": "meta.preprocessor: #0000FF",
"dark_vs": "meta.preprocessor: #569CD6",
"light_vs": "meta.preprocessor: #0000FF",
"hc_black": "meta.preprocessor: #569CD6"
}
},
{
"c": "#",
"t": "source.cpp meta.preprocessor.macro.cpp keyword.control.directive.define.cpp punctuation.definition.directive.cpp",
"r": {
"dark_plus": "keyword.control: #C586C0",
"light_plus": "keyword.control: #AF00DB",
"dark_vs": "keyword.control: #569CD6",
"light_vs": "keyword.control: #0000FF",
"hc_black": "keyword.control: #C586C0"
}
},
{
"c": "define",
"t": "source.cpp meta.preprocessor.macro.cpp keyword.control.directive.define.cpp",
"r": {
"dark_plus": "keyword.control: #C586C0",
"light_plus": "keyword.control: #AF00DB",
"dark_vs": "keyword.control: #569CD6",
"light_vs": "keyword.control: #0000FF",
"hc_black": "keyword.control: #C586C0"
}
},
{
"c": " ",
"t": "source.cpp meta.preprocessor.macro.cpp",
"r": {
"dark_plus": "meta.preprocessor: #569CD6",
"light_plus": "meta.preprocessor: #0000FF",
"dark_vs": "meta.preprocessor: #569CD6",
"light_vs": "meta.preprocessor: #0000FF",
"hc_black": "meta.preprocessor: #569CD6"
}
},
{
"c": "_UCRT",
"t": "source.cpp meta.preprocessor.macro.cpp entity.name.function.preprocessor.cpp",
"r": {
"dark_plus": "entity.name.function.preprocessor: #569CD6",
"light_plus": "entity.name.function.preprocessor: #0000FF",
"dark_vs": "entity.name.function.preprocessor: #569CD6",
"light_vs": "entity.name.function.preprocessor: #0000FF",
"hc_black": "entity.name.function: #DCDCAA"
}
},
{
"c": "#",
"t": "source.cpp keyword.control.directive.endif.cpp punctuation.definition.directive.cpp",
"r": {
"dark_plus": "keyword.control: #C586C0",
"light_plus": "keyword.control: #AF00DB",
"dark_vs": "keyword.control: #569CD6",
"light_vs": "keyword.control: #0000FF",
"hc_black": "keyword.control: #C586C0"
}
},
{
"c": "endif",
"t": "source.cpp keyword.control.directive.endif.cpp",
"r": {
"dark_plus": "keyword.control: #C586C0",
"light_plus": "keyword.control: #AF00DB",
"dark_vs": "keyword.control: #569CD6",
"light_vs": "keyword.control: #0000FF",
"hc_black": "keyword.control: #C586C0"
}
}
] | extensions/cpp/test/colorize-results/test-23630_cpp.json | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.00017365040548611432,
0.0001716677361400798,
0.00016419454186689109,
0.0001725686015561223,
0.0000025631827611505287
] |
{
"id": 3,
"code_window": [
"\n",
"\t\tconst notebookEditorCursorAtBoundaryContext = NOTEBOOK_EDITOR_CURSOR_BOUNDARY.bindTo(contextKeyService);\n",
"\t\tnotebookEditorCursorAtBoundaryContext.set('none');\n",
"\n",
"\t\tlet cursorSelectionLisener: IDisposable | null = null;\n",
"\n",
"\t\tconst recomputeContext = (element: CellViewModel) => {\n",
"\t\t\tswitch (element.cursorAtBoundary()) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tlet cursorSelectionListener: IDisposable | null = null;\n",
"\t\tlet textEditorAttachListener: IDisposable | null = null;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "replace",
"edit_start_line_idx": 60
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as DOM from 'vs/base/browser/dom';
import { IListRenderer, IListVirtualDelegate, ListError } from 'vs/base/browser/ui/list/list';
import { Event } from 'vs/base/common/event';
import { ScrollEvent } from 'vs/base/common/scrollable';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IListService, IWorkbenchListOptions, WorkbenchList } from 'vs/platform/list/browser/listService';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { IMouseWheelEvent } from 'vs/base/browser/mouseEvent';
import { isMacintosh } from 'vs/base/common/platform';
import { NOTEBOOK_EDITOR_CURSOR_BOUNDARY } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { Range } from 'vs/editor/common/core/range';
import { CellRevealType, CellRevealPosition, CursorAtBoundary } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { IDisposable, DisposableStore } from 'vs/base/common/lifecycle';
import { CellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel';
import { EDITOR_TOP_PADDING } from 'vs/workbench/contrib/notebook/browser/constants';
export class NotebookCellList extends WorkbenchList<CellViewModel> implements IDisposable {
get onWillScroll(): Event<ScrollEvent> { return this.view.onWillScroll; }
get rowsContainer(): HTMLElement {
return this.view.containerDomNode;
}
private _previousSelectedElements: CellViewModel[] = [];
private _localDisposableStore = new DisposableStore();
constructor(
private listUser: string,
container: HTMLElement,
delegate: IListVirtualDelegate<CellViewModel>,
renderers: IListRenderer<CellViewModel, any>[],
contextKeyService: IContextKeyService,
options: IWorkbenchListOptions<CellViewModel>,
@IListService listService: IListService,
@IThemeService themeService: IThemeService,
@IConfigurationService configurationService: IConfigurationService,
@IKeybindingService keybindingService: IKeybindingService
) {
super(listUser, container, delegate, renderers, options, contextKeyService, listService, themeService, configurationService, keybindingService);
this._previousSelectedElements = this.getSelectedElements();
this._localDisposableStore.add(this.onDidChangeSelection((e) => {
this._previousSelectedElements.forEach(element => {
if (e.elements.indexOf(element) < 0) {
element.onDeselect();
}
});
this._previousSelectedElements = e.elements;
}));
const notebookEditorCursorAtBoundaryContext = NOTEBOOK_EDITOR_CURSOR_BOUNDARY.bindTo(contextKeyService);
notebookEditorCursorAtBoundaryContext.set('none');
let cursorSelectionLisener: IDisposable | null = null;
const recomputeContext = (element: CellViewModel) => {
switch (element.cursorAtBoundary()) {
case CursorAtBoundary.Both:
notebookEditorCursorAtBoundaryContext.set('both');
break;
case CursorAtBoundary.Top:
notebookEditorCursorAtBoundaryContext.set('top');
break;
case CursorAtBoundary.Bottom:
notebookEditorCursorAtBoundaryContext.set('bottom');
break;
default:
notebookEditorCursorAtBoundaryContext.set('none');
break;
}
return;
};
// Cursor Boundary context
this._localDisposableStore.add(this.onDidChangeFocus((e) => {
cursorSelectionLisener?.dispose();
if (e.elements.length) {
// we only validate the first focused element
const focusedElement = e.elements[0];
cursorSelectionLisener = focusedElement.onDidChangeCursorSelection(() => {
recomputeContext(focusedElement);
});
recomputeContext(focusedElement);
return;
}
// reset context
notebookEditorCursorAtBoundaryContext.set('none');
}));
}
domElementAtIndex(index: number): HTMLElement | null {
return this.view.domElement(index);
}
focusView() {
this.view.domNode.focus();
}
getAbsoluteTop(index: number): number {
if (index < 0 || index >= this.length) {
throw new ListError(this.listUser, `Invalid index ${index}`);
}
return this.view.elementTop(index);
}
triggerScrollFromMouseWheelEvent(browserEvent: IMouseWheelEvent) {
this.view.triggerScrollFromMouseWheelEvent(browserEvent);
}
updateElementHeight(index: number, size: number): void {
const focused = this.getSelection();
this.view.updateElementHeight(index, size, focused.length ? focused[0] : null);
// this.view.updateElementHeight(index, size, null);
}
// override
domFocus() {
if (document.activeElement && this.view.domNode.contains(document.activeElement)) {
// for example, when focus goes into monaco editor, if we refocus the list view, the editor will lose focus.
return;
}
if (!isMacintosh && document.activeElement && isContextMenuFocused()) {
return;
}
super.domFocus();
}
private _revealRange(index: number, range: Range, revealType: CellRevealType, newlyCreated: boolean, alignToBottom: boolean) {
const element = this.view.element(index);
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const startLineNumber = range.startLineNumber;
const lineOffset = element.getLineScrollTopOffset(startLineNumber);
const elementTop = this.view.elementTop(index);
const lineTop = elementTop + lineOffset + EDITOR_TOP_PADDING;
// TODO@rebornix 30 ---> line height * 1.5
if (lineTop < scrollTop) {
this.view.setScrollTop(lineTop - 30);
} else if (lineTop > wrapperBottom) {
this.view.setScrollTop(scrollTop + lineTop - wrapperBottom + 30);
} else if (newlyCreated) {
// newly scrolled into view
if (alignToBottom) {
// align to the bottom
this.view.setScrollTop(scrollTop + lineTop - wrapperBottom + 30);
} else {
// align to to top
this.view.setScrollTop(lineTop - 30);
}
}
if (revealType === CellRevealType.Range) {
element.revealRangeInCenter(range);
}
}
// TODO@rebornix TEST & Fix potential bugs
// List items have real dynamic heights, which means after we set `scrollTop` based on the `elementTop(index)`, the element at `index` might still be removed from the view once all relayouting tasks are done.
// For example, we scroll item 10 into the view upwards, in the first round, items 7, 8, 9, 10 are all in the viewport. Then item 7 and 8 resize themselves to be larger and finally item 10 is removed from the view.
// To ensure that item 10 is always there, we need to scroll item 10 to the top edge of the viewport.
private _revealRangeInternal(index: number, range: Range, revealType: CellRevealType) {
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const elementTop = this.view.elementTop(index);
const element = this.view.element(index);
if (element.editorAttached) {
this._revealRange(index, range, revealType, false, false);
} else {
const elementHeight = this.view.elementHeight(index);
let upwards = false;
if (elementTop + elementHeight < scrollTop) {
// scroll downwards
this.view.setScrollTop(elementTop);
upwards = false;
} else if (elementTop > wrapperBottom) {
// scroll upwards
this.view.setScrollTop(elementTop - this.view.renderHeight / 2);
upwards = true;
}
const editorAttachedPromise = new Promise((resolve, reject) => {
element.onDidChangeEditorAttachState(state => state ? resolve() : reject());
});
editorAttachedPromise.then(() => {
this._revealRange(index, range, revealType, true, upwards);
});
}
}
revealLineInView(index: number, line: number) {
this._revealRangeInternal(index, new Range(line, 1, line, 1), CellRevealType.Line);
}
revealRangeInView(index: number, range: Range): void {
this._revealRangeInternal(index, range, CellRevealType.Range);
}
private _revealRangeInCenterInternal(index: number, range: Range, revealType: CellRevealType) {
const reveal = (index: number, range: Range, revealType: CellRevealType) => {
const element = this.view.element(index);
let lineOffset = element.getLineScrollTopOffset(range.startLineNumber);
let lineOffsetInView = this.view.elementTop(index) + lineOffset;
this.view.setScrollTop(lineOffsetInView - this.view.renderHeight / 2);
if (revealType === CellRevealType.Range) {
element.revealRangeInCenter(range);
}
};
const elementTop = this.view.elementTop(index);
const viewItemOffset = elementTop;
this.view.setScrollTop(viewItemOffset - this.view.renderHeight / 2);
const element = this.view.element(index);
if (!element.editorAttached) {
getEditorAttachedPromise(element).then(() => reveal(index, range, revealType));
} else {
reveal(index, range, revealType);
}
}
revealLineInCenter(index: number, line: number) {
this._revealRangeInCenterInternal(index, new Range(line, 1, line, 1), CellRevealType.Line);
}
revealRangeInCenter(index: number, range: Range): void {
this._revealRangeInCenterInternal(index, range, CellRevealType.Range);
}
private _revealRangeInCenterIfOutsideViewportInternal(index: number, range: Range, revealType: CellRevealType) {
const reveal = (index: number, range: Range, revealType: CellRevealType) => {
const element = this.view.element(index);
let lineOffset = element.getLineScrollTopOffset(range.startLineNumber);
let lineOffsetInView = this.view.elementTop(index) + lineOffset;
this.view.setScrollTop(lineOffsetInView - this.view.renderHeight / 2);
if (revealType === CellRevealType.Range) {
setTimeout(() => {
element.revealRangeInCenter(range);
}, 240);
}
};
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const elementTop = this.view.elementTop(index);
const viewItemOffset = elementTop;
const element = this.view.element(index);
if (viewItemOffset < scrollTop || viewItemOffset > wrapperBottom) {
// let it render
this.view.setScrollTop(viewItemOffset - this.view.renderHeight / 2);
// after rendering, it might be pushed down due to markdown cell dynamic height
const elementTop = this.view.elementTop(index);
this.view.setScrollTop(elementTop - this.view.renderHeight / 2);
// reveal editor
if (!element.editorAttached) {
getEditorAttachedPromise(element).then(() => reveal(index, range, revealType));
} else {
// for example markdown
}
} else {
if (element.editorAttached) {
element.revealRangeInCenter(range);
} else {
// for example, markdown cell in preview mode
getEditorAttachedPromise(element).then(() => reveal(index, range, revealType));
}
}
}
revealLineInCenterIfOutsideViewport(index: number, line: number) {
this._revealRangeInCenterIfOutsideViewportInternal(index, new Range(line, 1, line, 1), CellRevealType.Line);
}
revealRangeInCenterIfOutsideViewport(index: number, range: Range): void {
this._revealRangeInCenterIfOutsideViewportInternal(index, range, CellRevealType.Range);
}
private _revealInternal(index: number, ignoreIfInsideViewport: boolean, revealPosition: CellRevealPosition) {
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const elementTop = this.view.elementTop(index);
if (ignoreIfInsideViewport && elementTop >= scrollTop && elementTop < wrapperBottom) {
// inside the viewport
return;
}
// first render
const viewItemOffset = revealPosition === CellRevealPosition.Top ? elementTop : (elementTop - this.view.renderHeight / 2);
this.view.setScrollTop(viewItemOffset);
// second scroll as markdown cell is dynamic
const newElementTop = this.view.elementTop(index);
const newViewItemOffset = revealPosition === CellRevealPosition.Top ? newElementTop : (newElementTop - this.view.renderHeight / 2);
this.view.setScrollTop(newViewItemOffset);
}
revealInView(index: number) {
this._revealInternal(index, true, CellRevealPosition.Top);
}
revealInCenter(index: number) {
this._revealInternal(index, false, CellRevealPosition.Center);
}
revealInCenterIfOutsideViewport(index: number) {
this._revealInternal(index, true, CellRevealPosition.Center);
}
setCellSelection(index: number, range: Range) {
const element = this.view.element(index);
if (element.editorAttached) {
element.setSelection(range);
} else {
getEditorAttachedPromise(element).then(() => { element.setSelection(range); });
}
}
dispose() {
this._localDisposableStore.dispose();
super.dispose();
}
}
function getEditorAttachedPromise(element: CellViewModel) {
return new Promise((resolve, reject) => {
Event.once(element.onDidChangeEditorAttachState)(state => state ? resolve() : reject());
});
}
function isContextMenuFocused() {
return !!DOM.findParentWithClass(<HTMLElement>document.activeElement, 'context-view');
}
| src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts | 1 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.9992515444755554,
0.13943035900592804,
0.00016631383914500475,
0.0002047800226137042,
0.34500551223754883
] |
{
"id": 3,
"code_window": [
"\n",
"\t\tconst notebookEditorCursorAtBoundaryContext = NOTEBOOK_EDITOR_CURSOR_BOUNDARY.bindTo(contextKeyService);\n",
"\t\tnotebookEditorCursorAtBoundaryContext.set('none');\n",
"\n",
"\t\tlet cursorSelectionLisener: IDisposable | null = null;\n",
"\n",
"\t\tconst recomputeContext = (element: CellViewModel) => {\n",
"\t\t\tswitch (element.cursorAtBoundary()) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tlet cursorSelectionListener: IDisposable | null = null;\n",
"\t\tlet textEditorAttachListener: IDisposable | null = null;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "replace",
"edit_start_line_idx": 60
} | /*---------------------------------------------------------------------------------------------
* 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 { CallHierarchyProviderRegistry, CallHierarchyDirection, CallHierarchyModel } from 'vs/workbench/contrib/callHierarchy/common/callHierarchy';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { CallHierarchyTreePeekWidget } from 'vs/workbench/contrib/callHierarchy/browser/callHierarchyPeek';
import { Event } from 'vs/base/common/event';
import { registerEditorContribution, registerEditorAction, EditorAction, registerEditorCommand, EditorCommand } from 'vs/editor/browser/editorExtensions';
import { IEditorContribution } from 'vs/editor/common/editorCommon';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { IContextKeyService, RawContextKey, IContextKey, ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { PeekContext } from 'vs/editor/contrib/peekView/peekView';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import { Range } from 'vs/editor/common/core/range';
import { IPosition } from 'vs/editor/common/core/position';
import { MenuId } from 'vs/platform/actions/common/actions';
const _ctxHasCallHierarchyProvider = new RawContextKey<boolean>('editorHasCallHierarchyProvider', false);
const _ctxCallHierarchyVisible = new RawContextKey<boolean>('callHierarchyVisible', false);
class CallHierarchyController implements IEditorContribution {
static readonly Id = 'callHierarchy';
static get(editor: ICodeEditor): CallHierarchyController {
return editor.getContribution<CallHierarchyController>(CallHierarchyController.Id);
}
private static readonly _StorageDirection = 'callHierarchy/defaultDirection';
private readonly _ctxHasProvider: IContextKey<boolean>;
private readonly _ctxIsVisible: IContextKey<boolean>;
private readonly _dispoables = new DisposableStore();
private readonly _sessionDisposables = new DisposableStore();
private _widget?: CallHierarchyTreePeekWidget;
constructor(
private readonly _editor: ICodeEditor,
@IContextKeyService private readonly _contextKeyService: IContextKeyService,
@IStorageService private readonly _storageService: IStorageService,
@ICodeEditorService private readonly _editorService: ICodeEditorService,
@IInstantiationService private readonly _instantiationService: IInstantiationService,
) {
this._ctxIsVisible = _ctxCallHierarchyVisible.bindTo(this._contextKeyService);
this._ctxHasProvider = _ctxHasCallHierarchyProvider.bindTo(this._contextKeyService);
this._dispoables.add(Event.any<any>(_editor.onDidChangeModel, _editor.onDidChangeModelLanguage, CallHierarchyProviderRegistry.onDidChange)(() => {
this._ctxHasProvider.set(_editor.hasModel() && CallHierarchyProviderRegistry.has(_editor.getModel()));
}));
this._dispoables.add(this._sessionDisposables);
}
dispose(): void {
this._ctxHasProvider.reset();
this._ctxIsVisible.reset();
this._dispoables.dispose();
}
async startCallHierarchyFromEditor(): Promise<void> {
this._sessionDisposables.clear();
if (!this._editor.hasModel()) {
return;
}
const document = this._editor.getModel();
const position = this._editor.getPosition();
if (!CallHierarchyProviderRegistry.has(document)) {
return;
}
const cts = new CancellationTokenSource();
const model = CallHierarchyModel.create(document, position, cts.token);
const direction = this._storageService.getNumber(CallHierarchyController._StorageDirection, StorageScope.GLOBAL, <number>CallHierarchyDirection.CallsFrom);
this._showCallHierarchyWidget(position, direction, model, cts);
}
async startCallHierarchyFromCallHierarchy(): Promise<void> {
if (!this._widget) {
return;
}
const model = this._widget.getModel();
const call = this._widget.getFocused();
if (!call || !model) {
return;
}
const newEditor = await this._editorService.openCodeEditor({ resource: call.item.uri }, this._editor);
if (!newEditor) {
return;
}
const newModel = model.fork(call.item);
this._sessionDisposables.clear();
CallHierarchyController.get(newEditor)._showCallHierarchyWidget(
Range.lift(newModel.root.selectionRange).getStartPosition(),
this._widget.direction,
Promise.resolve(newModel),
new CancellationTokenSource()
);
}
private _showCallHierarchyWidget(position: IPosition, direction: number, model: Promise<CallHierarchyModel | undefined>, cts: CancellationTokenSource) {
Event.any<any>(this._editor.onDidChangeModel, this._editor.onDidChangeModelLanguage)(this.endCallHierarchy, this, this._sessionDisposables);
this._widget = this._instantiationService.createInstance(CallHierarchyTreePeekWidget, this._editor, position, direction);
this._widget.showLoading();
this._ctxIsVisible.set(true);
this._sessionDisposables.add(this._widget.onDidClose(() => {
this.endCallHierarchy();
this._storageService.store(CallHierarchyController._StorageDirection, this._widget!.direction, StorageScope.GLOBAL);
}));
this._sessionDisposables.add({ dispose() { cts.dispose(true); } });
this._sessionDisposables.add(this._widget);
model.then(model => {
if (cts.token.isCancellationRequested) {
return; // nothing
}
if (model) {
this._sessionDisposables.add(model);
this._widget!.showModel(model);
}
else {
this._widget!.showMessage(localize('no.item', "No results"));
}
}).catch(e => {
this._widget!.showMessage(localize('error', "Failed to show call hierarchy"));
console.error(e);
});
}
toggleCallHierarchyDirection(): void {
if (this._widget) {
this._widget.toggleDirection();
}
}
endCallHierarchy(): void {
this._sessionDisposables.clear();
this._ctxIsVisible.set(false);
this._editor.focus();
}
}
registerEditorContribution(CallHierarchyController.Id, CallHierarchyController);
registerEditorAction(class extends EditorAction {
constructor() {
super({
id: 'editor.showCallHierarchy',
label: localize('title', "Peek Call Hierarchy"),
alias: 'Peek Call Hierarchy',
contextMenuOpts: {
menuId: MenuId.EditorContextPeek,
group: 'navigation',
order: 1000
},
kbOpts: {
kbExpr: EditorContextKeys.editorTextFocus,
weight: KeybindingWeight.WorkbenchContrib,
primary: KeyMod.Shift + KeyMod.Alt + KeyCode.KEY_H
},
precondition: ContextKeyExpr.and(
_ctxHasCallHierarchyProvider,
PeekContext.notInPeekEditor
)
});
}
async run(_accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> {
return CallHierarchyController.get(editor).startCallHierarchyFromEditor();
}
});
registerEditorAction(class extends EditorAction {
constructor() {
super({
id: 'editor.toggleCallHierarchy',
label: localize('title.toggle', "Toggle Call Hierarchy"),
alias: 'Toggle Call Hierarchy',
kbOpts: {
weight: KeybindingWeight.WorkbenchContrib,
primary: KeyMod.Shift + KeyMod.Alt + KeyCode.KEY_H
},
precondition: _ctxCallHierarchyVisible
});
}
async run(_accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> {
return CallHierarchyController.get(editor).toggleCallHierarchyDirection();
}
});
registerEditorAction(class extends EditorAction {
constructor() {
super({
id: 'editor.refocusCallHierarchy',
label: localize('title.refocus', "Refocus Call Hierarchy"),
alias: 'Refocus Call Hierarchy',
kbOpts: {
weight: KeybindingWeight.WorkbenchContrib,
primary: KeyMod.Shift + KeyCode.Enter
},
precondition: _ctxCallHierarchyVisible
});
}
async run(_accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> {
return CallHierarchyController.get(editor).startCallHierarchyFromCallHierarchy();
}
});
registerEditorCommand(new class extends EditorCommand {
constructor() {
super({
id: 'editor.closeCallHierarchy',
kbOpts: {
weight: KeybindingWeight.WorkbenchContrib + 10,
primary: KeyCode.Escape
},
precondition: ContextKeyExpr.and(
_ctxCallHierarchyVisible,
ContextKeyExpr.not('config.editor.stablePeek')
)
});
}
runEditorCommand(_accessor: ServicesAccessor, editor: ICodeEditor): void {
return CallHierarchyController.get(editor).endCallHierarchy();
}
});
| src/vs/workbench/contrib/callHierarchy/browser/callHierarchy.contribution.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.00023688604414928705,
0.00017441991076339036,
0.00016743739251978695,
0.00017144186131190509,
0.000012974707715329714
] |
{
"id": 3,
"code_window": [
"\n",
"\t\tconst notebookEditorCursorAtBoundaryContext = NOTEBOOK_EDITOR_CURSOR_BOUNDARY.bindTo(contextKeyService);\n",
"\t\tnotebookEditorCursorAtBoundaryContext.set('none');\n",
"\n",
"\t\tlet cursorSelectionLisener: IDisposable | null = null;\n",
"\n",
"\t\tconst recomputeContext = (element: CellViewModel) => {\n",
"\t\t\tswitch (element.cursorAtBoundary()) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tlet cursorSelectionListener: IDisposable | null = null;\n",
"\t\tlet textEditorAttachListener: IDisposable | null = null;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "replace",
"edit_start_line_idx": 60
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./standalone-tokens';
import { IDisposable } from 'vs/base/common/lifecycle';
import { URI } from 'vs/base/common/uri';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import { OpenerService } from 'vs/editor/browser/services/openerService';
import { DiffNavigator, IDiffNavigator } from 'vs/editor/browser/widget/diffNavigator';
import { EditorOptions, ConfigurationChangedEvent } from 'vs/editor/common/config/editorOptions';
import { BareFontInfo, FontInfo } from 'vs/editor/common/config/fontInfo';
import { Token } from 'vs/editor/common/core/token';
import { IEditor, EditorType } from 'vs/editor/common/editorCommon';
import { FindMatch, ITextModel, TextModelResolvedOptions } from 'vs/editor/common/model';
import * as modes from 'vs/editor/common/modes';
import { NULL_STATE, nullTokenize } from 'vs/editor/common/modes/nullMode';
import { IEditorWorkerService } from 'vs/editor/common/services/editorWorkerService';
import { ILanguageSelection } from 'vs/editor/common/services/modeService';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { IWebWorkerOptions, MonacoWebWorker, createWebWorker as actualCreateWebWorker } from 'vs/editor/common/services/webWorker';
import * as standaloneEnums from 'vs/editor/common/standalone/standaloneEnums';
import { Colorizer, IColorizerElementOptions, IColorizerOptions } from 'vs/editor/standalone/browser/colorizer';
import { SimpleEditorModelResolverService } from 'vs/editor/standalone/browser/simpleServices';
import { IDiffEditorConstructionOptions, IStandaloneEditorConstructionOptions, IStandaloneCodeEditor, IStandaloneDiffEditor, StandaloneDiffEditor, StandaloneEditor } from 'vs/editor/standalone/browser/standaloneCodeEditor';
import { DynamicStandaloneServices, IEditorOverrideServices, StaticServices } from 'vs/editor/standalone/browser/standaloneServices';
import { IStandaloneThemeData, IStandaloneThemeService } from 'vs/editor/standalone/common/standaloneThemeService';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IContextViewService, IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IMarker, IMarkerData } from 'vs/platform/markers/common/markers';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { IAccessibilityService } from 'vs/platform/accessibility/common/accessibility';
import { clearAllFontInfos } from 'vs/editor/browser/config/configuration';
import { IEditorProgressService } from 'vs/platform/progress/common/progress';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
function withAllStandaloneServices<T extends IEditor>(domElement: HTMLElement, override: IEditorOverrideServices, callback: (services: DynamicStandaloneServices) => T): T {
let services = new DynamicStandaloneServices(domElement, override);
let simpleEditorModelResolverService: SimpleEditorModelResolverService | null = null;
if (!services.has(ITextModelService)) {
simpleEditorModelResolverService = new SimpleEditorModelResolverService(StaticServices.modelService.get());
services.set(ITextModelService, simpleEditorModelResolverService);
}
if (!services.has(IOpenerService)) {
services.set(IOpenerService, new OpenerService(services.get(ICodeEditorService), services.get(ICommandService)));
}
let result = callback(services);
if (simpleEditorModelResolverService) {
simpleEditorModelResolverService.setEditor(result);
}
return result;
}
/**
* Create a new editor under `domElement`.
* `domElement` should be empty (not contain other dom nodes).
* The editor will read the size of `domElement`.
*/
export function create(domElement: HTMLElement, options?: IStandaloneEditorConstructionOptions, override?: IEditorOverrideServices): IStandaloneCodeEditor {
return withAllStandaloneServices(domElement, override || {}, (services) => {
return new StandaloneEditor(
domElement,
options,
services,
services.get(IInstantiationService),
services.get(ICodeEditorService),
services.get(ICommandService),
services.get(IContextKeyService),
services.get(IKeybindingService),
services.get(IContextViewService),
services.get(IStandaloneThemeService),
services.get(INotificationService),
services.get(IConfigurationService),
services.get(IAccessibilityService)
);
});
}
/**
* Emitted when an editor is created.
* Creating a diff editor might cause this listener to be invoked with the two editors.
* @event
*/
export function onDidCreateEditor(listener: (codeEditor: ICodeEditor) => void): IDisposable {
return StaticServices.codeEditorService.get().onCodeEditorAdd((editor) => {
listener(<ICodeEditor>editor);
});
}
/**
* Create a new diff editor under `domElement`.
* `domElement` should be empty (not contain other dom nodes).
* The editor will read the size of `domElement`.
*/
export function createDiffEditor(domElement: HTMLElement, options?: IDiffEditorConstructionOptions, override?: IEditorOverrideServices): IStandaloneDiffEditor {
return withAllStandaloneServices(domElement, override || {}, (services) => {
return new StandaloneDiffEditor(
domElement,
options,
services,
services.get(IInstantiationService),
services.get(IContextKeyService),
services.get(IKeybindingService),
services.get(IContextViewService),
services.get(IEditorWorkerService),
services.get(ICodeEditorService),
services.get(IStandaloneThemeService),
services.get(INotificationService),
services.get(IConfigurationService),
services.get(IContextMenuService),
services.get(IEditorProgressService),
services.get(IClipboardService)
);
});
}
export interface IDiffNavigatorOptions {
readonly followsCaret?: boolean;
readonly ignoreCharChanges?: boolean;
readonly alwaysRevealFirst?: boolean;
}
export function createDiffNavigator(diffEditor: IStandaloneDiffEditor, opts?: IDiffNavigatorOptions): IDiffNavigator {
return new DiffNavigator(diffEditor, opts);
}
function doCreateModel(value: string, languageSelection: ILanguageSelection, uri?: URI): ITextModel {
return StaticServices.modelService.get().createModel(value, languageSelection, uri);
}
/**
* Create a new editor model.
* You can specify the language that should be set for this model or let the language be inferred from the `uri`.
*/
export function createModel(value: string, language?: string, uri?: URI): ITextModel {
value = value || '';
if (!language) {
let firstLF = value.indexOf('\n');
let firstLine = value;
if (firstLF !== -1) {
firstLine = value.substring(0, firstLF);
}
return doCreateModel(value, StaticServices.modeService.get().createByFilepathOrFirstLine(uri || null, firstLine), uri);
}
return doCreateModel(value, StaticServices.modeService.get().create(language), uri);
}
/**
* Change the language for a model.
*/
export function setModelLanguage(model: ITextModel, languageId: string): void {
StaticServices.modelService.get().setMode(model, StaticServices.modeService.get().create(languageId));
}
/**
* Set the markers for a model.
*/
export function setModelMarkers(model: ITextModel, owner: string, markers: IMarkerData[]): void {
if (model) {
StaticServices.markerService.get().changeOne(owner, model.uri, markers);
}
}
/**
* Get markers for owner and/or resource
*
* @returns list of markers
*/
export function getModelMarkers(filter: { owner?: string, resource?: URI, take?: number }): IMarker[] {
return StaticServices.markerService.get().read(filter);
}
/**
* Get the model that has `uri` if it exists.
*/
export function getModel(uri: URI): ITextModel | null {
return StaticServices.modelService.get().getModel(uri);
}
/**
* Get all the created models.
*/
export function getModels(): ITextModel[] {
return StaticServices.modelService.get().getModels();
}
/**
* Emitted when a model is created.
* @event
*/
export function onDidCreateModel(listener: (model: ITextModel) => void): IDisposable {
return StaticServices.modelService.get().onModelAdded(listener);
}
/**
* Emitted right before a model is disposed.
* @event
*/
export function onWillDisposeModel(listener: (model: ITextModel) => void): IDisposable {
return StaticServices.modelService.get().onModelRemoved(listener);
}
/**
* Emitted when a different language is set to a model.
* @event
*/
export function onDidChangeModelLanguage(listener: (e: { readonly model: ITextModel; readonly oldLanguage: string; }) => void): IDisposable {
return StaticServices.modelService.get().onModelModeChanged((e) => {
listener({
model: e.model,
oldLanguage: e.oldModeId
});
});
}
/**
* Create a new web worker that has model syncing capabilities built in.
* Specify an AMD module to load that will `create` an object that will be proxied.
*/
export function createWebWorker<T>(opts: IWebWorkerOptions): MonacoWebWorker<T> {
return actualCreateWebWorker<T>(StaticServices.modelService.get(), opts);
}
/**
* Colorize the contents of `domNode` using attribute `data-lang`.
*/
export function colorizeElement(domNode: HTMLElement, options: IColorizerElementOptions): Promise<void> {
return Colorizer.colorizeElement(StaticServices.standaloneThemeService.get(), StaticServices.modeService.get(), domNode, options);
}
/**
* Colorize `text` using language `languageId`.
*/
export function colorize(text: string, languageId: string, options: IColorizerOptions): Promise<string> {
return Colorizer.colorize(StaticServices.modeService.get(), text, languageId, options);
}
/**
* Colorize a line in a model.
*/
export function colorizeModelLine(model: ITextModel, lineNumber: number, tabSize: number = 4): string {
return Colorizer.colorizeModelLine(model, lineNumber, tabSize);
}
/**
* @internal
*/
function getSafeTokenizationSupport(language: string): Omit<modes.ITokenizationSupport, 'tokenize2'> {
let tokenizationSupport = modes.TokenizationRegistry.get(language);
if (tokenizationSupport) {
return tokenizationSupport;
}
return {
getInitialState: () => NULL_STATE,
tokenize: (line: string, state: modes.IState, deltaOffset: number) => nullTokenize(language, line, state, deltaOffset)
};
}
/**
* Tokenize `text` using language `languageId`
*/
export function tokenize(text: string, languageId: string): Token[][] {
let modeService = StaticServices.modeService.get();
// Needed in order to get the mode registered for subsequent look-ups
modeService.triggerMode(languageId);
let tokenizationSupport = getSafeTokenizationSupport(languageId);
let lines = text.split(/\r\n|\r|\n/);
let result: Token[][] = [];
let state = tokenizationSupport.getInitialState();
for (let i = 0, len = lines.length; i < len; i++) {
let line = lines[i];
let tokenizationResult = tokenizationSupport.tokenize(line, state, 0);
result[i] = tokenizationResult.tokens;
state = tokenizationResult.endState;
}
return result;
}
/**
* Define a new theme or update an existing theme.
*/
export function defineTheme(themeName: string, themeData: IStandaloneThemeData): void {
StaticServices.standaloneThemeService.get().defineTheme(themeName, themeData);
}
/**
* Switches to a theme.
*/
export function setTheme(themeName: string): void {
StaticServices.standaloneThemeService.get().setTheme(themeName);
}
/**
* Clears all cached font measurements and triggers re-measurement.
*/
export function remeasureFonts(): void {
clearAllFontInfos();
}
/**
* @internal
*/
export function createMonacoEditorAPI(): typeof monaco.editor {
return {
// methods
create: <any>create,
onDidCreateEditor: <any>onDidCreateEditor,
createDiffEditor: <any>createDiffEditor,
createDiffNavigator: <any>createDiffNavigator,
createModel: <any>createModel,
setModelLanguage: <any>setModelLanguage,
setModelMarkers: <any>setModelMarkers,
getModelMarkers: <any>getModelMarkers,
getModels: <any>getModels,
getModel: <any>getModel,
onDidCreateModel: <any>onDidCreateModel,
onWillDisposeModel: <any>onWillDisposeModel,
onDidChangeModelLanguage: <any>onDidChangeModelLanguage,
createWebWorker: <any>createWebWorker,
colorizeElement: <any>colorizeElement,
colorize: <any>colorize,
colorizeModelLine: <any>colorizeModelLine,
tokenize: <any>tokenize,
defineTheme: <any>defineTheme,
setTheme: <any>setTheme,
remeasureFonts: remeasureFonts,
// enums
AccessibilitySupport: standaloneEnums.AccessibilitySupport,
ContentWidgetPositionPreference: standaloneEnums.ContentWidgetPositionPreference,
CursorChangeReason: standaloneEnums.CursorChangeReason,
DefaultEndOfLine: standaloneEnums.DefaultEndOfLine,
EditorAutoIndentStrategy: standaloneEnums.EditorAutoIndentStrategy,
EditorOption: standaloneEnums.EditorOption,
EndOfLinePreference: standaloneEnums.EndOfLinePreference,
EndOfLineSequence: standaloneEnums.EndOfLineSequence,
MinimapPosition: standaloneEnums.MinimapPosition,
MouseTargetType: standaloneEnums.MouseTargetType,
OverlayWidgetPositionPreference: standaloneEnums.OverlayWidgetPositionPreference,
OverviewRulerLane: standaloneEnums.OverviewRulerLane,
RenderLineNumbersType: standaloneEnums.RenderLineNumbersType,
RenderMinimap: standaloneEnums.RenderMinimap,
ScrollbarVisibility: standaloneEnums.ScrollbarVisibility,
ScrollType: standaloneEnums.ScrollType,
TextEditorCursorBlinkingStyle: standaloneEnums.TextEditorCursorBlinkingStyle,
TextEditorCursorStyle: standaloneEnums.TextEditorCursorStyle,
TrackedRangeStickiness: standaloneEnums.TrackedRangeStickiness,
WrappingIndent: standaloneEnums.WrappingIndent,
// classes
ConfigurationChangedEvent: <any>ConfigurationChangedEvent,
BareFontInfo: <any>BareFontInfo,
FontInfo: <any>FontInfo,
TextModelResolvedOptions: <any>TextModelResolvedOptions,
FindMatch: <any>FindMatch,
// vars
EditorType: EditorType,
EditorOptions: <any>EditorOptions
};
}
| src/vs/editor/standalone/browser/standaloneEditor.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.003212575800716877,
0.00035960657987743616,
0.00016320179565809667,
0.00017103170102927834,
0.0006474384572356939
] |
{
"id": 3,
"code_window": [
"\n",
"\t\tconst notebookEditorCursorAtBoundaryContext = NOTEBOOK_EDITOR_CURSOR_BOUNDARY.bindTo(contextKeyService);\n",
"\t\tnotebookEditorCursorAtBoundaryContext.set('none');\n",
"\n",
"\t\tlet cursorSelectionLisener: IDisposable | null = null;\n",
"\n",
"\t\tconst recomputeContext = (element: CellViewModel) => {\n",
"\t\t\tswitch (element.cursorAtBoundary()) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tlet cursorSelectionListener: IDisposable | null = null;\n",
"\t\tlet textEditorAttachListener: IDisposable | null = null;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "replace",
"edit_start_line_idx": 60
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as strings from 'vs/base/common/strings';
import { ILocalization } from 'vs/platform/localizations/common/localizations';
import { URI } from 'vs/base/common/uri';
export const MANIFEST_CACHE_FOLDER = 'CachedExtensions';
export const USER_MANIFEST_CACHE_FILE = 'user';
export const BUILTIN_MANIFEST_CACHE_FILE = 'builtin';
export interface ICommand {
command: string;
title: string;
category?: string;
}
export interface IConfigurationProperty {
description: string;
type: string | string[];
default?: any;
}
export interface IConfiguration {
properties: { [key: string]: IConfigurationProperty; };
}
export interface IDebugger {
label?: string;
type: string;
runtime?: string;
}
export interface IGrammar {
language: string;
}
export interface IJSONValidation {
fileMatch: string | string[];
url: string;
}
export interface IKeyBinding {
command: string;
key: string;
when?: string;
mac?: string;
linux?: string;
win?: string;
}
export interface ILanguage {
id: string;
extensions: string[];
aliases: string[];
}
export interface IMenu {
command: string;
alt?: string;
when?: string;
group?: string;
}
export interface ISnippet {
language: string;
}
export interface ITheme {
label: string;
}
export interface IViewContainer {
id: string;
title: string;
}
export interface IView {
id: string;
name: string;
}
export interface IColor {
id: string;
description: string;
defaults: { light: string, dark: string, highContrast: string };
}
export interface IWebviewEditor {
readonly viewType: string;
readonly priority: string;
readonly selector: readonly {
readonly filenamePattern?: string;
}[];
}
export interface ICodeActionContributionAction {
readonly kind: string;
readonly title: string;
readonly description?: string;
}
export interface ICodeActionContribution {
readonly languages: readonly string[];
readonly actions: readonly ICodeActionContributionAction[];
}
export interface IExtensionContributions {
commands?: ICommand[];
configuration?: IConfiguration | IConfiguration[];
debuggers?: IDebugger[];
grammars?: IGrammar[];
jsonValidation?: IJSONValidation[];
keybindings?: IKeyBinding[];
languages?: ILanguage[];
menus?: { [context: string]: IMenu[] };
snippets?: ISnippet[];
themes?: ITheme[];
iconThemes?: ITheme[];
viewsContainers?: { [location: string]: IViewContainer[] };
views?: { [location: string]: IView[] };
colors?: IColor[];
localizations?: ILocalization[];
readonly customEditors?: readonly IWebviewEditor[];
readonly codeActions?: readonly ICodeActionContribution[];
}
export type ExtensionKind = 'ui' | 'workspace' | 'web';
export function isIExtensionIdentifier(thing: any): thing is IExtensionIdentifier {
return thing
&& typeof thing === 'object'
&& typeof thing.id === 'string'
&& (!thing.uuid || typeof thing.uuid === 'string');
}
export interface IExtensionIdentifier {
id: string;
uuid?: string;
}
export interface IExtensionManifest {
readonly name: string;
readonly displayName?: string;
readonly publisher: string;
readonly version: string;
readonly engines: { vscode: string };
readonly description?: string;
readonly main?: string;
readonly icon?: string;
readonly categories?: string[];
readonly keywords?: string[];
readonly activationEvents?: string[];
readonly extensionDependencies?: string[];
readonly extensionPack?: string[];
readonly extensionKind?: ExtensionKind | ExtensionKind[];
readonly contributes?: IExtensionContributions;
readonly repository?: { url: string; };
readonly bugs?: { url: string; };
readonly enableProposedApi?: boolean;
readonly api?: string;
readonly scripts?: { [key: string]: string; };
}
export const enum ExtensionType {
System,
User
}
export interface IExtension {
readonly type: ExtensionType;
readonly identifier: IExtensionIdentifier;
readonly manifest: IExtensionManifest;
readonly location: URI;
}
/**
* **!Do not construct directly!**
*
* **!Only static methods because it gets serialized!**
*
* This represents the "canonical" version for an extension identifier. Extension ids
* have to be case-insensitive (due to the marketplace), but we must ensure case
* preservation because the extension API is already public at this time.
*
* For example, given an extension with the publisher `"Hello"` and the name `"World"`,
* its canonical extension identifier is `"Hello.World"`. This extension could be
* referenced in some other extension's dependencies using the string `"hello.world"`.
*
* To make matters more complicated, an extension can optionally have an UUID. When two
* extensions have the same UUID, they are considered equal even if their identifier is different.
*/
export class ExtensionIdentifier {
public readonly value: string;
private readonly _lower: string;
constructor(value: string) {
this.value = value;
this._lower = value.toLowerCase();
}
public static equals(a: ExtensionIdentifier | string | null | undefined, b: ExtensionIdentifier | string | null | undefined) {
if (typeof a === 'undefined' || a === null) {
return (typeof b === 'undefined' || b === null);
}
if (typeof b === 'undefined' || b === null) {
return false;
}
if (typeof a === 'string' || typeof b === 'string') {
// At least one of the arguments is an extension id in string form,
// so we have to use the string comparison which ignores case.
let aValue = (typeof a === 'string' ? a : a.value);
let bValue = (typeof b === 'string' ? b : b.value);
return strings.equalsIgnoreCase(aValue, bValue);
}
// Now we know both arguments are ExtensionIdentifier
return (a._lower === b._lower);
}
/**
* Gives the value by which to index (for equality).
*/
public static toKey(id: ExtensionIdentifier | string): string {
if (typeof id === 'string') {
return id.toLowerCase();
}
return id._lower;
}
}
export interface IExtensionDescription extends IExtensionManifest {
readonly identifier: ExtensionIdentifier;
readonly uuid?: string;
readonly isBuiltin: boolean;
readonly isUnderDevelopment: boolean;
readonly extensionLocation: URI;
enableProposedApi?: boolean;
}
export function isLanguagePackExtension(manifest: IExtensionManifest): boolean {
return manifest.contributes && manifest.contributes.localizations ? manifest.contributes.localizations.length > 0 : false;
}
| src/vs/platform/extensions/common/extensions.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.000430231710197404,
0.00018581417680252343,
0.00016520274220965803,
0.0001747801579767838,
0.00005170976874069311
] |
{
"id": 4,
"code_window": [
"\t\t\t}\n",
"\t\t\treturn;\n",
"\t\t};\n",
"\n",
"\t\t// Cursor Boundary context\n",
"\t\tthis._localDisposableStore.add(this.onDidChangeFocus((e) => {\n",
"\t\t\tcursorSelectionLisener?.dispose();\n",
"\t\t\tif (e.elements.length) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\tthis._localDisposableStore.add(this.onDidChangeSelection((e) => {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "replace",
"edit_start_line_idx": 81
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as DOM from 'vs/base/browser/dom';
import { IListRenderer, IListVirtualDelegate, ListError } from 'vs/base/browser/ui/list/list';
import { Event } from 'vs/base/common/event';
import { ScrollEvent } from 'vs/base/common/scrollable';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IListService, IWorkbenchListOptions, WorkbenchList } from 'vs/platform/list/browser/listService';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { IMouseWheelEvent } from 'vs/base/browser/mouseEvent';
import { isMacintosh } from 'vs/base/common/platform';
import { NOTEBOOK_EDITOR_CURSOR_BOUNDARY } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { Range } from 'vs/editor/common/core/range';
import { CellRevealType, CellRevealPosition, CursorAtBoundary } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { IDisposable, DisposableStore } from 'vs/base/common/lifecycle';
import { CellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel';
import { EDITOR_TOP_PADDING } from 'vs/workbench/contrib/notebook/browser/constants';
export class NotebookCellList extends WorkbenchList<CellViewModel> implements IDisposable {
get onWillScroll(): Event<ScrollEvent> { return this.view.onWillScroll; }
get rowsContainer(): HTMLElement {
return this.view.containerDomNode;
}
private _previousSelectedElements: CellViewModel[] = [];
private _localDisposableStore = new DisposableStore();
constructor(
private listUser: string,
container: HTMLElement,
delegate: IListVirtualDelegate<CellViewModel>,
renderers: IListRenderer<CellViewModel, any>[],
contextKeyService: IContextKeyService,
options: IWorkbenchListOptions<CellViewModel>,
@IListService listService: IListService,
@IThemeService themeService: IThemeService,
@IConfigurationService configurationService: IConfigurationService,
@IKeybindingService keybindingService: IKeybindingService
) {
super(listUser, container, delegate, renderers, options, contextKeyService, listService, themeService, configurationService, keybindingService);
this._previousSelectedElements = this.getSelectedElements();
this._localDisposableStore.add(this.onDidChangeSelection((e) => {
this._previousSelectedElements.forEach(element => {
if (e.elements.indexOf(element) < 0) {
element.onDeselect();
}
});
this._previousSelectedElements = e.elements;
}));
const notebookEditorCursorAtBoundaryContext = NOTEBOOK_EDITOR_CURSOR_BOUNDARY.bindTo(contextKeyService);
notebookEditorCursorAtBoundaryContext.set('none');
let cursorSelectionLisener: IDisposable | null = null;
const recomputeContext = (element: CellViewModel) => {
switch (element.cursorAtBoundary()) {
case CursorAtBoundary.Both:
notebookEditorCursorAtBoundaryContext.set('both');
break;
case CursorAtBoundary.Top:
notebookEditorCursorAtBoundaryContext.set('top');
break;
case CursorAtBoundary.Bottom:
notebookEditorCursorAtBoundaryContext.set('bottom');
break;
default:
notebookEditorCursorAtBoundaryContext.set('none');
break;
}
return;
};
// Cursor Boundary context
this._localDisposableStore.add(this.onDidChangeFocus((e) => {
cursorSelectionLisener?.dispose();
if (e.elements.length) {
// we only validate the first focused element
const focusedElement = e.elements[0];
cursorSelectionLisener = focusedElement.onDidChangeCursorSelection(() => {
recomputeContext(focusedElement);
});
recomputeContext(focusedElement);
return;
}
// reset context
notebookEditorCursorAtBoundaryContext.set('none');
}));
}
domElementAtIndex(index: number): HTMLElement | null {
return this.view.domElement(index);
}
focusView() {
this.view.domNode.focus();
}
getAbsoluteTop(index: number): number {
if (index < 0 || index >= this.length) {
throw new ListError(this.listUser, `Invalid index ${index}`);
}
return this.view.elementTop(index);
}
triggerScrollFromMouseWheelEvent(browserEvent: IMouseWheelEvent) {
this.view.triggerScrollFromMouseWheelEvent(browserEvent);
}
updateElementHeight(index: number, size: number): void {
const focused = this.getSelection();
this.view.updateElementHeight(index, size, focused.length ? focused[0] : null);
// this.view.updateElementHeight(index, size, null);
}
// override
domFocus() {
if (document.activeElement && this.view.domNode.contains(document.activeElement)) {
// for example, when focus goes into monaco editor, if we refocus the list view, the editor will lose focus.
return;
}
if (!isMacintosh && document.activeElement && isContextMenuFocused()) {
return;
}
super.domFocus();
}
private _revealRange(index: number, range: Range, revealType: CellRevealType, newlyCreated: boolean, alignToBottom: boolean) {
const element = this.view.element(index);
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const startLineNumber = range.startLineNumber;
const lineOffset = element.getLineScrollTopOffset(startLineNumber);
const elementTop = this.view.elementTop(index);
const lineTop = elementTop + lineOffset + EDITOR_TOP_PADDING;
// TODO@rebornix 30 ---> line height * 1.5
if (lineTop < scrollTop) {
this.view.setScrollTop(lineTop - 30);
} else if (lineTop > wrapperBottom) {
this.view.setScrollTop(scrollTop + lineTop - wrapperBottom + 30);
} else if (newlyCreated) {
// newly scrolled into view
if (alignToBottom) {
// align to the bottom
this.view.setScrollTop(scrollTop + lineTop - wrapperBottom + 30);
} else {
// align to to top
this.view.setScrollTop(lineTop - 30);
}
}
if (revealType === CellRevealType.Range) {
element.revealRangeInCenter(range);
}
}
// TODO@rebornix TEST & Fix potential bugs
// List items have real dynamic heights, which means after we set `scrollTop` based on the `elementTop(index)`, the element at `index` might still be removed from the view once all relayouting tasks are done.
// For example, we scroll item 10 into the view upwards, in the first round, items 7, 8, 9, 10 are all in the viewport. Then item 7 and 8 resize themselves to be larger and finally item 10 is removed from the view.
// To ensure that item 10 is always there, we need to scroll item 10 to the top edge of the viewport.
private _revealRangeInternal(index: number, range: Range, revealType: CellRevealType) {
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const elementTop = this.view.elementTop(index);
const element = this.view.element(index);
if (element.editorAttached) {
this._revealRange(index, range, revealType, false, false);
} else {
const elementHeight = this.view.elementHeight(index);
let upwards = false;
if (elementTop + elementHeight < scrollTop) {
// scroll downwards
this.view.setScrollTop(elementTop);
upwards = false;
} else if (elementTop > wrapperBottom) {
// scroll upwards
this.view.setScrollTop(elementTop - this.view.renderHeight / 2);
upwards = true;
}
const editorAttachedPromise = new Promise((resolve, reject) => {
element.onDidChangeEditorAttachState(state => state ? resolve() : reject());
});
editorAttachedPromise.then(() => {
this._revealRange(index, range, revealType, true, upwards);
});
}
}
revealLineInView(index: number, line: number) {
this._revealRangeInternal(index, new Range(line, 1, line, 1), CellRevealType.Line);
}
revealRangeInView(index: number, range: Range): void {
this._revealRangeInternal(index, range, CellRevealType.Range);
}
private _revealRangeInCenterInternal(index: number, range: Range, revealType: CellRevealType) {
const reveal = (index: number, range: Range, revealType: CellRevealType) => {
const element = this.view.element(index);
let lineOffset = element.getLineScrollTopOffset(range.startLineNumber);
let lineOffsetInView = this.view.elementTop(index) + lineOffset;
this.view.setScrollTop(lineOffsetInView - this.view.renderHeight / 2);
if (revealType === CellRevealType.Range) {
element.revealRangeInCenter(range);
}
};
const elementTop = this.view.elementTop(index);
const viewItemOffset = elementTop;
this.view.setScrollTop(viewItemOffset - this.view.renderHeight / 2);
const element = this.view.element(index);
if (!element.editorAttached) {
getEditorAttachedPromise(element).then(() => reveal(index, range, revealType));
} else {
reveal(index, range, revealType);
}
}
revealLineInCenter(index: number, line: number) {
this._revealRangeInCenterInternal(index, new Range(line, 1, line, 1), CellRevealType.Line);
}
revealRangeInCenter(index: number, range: Range): void {
this._revealRangeInCenterInternal(index, range, CellRevealType.Range);
}
private _revealRangeInCenterIfOutsideViewportInternal(index: number, range: Range, revealType: CellRevealType) {
const reveal = (index: number, range: Range, revealType: CellRevealType) => {
const element = this.view.element(index);
let lineOffset = element.getLineScrollTopOffset(range.startLineNumber);
let lineOffsetInView = this.view.elementTop(index) + lineOffset;
this.view.setScrollTop(lineOffsetInView - this.view.renderHeight / 2);
if (revealType === CellRevealType.Range) {
setTimeout(() => {
element.revealRangeInCenter(range);
}, 240);
}
};
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const elementTop = this.view.elementTop(index);
const viewItemOffset = elementTop;
const element = this.view.element(index);
if (viewItemOffset < scrollTop || viewItemOffset > wrapperBottom) {
// let it render
this.view.setScrollTop(viewItemOffset - this.view.renderHeight / 2);
// after rendering, it might be pushed down due to markdown cell dynamic height
const elementTop = this.view.elementTop(index);
this.view.setScrollTop(elementTop - this.view.renderHeight / 2);
// reveal editor
if (!element.editorAttached) {
getEditorAttachedPromise(element).then(() => reveal(index, range, revealType));
} else {
// for example markdown
}
} else {
if (element.editorAttached) {
element.revealRangeInCenter(range);
} else {
// for example, markdown cell in preview mode
getEditorAttachedPromise(element).then(() => reveal(index, range, revealType));
}
}
}
revealLineInCenterIfOutsideViewport(index: number, line: number) {
this._revealRangeInCenterIfOutsideViewportInternal(index, new Range(line, 1, line, 1), CellRevealType.Line);
}
revealRangeInCenterIfOutsideViewport(index: number, range: Range): void {
this._revealRangeInCenterIfOutsideViewportInternal(index, range, CellRevealType.Range);
}
private _revealInternal(index: number, ignoreIfInsideViewport: boolean, revealPosition: CellRevealPosition) {
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const elementTop = this.view.elementTop(index);
if (ignoreIfInsideViewport && elementTop >= scrollTop && elementTop < wrapperBottom) {
// inside the viewport
return;
}
// first render
const viewItemOffset = revealPosition === CellRevealPosition.Top ? elementTop : (elementTop - this.view.renderHeight / 2);
this.view.setScrollTop(viewItemOffset);
// second scroll as markdown cell is dynamic
const newElementTop = this.view.elementTop(index);
const newViewItemOffset = revealPosition === CellRevealPosition.Top ? newElementTop : (newElementTop - this.view.renderHeight / 2);
this.view.setScrollTop(newViewItemOffset);
}
revealInView(index: number) {
this._revealInternal(index, true, CellRevealPosition.Top);
}
revealInCenter(index: number) {
this._revealInternal(index, false, CellRevealPosition.Center);
}
revealInCenterIfOutsideViewport(index: number) {
this._revealInternal(index, true, CellRevealPosition.Center);
}
setCellSelection(index: number, range: Range) {
const element = this.view.element(index);
if (element.editorAttached) {
element.setSelection(range);
} else {
getEditorAttachedPromise(element).then(() => { element.setSelection(range); });
}
}
dispose() {
this._localDisposableStore.dispose();
super.dispose();
}
}
function getEditorAttachedPromise(element: CellViewModel) {
return new Promise((resolve, reject) => {
Event.once(element.onDidChangeEditorAttachState)(state => state ? resolve() : reject());
});
}
function isContextMenuFocused() {
return !!DOM.findParentWithClass(<HTMLElement>document.activeElement, 'context-view');
}
| src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts | 1 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.9285926818847656,
0.03081699274480343,
0.00016432139091193676,
0.00017134594963863492,
0.154020756483078
] |
{
"id": 4,
"code_window": [
"\t\t\t}\n",
"\t\t\treturn;\n",
"\t\t};\n",
"\n",
"\t\t// Cursor Boundary context\n",
"\t\tthis._localDisposableStore.add(this.onDidChangeFocus((e) => {\n",
"\t\t\tcursorSelectionLisener?.dispose();\n",
"\t\t\tif (e.elements.length) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\tthis._localDisposableStore.add(this.onDidChangeSelection((e) => {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "replace",
"edit_start_line_idx": 81
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { VSBuffer } from 'vs/base/common/buffer';
import { sep } from 'vs/base/common/path';
import { URI } from 'vs/base/common/uri';
import { IFileService } from 'vs/platform/files/common/files';
import { REMOTE_HOST_SCHEME } from 'vs/platform/remote/common/remoteHosts';
import { getWebviewContentMimeType } from 'vs/workbench/contrib/webview/common/mimeTypes';
import { isUNC } from 'vs/base/common/extpath';
export const WebviewResourceScheme = 'vscode-resource';
export namespace WebviewResourceResponse {
export enum Type { Success, Failed, AccessDenied }
export class Success {
readonly type = Type.Success;
constructor(
public readonly data: VSBuffer,
public readonly mimeType: string
) { }
}
export const Failed = { type: Type.Failed } as const;
export const AccessDenied = { type: Type.AccessDenied } as const;
export type Response = Success | typeof Failed | typeof AccessDenied;
}
async function resolveContent(
fileService: IFileService,
resource: URI,
mime: string
): Promise<WebviewResourceResponse.Response> {
try {
const contents = await fileService.readFile(resource);
return new WebviewResourceResponse.Success(contents.value, mime);
} catch (err) {
console.log(err);
return WebviewResourceResponse.Failed;
}
}
export async function loadLocalResource(
requestUri: URI,
fileService: IFileService,
extensionLocation: URI | undefined,
getRoots: () => ReadonlyArray<URI>
): Promise<WebviewResourceResponse.Response> {
const normalizedPath = normalizeRequestPath(requestUri);
for (const root of getRoots()) {
if (!containsResource(root, normalizedPath)) {
continue;
}
if (extensionLocation && extensionLocation.scheme === REMOTE_HOST_SCHEME) {
const redirectedUri = URI.from({
scheme: REMOTE_HOST_SCHEME,
authority: extensionLocation.authority,
path: '/vscode-resource',
query: JSON.stringify({
requestResourcePath: normalizedPath.path
})
});
return resolveContent(fileService, redirectedUri, getWebviewContentMimeType(requestUri));
} else {
return resolveContent(fileService, normalizedPath, getWebviewContentMimeType(normalizedPath));
}
}
return WebviewResourceResponse.AccessDenied;
}
function normalizeRequestPath(requestUri: URI) {
if (requestUri.scheme !== WebviewResourceScheme) {
return requestUri;
}
// Modern vscode-resources uris put the scheme of the requested resource as the authority
if (requestUri.authority) {
return URI.parse(`${requestUri.authority}:${encodeURIComponent(requestUri.path).replace(/%2F/g, '/')}`).with({
query: requestUri.query,
fragment: requestUri.fragment
});
}
// Old style vscode-resource uris lose the scheme of the resource which means they are unable to
// load a mix of local and remote content properly.
return requestUri.with({ scheme: 'file' });
}
function containsResource(root: URI, resource: URI): boolean {
let rootPath = root.fsPath + (root.fsPath.endsWith(sep) ? '' : sep);
let resourceFsPath = resource.fsPath;
if (isUNC(root.fsPath) && isUNC(resource.fsPath)) {
rootPath = rootPath.toLowerCase();
resourceFsPath = resourceFsPath.toLowerCase();
}
return resourceFsPath.startsWith(rootPath);
}
| src/vs/workbench/contrib/webview/common/resourceLoader.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.00017374612798448652,
0.00017050912720151246,
0.00016551824228372425,
0.00017116563685704023,
0.000002042800588242244
] |
{
"id": 4,
"code_window": [
"\t\t\t}\n",
"\t\t\treturn;\n",
"\t\t};\n",
"\n",
"\t\t// Cursor Boundary context\n",
"\t\tthis._localDisposableStore.add(this.onDidChangeFocus((e) => {\n",
"\t\t\tcursorSelectionLisener?.dispose();\n",
"\t\t\tif (e.elements.length) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\tthis._localDisposableStore.add(this.onDidChangeSelection((e) => {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "replace",
"edit_start_line_idx": 81
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { IWorkspacesService, IWorkspaceFolderCreationData, IWorkspaceIdentifier, IEnterWorkspaceResult, IRecentlyOpened, restoreRecentlyOpened, IRecent, isRecentFile, isRecentFolder, toStoreData, IStoredWorkspaceFolder, getStoredWorkspaceFolder, WORKSPACE_EXTENSION, IStoredWorkspace } from 'vs/platform/workspaces/common/workspaces';
import { URI } from 'vs/base/common/uri';
import { Event, Emitter } from 'vs/base/common/event';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { ILogService } from 'vs/platform/log/common/log';
import { Disposable } from 'vs/base/common/lifecycle';
import { getWorkspaceIdentifier } from 'vs/workbench/services/workspaces/browser/workspaces';
import { IFileService, FileOperationError, FileOperationResult } from 'vs/platform/files/common/files';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { joinPath } from 'vs/base/common/resources';
import { VSBuffer } from 'vs/base/common/buffer';
export class BrowserWorkspacesService extends Disposable implements IWorkspacesService {
static readonly RECENTLY_OPENED_KEY = 'recently.opened';
_serviceBrand: undefined;
private readonly _onRecentlyOpenedChange: Emitter<void> = this._register(new Emitter<void>());
readonly onRecentlyOpenedChange: Event<void> = this._onRecentlyOpenedChange.event;
constructor(
@IStorageService private readonly storageService: IStorageService,
@IWorkspaceContextService private readonly workspaceService: IWorkspaceContextService,
@ILogService private readonly logService: ILogService,
@IFileService private readonly fileService: IFileService,
@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService
) {
super();
// Opening a workspace should push it as most
// recently used to the workspaces history
this.addWorkspaceToRecentlyOpened();
this.registerListeners();
}
private registerListeners(): void {
this._register(this.storageService.onDidChangeStorage(event => {
if (event.key === BrowserWorkspacesService.RECENTLY_OPENED_KEY && event.scope === StorageScope.GLOBAL) {
this._onRecentlyOpenedChange.fire();
}
}));
}
private addWorkspaceToRecentlyOpened(): void {
const workspace = this.workspaceService.getWorkspace();
switch (this.workspaceService.getWorkbenchState()) {
case WorkbenchState.FOLDER:
this.addRecentlyOpened([{ folderUri: workspace.folders[0].uri }]);
break;
case WorkbenchState.WORKSPACE:
this.addRecentlyOpened([{ workspace: { id: workspace.id, configPath: workspace.configuration! } }]);
break;
}
}
//#region Workspaces History
async getRecentlyOpened(): Promise<IRecentlyOpened> {
const recentlyOpenedRaw = this.storageService.get(BrowserWorkspacesService.RECENTLY_OPENED_KEY, StorageScope.GLOBAL);
if (recentlyOpenedRaw) {
return restoreRecentlyOpened(JSON.parse(recentlyOpenedRaw), this.logService);
}
return { workspaces: [], files: [] };
}
async addRecentlyOpened(recents: IRecent[]): Promise<void> {
const recentlyOpened = await this.getRecentlyOpened();
recents.forEach(recent => {
if (isRecentFile(recent)) {
this.doRemoveRecentlyOpened(recentlyOpened, [recent.fileUri]);
recentlyOpened.files.unshift(recent);
} else if (isRecentFolder(recent)) {
this.doRemoveRecentlyOpened(recentlyOpened, [recent.folderUri]);
recentlyOpened.workspaces.unshift(recent);
} else {
this.doRemoveRecentlyOpened(recentlyOpened, [recent.workspace.configPath]);
recentlyOpened.workspaces.unshift(recent);
}
});
return this.saveRecentlyOpened(recentlyOpened);
}
async removeRecentlyOpened(paths: URI[]): Promise<void> {
const recentlyOpened = await this.getRecentlyOpened();
this.doRemoveRecentlyOpened(recentlyOpened, paths);
return this.saveRecentlyOpened(recentlyOpened);
}
private doRemoveRecentlyOpened(recentlyOpened: IRecentlyOpened, paths: URI[]): void {
recentlyOpened.files = recentlyOpened.files.filter(file => {
return !paths.some(path => path.toString() === file.fileUri.toString());
});
recentlyOpened.workspaces = recentlyOpened.workspaces.filter(workspace => {
return !paths.some(path => path.toString() === (isRecentFolder(workspace) ? workspace.folderUri.toString() : workspace.workspace.configPath.toString()));
});
}
private async saveRecentlyOpened(data: IRecentlyOpened): Promise<void> {
return this.storageService.store(BrowserWorkspacesService.RECENTLY_OPENED_KEY, JSON.stringify(toStoreData(data)), StorageScope.GLOBAL);
}
async clearRecentlyOpened(): Promise<void> {
this.storageService.remove(BrowserWorkspacesService.RECENTLY_OPENED_KEY, StorageScope.GLOBAL);
}
//#endregion
//#region Workspace Management
async enterWorkspace(path: URI): Promise<IEnterWorkspaceResult | null> {
return { workspace: await this.getWorkspaceIdentifier(path) };
}
async createUntitledWorkspace(folders?: IWorkspaceFolderCreationData[], remoteAuthority?: string): Promise<IWorkspaceIdentifier> {
const randomId = (Date.now() + Math.round(Math.random() * 1000)).toString();
const newUntitledWorkspacePath = joinPath(this.environmentService.untitledWorkspacesHome, `Untitled-${randomId}.${WORKSPACE_EXTENSION}`);
// Build array of workspace folders to store
const storedWorkspaceFolder: IStoredWorkspaceFolder[] = [];
if (folders) {
for (const folder of folders) {
storedWorkspaceFolder.push(getStoredWorkspaceFolder(folder.uri, folder.name, this.environmentService.untitledWorkspacesHome));
}
}
// Store at untitled workspaces location
const storedWorkspace: IStoredWorkspace = { folders: storedWorkspaceFolder, remoteAuthority };
await this.fileService.writeFile(newUntitledWorkspacePath, VSBuffer.fromString(JSON.stringify(storedWorkspace, null, '\t')));
return this.getWorkspaceIdentifier(newUntitledWorkspacePath);
}
async deleteUntitledWorkspace(workspace: IWorkspaceIdentifier): Promise<void> {
try {
await this.fileService.del(workspace.configPath);
} catch (error) {
if ((<FileOperationError>error).fileOperationResult !== FileOperationResult.FILE_NOT_FOUND) {
throw error; // re-throw any other error than file not found which is OK
}
}
}
async getWorkspaceIdentifier(workspacePath: URI): Promise<IWorkspaceIdentifier> {
return getWorkspaceIdentifier(workspacePath);
}
//#endregion
}
registerSingleton(IWorkspacesService, BrowserWorkspacesService, true);
| src/vs/workbench/services/workspaces/browser/workspacesService.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.00046945575741119683,
0.00018954476399812847,
0.0001642201968934387,
0.0001696766703389585,
0.00007078500493662432
] |
{
"id": 4,
"code_window": [
"\t\t\t}\n",
"\t\t\treturn;\n",
"\t\t};\n",
"\n",
"\t\t// Cursor Boundary context\n",
"\t\tthis._localDisposableStore.add(this.onDidChangeFocus((e) => {\n",
"\t\t\tcursorSelectionLisener?.dispose();\n",
"\t\t\tif (e.elements.length) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\t\tthis._localDisposableStore.add(this.onDidChangeSelection((e) => {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "replace",
"edit_start_line_idx": 81
} | <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M13 3.5V6H15.151L15.634 6.629L13 13.629L12.516 14L8.74284 14C8.99647 13.6929 9.2174 13.3578 9.4003 13L12.133 13L14.5 7H8.74284C8.52467 6.73583 8.2823 6.49238 8.01914 6.27304L8.14602 6.146L8.50002 6H12V4H6.5L6.146 3.854L5.293 3H1V6.25716C0.62057 6.57052 0.283885 6.93379 0 7.33692V2.5L0.5 2H5.5L5.854 2.146L6.707 3H12.5L13 3.5Z" fill="#C5C5C5"/>
<path d="M6 10.5C6 11.3284 5.32843 12 4.5 12C3.67157 12 3 11.3284 3 10.5C3 9.67157 3.67157 9 4.5 9C5.32843 9 6 9.67157 6 10.5Z" fill="#C4C4C4"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M8 10.5C8 12.433 6.433 14 4.5 14C2.567 14 1 12.433 1 10.5C1 8.567 2.567 7 4.5 7C6.433 7 8 8.567 8 10.5ZM4.5 13C5.88071 13 7 11.8807 7 10.5C7 9.11929 5.88071 8 4.5 8C3.11929 8 2 9.11929 2 10.5C2 11.8807 3.11929 13 4.5 13Z" fill="#C4C4C4"/>
</svg>
| extensions/theme-defaults/fileicons/images/root-folder-open-dark.svg | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.000545498332940042,
0.000545498332940042,
0.000545498332940042,
0.000545498332940042,
0
] |
{
"id": 5,
"code_window": [
"\t\t\tif (e.elements.length) {\n",
"\t\t\t\t// we only validate the first focused element\n",
"\t\t\t\tconst focusedElement = e.elements[0];\n",
"\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tcursorSelectionListener?.dispose();\n",
"\t\t\t\ttextEditorAttachListener?.dispose();\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "add",
"edit_start_line_idx": 84
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as DOM from 'vs/base/browser/dom';
import { IListRenderer, IListVirtualDelegate, ListError } from 'vs/base/browser/ui/list/list';
import { Event } from 'vs/base/common/event';
import { ScrollEvent } from 'vs/base/common/scrollable';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IListService, IWorkbenchListOptions, WorkbenchList } from 'vs/platform/list/browser/listService';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { IMouseWheelEvent } from 'vs/base/browser/mouseEvent';
import { isMacintosh } from 'vs/base/common/platform';
import { NOTEBOOK_EDITOR_CURSOR_BOUNDARY } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { Range } from 'vs/editor/common/core/range';
import { CellRevealType, CellRevealPosition, CursorAtBoundary } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { IDisposable, DisposableStore } from 'vs/base/common/lifecycle';
import { CellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel';
import { EDITOR_TOP_PADDING } from 'vs/workbench/contrib/notebook/browser/constants';
export class NotebookCellList extends WorkbenchList<CellViewModel> implements IDisposable {
get onWillScroll(): Event<ScrollEvent> { return this.view.onWillScroll; }
get rowsContainer(): HTMLElement {
return this.view.containerDomNode;
}
private _previousSelectedElements: CellViewModel[] = [];
private _localDisposableStore = new DisposableStore();
constructor(
private listUser: string,
container: HTMLElement,
delegate: IListVirtualDelegate<CellViewModel>,
renderers: IListRenderer<CellViewModel, any>[],
contextKeyService: IContextKeyService,
options: IWorkbenchListOptions<CellViewModel>,
@IListService listService: IListService,
@IThemeService themeService: IThemeService,
@IConfigurationService configurationService: IConfigurationService,
@IKeybindingService keybindingService: IKeybindingService
) {
super(listUser, container, delegate, renderers, options, contextKeyService, listService, themeService, configurationService, keybindingService);
this._previousSelectedElements = this.getSelectedElements();
this._localDisposableStore.add(this.onDidChangeSelection((e) => {
this._previousSelectedElements.forEach(element => {
if (e.elements.indexOf(element) < 0) {
element.onDeselect();
}
});
this._previousSelectedElements = e.elements;
}));
const notebookEditorCursorAtBoundaryContext = NOTEBOOK_EDITOR_CURSOR_BOUNDARY.bindTo(contextKeyService);
notebookEditorCursorAtBoundaryContext.set('none');
let cursorSelectionLisener: IDisposable | null = null;
const recomputeContext = (element: CellViewModel) => {
switch (element.cursorAtBoundary()) {
case CursorAtBoundary.Both:
notebookEditorCursorAtBoundaryContext.set('both');
break;
case CursorAtBoundary.Top:
notebookEditorCursorAtBoundaryContext.set('top');
break;
case CursorAtBoundary.Bottom:
notebookEditorCursorAtBoundaryContext.set('bottom');
break;
default:
notebookEditorCursorAtBoundaryContext.set('none');
break;
}
return;
};
// Cursor Boundary context
this._localDisposableStore.add(this.onDidChangeFocus((e) => {
cursorSelectionLisener?.dispose();
if (e.elements.length) {
// we only validate the first focused element
const focusedElement = e.elements[0];
cursorSelectionLisener = focusedElement.onDidChangeCursorSelection(() => {
recomputeContext(focusedElement);
});
recomputeContext(focusedElement);
return;
}
// reset context
notebookEditorCursorAtBoundaryContext.set('none');
}));
}
domElementAtIndex(index: number): HTMLElement | null {
return this.view.domElement(index);
}
focusView() {
this.view.domNode.focus();
}
getAbsoluteTop(index: number): number {
if (index < 0 || index >= this.length) {
throw new ListError(this.listUser, `Invalid index ${index}`);
}
return this.view.elementTop(index);
}
triggerScrollFromMouseWheelEvent(browserEvent: IMouseWheelEvent) {
this.view.triggerScrollFromMouseWheelEvent(browserEvent);
}
updateElementHeight(index: number, size: number): void {
const focused = this.getSelection();
this.view.updateElementHeight(index, size, focused.length ? focused[0] : null);
// this.view.updateElementHeight(index, size, null);
}
// override
domFocus() {
if (document.activeElement && this.view.domNode.contains(document.activeElement)) {
// for example, when focus goes into monaco editor, if we refocus the list view, the editor will lose focus.
return;
}
if (!isMacintosh && document.activeElement && isContextMenuFocused()) {
return;
}
super.domFocus();
}
private _revealRange(index: number, range: Range, revealType: CellRevealType, newlyCreated: boolean, alignToBottom: boolean) {
const element = this.view.element(index);
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const startLineNumber = range.startLineNumber;
const lineOffset = element.getLineScrollTopOffset(startLineNumber);
const elementTop = this.view.elementTop(index);
const lineTop = elementTop + lineOffset + EDITOR_TOP_PADDING;
// TODO@rebornix 30 ---> line height * 1.5
if (lineTop < scrollTop) {
this.view.setScrollTop(lineTop - 30);
} else if (lineTop > wrapperBottom) {
this.view.setScrollTop(scrollTop + lineTop - wrapperBottom + 30);
} else if (newlyCreated) {
// newly scrolled into view
if (alignToBottom) {
// align to the bottom
this.view.setScrollTop(scrollTop + lineTop - wrapperBottom + 30);
} else {
// align to to top
this.view.setScrollTop(lineTop - 30);
}
}
if (revealType === CellRevealType.Range) {
element.revealRangeInCenter(range);
}
}
// TODO@rebornix TEST & Fix potential bugs
// List items have real dynamic heights, which means after we set `scrollTop` based on the `elementTop(index)`, the element at `index` might still be removed from the view once all relayouting tasks are done.
// For example, we scroll item 10 into the view upwards, in the first round, items 7, 8, 9, 10 are all in the viewport. Then item 7 and 8 resize themselves to be larger and finally item 10 is removed from the view.
// To ensure that item 10 is always there, we need to scroll item 10 to the top edge of the viewport.
private _revealRangeInternal(index: number, range: Range, revealType: CellRevealType) {
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const elementTop = this.view.elementTop(index);
const element = this.view.element(index);
if (element.editorAttached) {
this._revealRange(index, range, revealType, false, false);
} else {
const elementHeight = this.view.elementHeight(index);
let upwards = false;
if (elementTop + elementHeight < scrollTop) {
// scroll downwards
this.view.setScrollTop(elementTop);
upwards = false;
} else if (elementTop > wrapperBottom) {
// scroll upwards
this.view.setScrollTop(elementTop - this.view.renderHeight / 2);
upwards = true;
}
const editorAttachedPromise = new Promise((resolve, reject) => {
element.onDidChangeEditorAttachState(state => state ? resolve() : reject());
});
editorAttachedPromise.then(() => {
this._revealRange(index, range, revealType, true, upwards);
});
}
}
revealLineInView(index: number, line: number) {
this._revealRangeInternal(index, new Range(line, 1, line, 1), CellRevealType.Line);
}
revealRangeInView(index: number, range: Range): void {
this._revealRangeInternal(index, range, CellRevealType.Range);
}
private _revealRangeInCenterInternal(index: number, range: Range, revealType: CellRevealType) {
const reveal = (index: number, range: Range, revealType: CellRevealType) => {
const element = this.view.element(index);
let lineOffset = element.getLineScrollTopOffset(range.startLineNumber);
let lineOffsetInView = this.view.elementTop(index) + lineOffset;
this.view.setScrollTop(lineOffsetInView - this.view.renderHeight / 2);
if (revealType === CellRevealType.Range) {
element.revealRangeInCenter(range);
}
};
const elementTop = this.view.elementTop(index);
const viewItemOffset = elementTop;
this.view.setScrollTop(viewItemOffset - this.view.renderHeight / 2);
const element = this.view.element(index);
if (!element.editorAttached) {
getEditorAttachedPromise(element).then(() => reveal(index, range, revealType));
} else {
reveal(index, range, revealType);
}
}
revealLineInCenter(index: number, line: number) {
this._revealRangeInCenterInternal(index, new Range(line, 1, line, 1), CellRevealType.Line);
}
revealRangeInCenter(index: number, range: Range): void {
this._revealRangeInCenterInternal(index, range, CellRevealType.Range);
}
private _revealRangeInCenterIfOutsideViewportInternal(index: number, range: Range, revealType: CellRevealType) {
const reveal = (index: number, range: Range, revealType: CellRevealType) => {
const element = this.view.element(index);
let lineOffset = element.getLineScrollTopOffset(range.startLineNumber);
let lineOffsetInView = this.view.elementTop(index) + lineOffset;
this.view.setScrollTop(lineOffsetInView - this.view.renderHeight / 2);
if (revealType === CellRevealType.Range) {
setTimeout(() => {
element.revealRangeInCenter(range);
}, 240);
}
};
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const elementTop = this.view.elementTop(index);
const viewItemOffset = elementTop;
const element = this.view.element(index);
if (viewItemOffset < scrollTop || viewItemOffset > wrapperBottom) {
// let it render
this.view.setScrollTop(viewItemOffset - this.view.renderHeight / 2);
// after rendering, it might be pushed down due to markdown cell dynamic height
const elementTop = this.view.elementTop(index);
this.view.setScrollTop(elementTop - this.view.renderHeight / 2);
// reveal editor
if (!element.editorAttached) {
getEditorAttachedPromise(element).then(() => reveal(index, range, revealType));
} else {
// for example markdown
}
} else {
if (element.editorAttached) {
element.revealRangeInCenter(range);
} else {
// for example, markdown cell in preview mode
getEditorAttachedPromise(element).then(() => reveal(index, range, revealType));
}
}
}
revealLineInCenterIfOutsideViewport(index: number, line: number) {
this._revealRangeInCenterIfOutsideViewportInternal(index, new Range(line, 1, line, 1), CellRevealType.Line);
}
revealRangeInCenterIfOutsideViewport(index: number, range: Range): void {
this._revealRangeInCenterIfOutsideViewportInternal(index, range, CellRevealType.Range);
}
private _revealInternal(index: number, ignoreIfInsideViewport: boolean, revealPosition: CellRevealPosition) {
const scrollTop = this.view.getScrollTop();
const wrapperBottom = scrollTop + this.view.renderHeight;
const elementTop = this.view.elementTop(index);
if (ignoreIfInsideViewport && elementTop >= scrollTop && elementTop < wrapperBottom) {
// inside the viewport
return;
}
// first render
const viewItemOffset = revealPosition === CellRevealPosition.Top ? elementTop : (elementTop - this.view.renderHeight / 2);
this.view.setScrollTop(viewItemOffset);
// second scroll as markdown cell is dynamic
const newElementTop = this.view.elementTop(index);
const newViewItemOffset = revealPosition === CellRevealPosition.Top ? newElementTop : (newElementTop - this.view.renderHeight / 2);
this.view.setScrollTop(newViewItemOffset);
}
revealInView(index: number) {
this._revealInternal(index, true, CellRevealPosition.Top);
}
revealInCenter(index: number) {
this._revealInternal(index, false, CellRevealPosition.Center);
}
revealInCenterIfOutsideViewport(index: number) {
this._revealInternal(index, true, CellRevealPosition.Center);
}
setCellSelection(index: number, range: Range) {
const element = this.view.element(index);
if (element.editorAttached) {
element.setSelection(range);
} else {
getEditorAttachedPromise(element).then(() => { element.setSelection(range); });
}
}
dispose() {
this._localDisposableStore.dispose();
super.dispose();
}
}
function getEditorAttachedPromise(element: CellViewModel) {
return new Promise((resolve, reject) => {
Event.once(element.onDidChangeEditorAttachState)(state => state ? resolve() : reject());
});
}
function isContextMenuFocused() {
return !!DOM.findParentWithClass(<HTMLElement>document.activeElement, 'context-view');
}
| src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts | 1 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.9988222718238831,
0.05790714919567108,
0.00016472172865178436,
0.00016906726523302495,
0.22842244803905487
] |
{
"id": 5,
"code_window": [
"\t\t\tif (e.elements.length) {\n",
"\t\t\t\t// we only validate the first focused element\n",
"\t\t\t\tconst focusedElement = e.elements[0];\n",
"\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tcursorSelectionListener?.dispose();\n",
"\t\t\t\ttextEditorAttachListener?.dispose();\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "add",
"edit_start_line_idx": 84
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as dom from 'vs/base/browser/dom';
import { GlobalMouseMoveMonitor, IStandardMouseMoveEventData, standardMouseMoveMerger } from 'vs/base/browser/globalMouseMoveMonitor';
import { Emitter } from 'vs/base/common/event';
import { Disposable } from 'vs/base/common/lifecycle';
import 'vs/css!./lightBulbWidget';
import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition } from 'vs/editor/browser/editorBrowser';
import { IPosition } from 'vs/editor/common/core/position';
import { TextModel } from 'vs/editor/common/model/textModel';
import { CodeActionSet } from 'vs/editor/contrib/codeAction/codeAction';
import * as nls from 'vs/nls';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { EditorOption } from 'vs/editor/common/config/editorOptions';
import { registerThemingParticipant, IColorTheme, ICssStyleCollector } from 'vs/platform/theme/common/themeService';
import { editorLightBulbForeground, editorLightBulbAutoFixForeground } from 'vs/platform/theme/common/colorRegistry';
import { Gesture } from 'vs/base/browser/touch';
import type { CodeActionTrigger } from 'vs/editor/contrib/codeAction/types';
namespace LightBulbState {
export const enum Type {
Hidden,
Showing,
}
export const Hidden = { type: Type.Hidden } as const;
export class Showing {
readonly type = Type.Showing;
constructor(
public readonly actions: CodeActionSet,
public readonly trigger: CodeActionTrigger,
public readonly editorPosition: IPosition,
public readonly widgetPosition: IContentWidgetPosition,
) { }
}
export type State = typeof Hidden | Showing;
}
export class LightBulbWidget extends Disposable implements IContentWidget {
private static readonly _posPref = [ContentWidgetPositionPreference.EXACT];
private readonly _domNode: HTMLDivElement;
private readonly _onClick = this._register(new Emitter<{ x: number; y: number; actions: CodeActionSet; trigger: CodeActionTrigger }>());
public readonly onClick = this._onClick.event;
private _state: LightBulbState.State = LightBulbState.Hidden;
constructor(
private readonly _editor: ICodeEditor,
private readonly _quickFixActionId: string,
private readonly _preferredFixActionId: string,
@IKeybindingService private readonly _keybindingService: IKeybindingService
) {
super();
this._domNode = document.createElement('div');
this._domNode.className = 'codicon codicon-lightbulb';
this._editor.addContentWidget(this);
this._register(this._editor.onDidChangeModelContent(_ => {
// cancel when the line in question has been removed
const editorModel = this._editor.getModel();
if (this.state.type !== LightBulbState.Type.Showing || !editorModel || this.state.editorPosition.lineNumber >= editorModel.getLineCount()) {
this.hide();
}
}));
Gesture.ignoreTarget(this._domNode);
this._register(dom.addStandardDisposableGenericMouseDownListner(this._domNode, e => {
if (this.state.type !== LightBulbState.Type.Showing) {
return;
}
// Make sure that focus / cursor location is not lost when clicking widget icon
this._editor.focus();
e.preventDefault();
// a bit of extra work to make sure the menu
// doesn't cover the line-text
const { top, height } = dom.getDomNodePagePosition(this._domNode);
const lineHeight = this._editor.getOption(EditorOption.lineHeight);
let pad = Math.floor(lineHeight / 3);
if (this.state.widgetPosition.position !== null && this.state.widgetPosition.position.lineNumber < this.state.editorPosition.lineNumber) {
pad += lineHeight;
}
this._onClick.fire({
x: e.posx,
y: top + height + pad,
actions: this.state.actions,
trigger: this.state.trigger,
});
}));
this._register(dom.addDisposableListener(this._domNode, 'mouseenter', (e: MouseEvent) => {
if ((e.buttons & 1) !== 1) {
return;
}
// mouse enters lightbulb while the primary/left button
// is being pressed -> hide the lightbulb and block future
// showings until mouse is released
this.hide();
const monitor = new GlobalMouseMoveMonitor<IStandardMouseMoveEventData>();
monitor.startMonitoring(<HTMLElement>e.target, e.buttons, standardMouseMoveMerger, () => { }, () => {
monitor.dispose();
});
}));
this._register(this._editor.onDidChangeConfiguration(e => {
// hide when told to do so
if (e.hasChanged(EditorOption.lightbulb) && !this._editor.getOption(EditorOption.lightbulb).enabled) {
this.hide();
}
}));
this._updateLightBulbTitle();
this._register(this._keybindingService.onDidUpdateKeybindings(this._updateLightBulbTitle, this));
}
dispose(): void {
super.dispose();
this._editor.removeContentWidget(this);
}
getId(): string {
return 'LightBulbWidget';
}
getDomNode(): HTMLElement {
return this._domNode;
}
getPosition(): IContentWidgetPosition | null {
return this._state.type === LightBulbState.Type.Showing ? this._state.widgetPosition : null;
}
public update(actions: CodeActionSet, trigger: CodeActionTrigger, atPosition: IPosition) {
if (actions.validActions.length <= 0) {
return this.hide();
}
const options = this._editor.getOptions();
if (!options.get(EditorOption.lightbulb).enabled) {
return this.hide();
}
const { lineNumber, column } = atPosition;
const model = this._editor.getModel();
if (!model) {
return this.hide();
}
const tabSize = model.getOptions().tabSize;
const fontInfo = options.get(EditorOption.fontInfo);
const lineContent = model.getLineContent(lineNumber);
const indent = TextModel.computeIndentLevel(lineContent, tabSize);
const lineHasSpace = fontInfo.spaceWidth * indent > 22;
const isFolded = (lineNumber: number) => {
return lineNumber > 2 && this._editor.getTopForLineNumber(lineNumber) === this._editor.getTopForLineNumber(lineNumber - 1);
};
let effectiveLineNumber = lineNumber;
if (!lineHasSpace) {
if (lineNumber > 1 && !isFolded(lineNumber - 1)) {
effectiveLineNumber -= 1;
} else if (!isFolded(lineNumber + 1)) {
effectiveLineNumber += 1;
} else if (column * fontInfo.spaceWidth < 22) {
// cannot show lightbulb above/below and showing
// it inline would overlay the cursor...
return this.hide();
}
}
this.state = new LightBulbState.Showing(actions, trigger, atPosition, {
position: { lineNumber: effectiveLineNumber, column: 1 },
preference: LightBulbWidget._posPref
});
dom.toggleClass(this._domNode, 'codicon-lightbulb-autofix', actions.hasAutoFix);
this._editor.layoutContentWidget(this);
}
public hide(): void {
this.state = LightBulbState.Hidden;
this._editor.layoutContentWidget(this);
}
private get state(): LightBulbState.State { return this._state; }
private set state(value) {
this._state = value;
this._updateLightBulbTitle();
}
private _updateLightBulbTitle(): void {
if (this.state.type === LightBulbState.Type.Showing && this.state.actions.hasAutoFix) {
const preferredKb = this._keybindingService.lookupKeybinding(this._preferredFixActionId);
if (preferredKb) {
this.title = nls.localize('prefferedQuickFixWithKb', "Show Fixes. Preferred Fix Available ({0})", preferredKb.getLabel());
return;
}
}
const kb = this._keybindingService.lookupKeybinding(this._quickFixActionId);
if (kb) {
this.title = nls.localize('quickFixWithKb', "Show Fixes ({0})", kb.getLabel());
} else {
this.title = nls.localize('quickFix', "Show Fixes");
}
}
private set title(value: string) {
this._domNode.title = value;
}
}
registerThemingParticipant((theme: IColorTheme, collector: ICssStyleCollector) => {
// Lightbulb Icon
const editorLightBulbForegroundColor = theme.getColor(editorLightBulbForeground);
if (editorLightBulbForegroundColor) {
collector.addRule(`
.monaco-editor .contentWidgets .codicon-lightbulb {
color: ${editorLightBulbForegroundColor};
}`);
}
// Lightbulb Auto Fix Icon
const editorLightBulbAutoFixForegroundColor = theme.getColor(editorLightBulbAutoFixForeground);
if (editorLightBulbAutoFixForegroundColor) {
collector.addRule(`
.monaco-editor .contentWidgets .codicon-lightbulb-autofix {
color: ${editorLightBulbAutoFixForegroundColor};
}`);
}
});
| src/vs/editor/contrib/codeAction/lightBulbWidget.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.002113883849233389,
0.0003435438557062298,
0.0001646212476771325,
0.0001724889880279079,
0.00048779146163724363
] |
{
"id": 5,
"code_window": [
"\t\t\tif (e.elements.length) {\n",
"\t\t\t\t// we only validate the first focused element\n",
"\t\t\t\tconst focusedElement = e.elements[0];\n",
"\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tcursorSelectionListener?.dispose();\n",
"\t\t\t\ttextEditorAttachListener?.dispose();\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "add",
"edit_start_line_idx": 84
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
//@ts-check
'use strict';
const withDefaults = require('../shared.webpack.config');
const path = require('path');
const webpack = require('webpack');
const config = withDefaults({
context: path.join(__dirname, 'client'),
entry: {
extension: './src/jsonMain.ts',
},
output: {
filename: 'jsonMain.js',
path: path.join(__dirname, 'client', 'dist')
}
});
// add plugin, don't replace inherited
config.plugins.push(new webpack.IgnorePlugin(/vertx/)); // request-light dependency
module.exports = config;
| extensions/json-language-features/extension.webpack.config.js | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.0001764358312357217,
0.00017470061720814556,
0.00017297631711699069,
0.00017468968871980906,
0.0000014123619394013076
] |
{
"id": 5,
"code_window": [
"\t\t\tif (e.elements.length) {\n",
"\t\t\t\t// we only validate the first focused element\n",
"\t\t\t\tconst focusedElement = e.elements[0];\n",
"\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tcursorSelectionListener?.dispose();\n",
"\t\t\t\ttextEditorAttachListener?.dispose();\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "add",
"edit_start_line_idx": 84
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-tree {
height: 100%;
width: 100%;
white-space: nowrap;
user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
position: relative;
}
.monaco-tree > .monaco-scrollable-element {
height: 100%;
}
.monaco-tree > .monaco-scrollable-element > .monaco-tree-wrapper {
height: 100%;
width: 100%;
position: relative;
}
.monaco-tree .monaco-tree-rows {
position: absolute;
width: 100%;
height: 100%;
}
.monaco-tree .monaco-tree-rows > .monaco-tree-row {
box-sizing: border-box;
cursor: pointer;
overflow: hidden;
width: 100%;
touch-action: none;
}
.monaco-tree .monaco-tree-rows > .monaco-tree-row > .content {
position: relative;
height: 100%;
}
.monaco-tree-drag-image {
display: inline-block;
padding: 1px 7px;
border-radius: 10px;
font-size: 12px;
position: absolute;
}
/* for OS X ballistic scrolling */
.monaco-tree .monaco-tree-rows > .monaco-tree-row.scrolling {
display: none;
}
/* Highlighted */
.monaco-tree.highlighted .monaco-tree-rows > .monaco-tree-row:not(.highlighted) {
opacity: 0.3;
}
| src/vs/base/parts/tree/browser/tree.css | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.0001833403657656163,
0.0001722784509183839,
0.00016601913375779986,
0.0001720651489449665,
0.000005710532150260406
] |
{
"id": 6,
"code_window": [
"\t\t\t\t// we only validate the first focused element\n",
"\t\t\t\tconst focusedElement = e.elements[0];\n",
"\n",
"\t\t\t\tcursorSelectionLisener = focusedElement.onDidChangeCursorSelection(() => {\n",
"\t\t\t\t\trecomputeContext(focusedElement);\n",
"\t\t\t\t});\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tcursorSelectionListener = focusedElement.onDidChangeCursorSelection(() => {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "replace",
"edit_start_line_idx": 87
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { getZoomLevel } from 'vs/base/browser/browser';
import * as DOM from 'vs/base/browser/dom';
import { IMouseWheelEvent } from 'vs/base/browser/mouseEvent';
import { CancellationToken } from 'vs/base/common/cancellation';
import { DisposableStore, MutableDisposable } from 'vs/base/common/lifecycle';
import 'vs/css!./notebook';
import { IEditorOptions } from 'vs/editor/common/config/editorOptions';
import { BareFontInfo } from 'vs/editor/common/config/fontInfo';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { contrastBorder, editorBackground, focusBorder, foreground, textBlockQuoteBackground, textBlockQuoteBorder, textLinkActiveForeground, textLinkForeground, textPreformatForeground } from 'vs/platform/theme/common/colorRegistry';
import { IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { BaseEditor } from 'vs/workbench/browser/parts/editor/baseEditor';
import { EditorOptions, IEditorMemento, IEditorCloseEvent } from 'vs/workbench/common/editor';
import { INotebookEditor, NotebookLayoutInfo, CellState, NOTEBOOK_EDITOR_FOCUSED, CellFocusMode, ICellViewModel } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { NotebookEditorInput, NotebookEditorModel } from 'vs/workbench/contrib/notebook/browser/notebookEditorInput';
import { INotebookService } from 'vs/workbench/contrib/notebook/browser/notebookService';
import { OutputRenderer } from 'vs/workbench/contrib/notebook/browser/view/output/outputRenderer';
import { BackLayerWebView } from 'vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView';
import { CodeCellRenderer, MarkdownCellRenderer, NotebookCellListDelegate } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellRenderer';
import { IOutput, CellKind } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { IWebviewService } from 'vs/workbench/contrib/webview/browser/webview';
import { getExtraColor } from 'vs/workbench/contrib/welcome/walkThrough/common/walkThroughUtils';
import { IEditorGroup, IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { IEditor, ICompositeCodeEditor } from 'vs/editor/common/editorCommon';
import { IResourceEditorInput } from 'vs/platform/editor/common/editor';
import { Emitter, Event } from 'vs/base/common/event';
import { NotebookCellList } from 'vs/workbench/contrib/notebook/browser/view/notebookCellList';
import { NotebookFindWidget } from 'vs/workbench/contrib/notebook/browser/contrib/notebookFindWidget';
import { NotebookViewModel, INotebookEditorViewState, IModelDecorationsChangeAccessor } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookViewModel';
import { IEditorGroupView } from 'vs/workbench/browser/parts/editor/editor';
import { CellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookCellViewModel';
import { Range } from 'vs/editor/common/core/range';
import { CELL_MARGIN } from 'vs/workbench/contrib/notebook/browser/constants';
const $ = DOM.$;
const NOTEBOOK_EDITOR_VIEW_STATE_PREFERENCE_KEY = 'NotebookEditorViewState';
export class NotebookEditorOptions extends EditorOptions {
readonly cellOptions?: IResourceEditorInput;
constructor(options: Partial<NotebookEditorOptions>) {
super();
this.overwrite(options);
this.cellOptions = options.cellOptions;
}
with(options: Partial<NotebookEditorOptions>): NotebookEditorOptions {
return new NotebookEditorOptions({ ...this, ...options });
}
}
export class NotebookCodeEditors implements ICompositeCodeEditor {
private readonly _disposables = new DisposableStore();
private readonly _onDidChangeActiveEditor = new Emitter<this>();
readonly onDidChangeActiveEditor: Event<this> = this._onDidChangeActiveEditor.event;
constructor(
private _list: NotebookCellList,
private _renderedEditors: Map<ICellViewModel, ICodeEditor | undefined>
) {
_list.onDidChangeFocus(_e => this._onDidChangeActiveEditor.fire(this), undefined, this._disposables);
}
dispose(): void {
this._onDidChangeActiveEditor.dispose();
this._disposables.dispose();
}
get activeCodeEditor(): IEditor | undefined {
const [focused] = this._list.getFocusedElements();
return focused instanceof CellViewModel
? this._renderedEditors.get(focused)
: undefined;
}
}
export class NotebookEditor extends BaseEditor implements INotebookEditor {
static readonly ID: string = 'workbench.editor.notebook';
private rootElement!: HTMLElement;
private body!: HTMLElement;
private webview: BackLayerWebView | null = null;
private list: NotebookCellList | undefined;
private control: ICompositeCodeEditor | undefined;
private renderedEditors: Map<ICellViewModel, ICodeEditor | undefined> = new Map();
private notebookViewModel: NotebookViewModel | undefined;
private localStore: DisposableStore = this._register(new DisposableStore());
private editorMemento: IEditorMemento<INotebookEditorViewState>;
private readonly groupListener = this._register(new MutableDisposable());
private fontInfo: BareFontInfo | undefined;
private dimension: DOM.Dimension | null = null;
private editorFocus: IContextKey<boolean> | null = null;
private outputRenderer: OutputRenderer;
private findWidget: NotebookFindWidget;
constructor(
@ITelemetryService telemetryService: ITelemetryService,
@IThemeService themeService: IThemeService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IStorageService storageService: IStorageService,
@IWebviewService private webviewService: IWebviewService,
@INotebookService private notebookService: INotebookService,
@IEditorGroupsService editorGroupService: IEditorGroupsService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IEnvironmentService private readonly environmentSerice: IEnvironmentService,
@IContextKeyService private readonly contextKeyService: IContextKeyService,
) {
super(NotebookEditor.ID, telemetryService, themeService, storageService);
this.editorMemento = this.getEditorMemento<INotebookEditorViewState>(editorGroupService, NOTEBOOK_EDITOR_VIEW_STATE_PREFERENCE_KEY);
this.outputRenderer = new OutputRenderer(this, this.instantiationService);
this.findWidget = this.instantiationService.createInstance(NotebookFindWidget, this);
this.findWidget.updateTheme(this.themeService.getColorTheme());
}
get viewModel() {
return this.notebookViewModel;
}
get minimumWidth(): number { return 375; }
get maximumWidth(): number { return Number.POSITIVE_INFINITY; }
// these setters need to exist because this extends from BaseEditor
set minimumWidth(value: number) { /*noop*/ }
set maximumWidth(value: number) { /*noop*/ }
//#region Editor Core
public get isNotebookEditor() {
return true;
}
protected createEditor(parent: HTMLElement): void {
this.rootElement = DOM.append(parent, $('.notebook-editor'));
this.createBody(this.rootElement);
this.generateFontInfo();
this.editorFocus = NOTEBOOK_EDITOR_FOCUSED.bindTo(this.contextKeyService);
this._register(this.onDidFocus(() => {
this.editorFocus?.set(true);
}));
this._register(this.onDidBlur(() => {
this.editorFocus?.set(false);
}));
}
private generateFontInfo(): void {
const editorOptions = this.configurationService.getValue<IEditorOptions>('editor');
this.fontInfo = BareFontInfo.createFromRawSettings(editorOptions, getZoomLevel());
}
private createBody(parent: HTMLElement): void {
this.body = document.createElement('div');
DOM.addClass(this.body, 'cell-list-container');
this.createCellList();
DOM.append(parent, this.body);
DOM.append(parent, this.findWidget.getDomNode());
}
private createCellList(): void {
DOM.addClass(this.body, 'cell-list-container');
const renders = [
this.instantiationService.createInstance(CodeCellRenderer, this, this.renderedEditors),
this.instantiationService.createInstance(MarkdownCellRenderer, this),
];
this.list = <NotebookCellList>this.instantiationService.createInstance(
NotebookCellList,
'NotebookCellList',
this.body,
this.instantiationService.createInstance(NotebookCellListDelegate),
renders,
this.contextKeyService,
{
setRowLineHeight: false,
setRowHeight: false,
supportDynamicHeights: true,
horizontalScrolling: false,
keyboardSupport: false,
mouseSupport: true,
multipleSelectionSupport: false,
enableKeyboardNavigation: true,
overrideStyles: {
listBackground: editorBackground,
listActiveSelectionBackground: editorBackground,
listActiveSelectionForeground: foreground,
listFocusAndSelectionBackground: editorBackground,
listFocusAndSelectionForeground: foreground,
listFocusBackground: editorBackground,
listFocusForeground: foreground,
listHoverForeground: foreground,
listHoverBackground: editorBackground,
listHoverOutline: focusBorder,
listFocusOutline: focusBorder,
listInactiveSelectionBackground: editorBackground,
listInactiveSelectionForeground: foreground,
listInactiveFocusBackground: editorBackground,
listInactiveFocusOutline: editorBackground,
}
},
);
this.control = new NotebookCodeEditors(this.list, this.renderedEditors);
this.webview = new BackLayerWebView(this.webviewService, this.notebookService, this, this.environmentSerice);
this.list.rowsContainer.appendChild(this.webview.element);
this._register(this.list);
}
getControl() {
return this.control;
}
onHide() {
this.editorFocus?.set(false);
if (this.webview) {
this.localStore.clear();
this.list?.rowsContainer.removeChild(this.webview?.element);
this.webview?.dispose();
this.webview = null;
}
this.list?.splice(0, this.list?.length);
if (this.notebookViewModel && !this.notebookViewModel.isDirty()) {
this.notebookService.destoryNotebookDocument(this.notebookViewModel.viewType!, this.notebookViewModel!.notebookDocument);
this.notebookViewModel.dispose();
this.notebookViewModel = undefined;
}
super.onHide();
}
setEditorVisible(visible: boolean, group: IEditorGroup | undefined): void {
super.setEditorVisible(visible, group);
this.groupListener.value = ((group as IEditorGroupView).onWillCloseEditor(e => this.onWillCloseEditorInGroup(e)));
}
private onWillCloseEditorInGroup(e: IEditorCloseEvent): void {
const editor = e.editor;
if (!(editor instanceof NotebookEditorInput)) {
return; // only handle files
}
if (editor === this.input) {
this.saveTextEditorViewState(editor);
}
}
focus() {
super.focus();
this.editorFocus?.set(true);
}
async setInput(input: NotebookEditorInput, options: EditorOptions | undefined, token: CancellationToken): Promise<void> {
if (this.input instanceof NotebookEditorInput) {
this.saveTextEditorViewState(this.input);
}
await super.setInput(input, options, token);
const model = await input.resolve();
if (this.notebookViewModel === undefined || !this.notebookViewModel.equal(model) || this.webview === null) {
this.detachModel();
await this.attachModel(input, model);
}
// reveal cell if editor options tell to do so
if (options instanceof NotebookEditorOptions && options.cellOptions) {
const cellOptions = options.cellOptions;
const cell = this.notebookViewModel!.viewCells.find(cell => cell.uri.toString() === cellOptions.resource.toString());
if (cell) {
this.revealInCenterIfOutsideViewport(cell);
const editor = this.renderedEditors.get(cell)!;
if (editor) {
if (cellOptions.options?.selection) {
const { selection } = cellOptions.options;
editor.setSelection({
...selection,
endLineNumber: selection.endLineNumber || selection.startLineNumber,
endColumn: selection.endColumn || selection.startColumn
});
}
if (!cellOptions.options?.preserveFocus) {
editor.focus();
}
}
}
}
}
clearInput(): void {
if (this.input && this.input instanceof NotebookEditorInput && !this.input.isDisposed()) {
this.saveTextEditorViewState(this.input);
}
super.clearInput();
}
private detachModel() {
this.localStore.clear();
this.notebookViewModel?.dispose();
this.notebookViewModel = undefined;
this.webview?.clearInsets();
this.webview?.clearPreloadsCache();
this.findWidget.clear();
}
private async attachModel(input: NotebookEditorInput, model: NotebookEditorModel) {
if (!this.webview) {
this.webview = new BackLayerWebView(this.webviewService, this.notebookService, this, this.environmentSerice);
this.list?.rowsContainer.insertAdjacentElement('afterbegin', this.webview!.element);
}
this.notebookViewModel = this.instantiationService.createInstance(NotebookViewModel, input.viewType!, model);
const viewState = this.loadTextEditorViewState(input);
this.notebookViewModel.restoreEditorViewState(viewState);
this.localStore.add(this.notebookViewModel.onDidChangeViewCells((e) => {
if (e.synchronous) {
e.splices.reverse().forEach((diff) => {
this.list?.splice(diff[0], diff[1], diff[2]);
});
} else {
DOM.scheduleAtNextAnimationFrame(() => {
e.splices.reverse().forEach((diff) => {
this.list?.splice(diff[0], diff[1], diff[2]);
});
});
}
}));
this.webview?.updateRendererPreloads(this.notebookViewModel.renderers);
this.localStore.add(this.list!.onWillScroll(e => {
this.webview!.updateViewScrollTop(-e.scrollTop, []);
}));
this.localStore.add(this.list!.onDidChangeContentHeight(() => {
const scrollTop = this.list?.scrollTop || 0;
const scrollHeight = this.list?.scrollHeight || 0;
this.webview!.element.style.height = `${scrollHeight}px`;
let updateItems: { cell: CellViewModel, output: IOutput, cellTop: number }[] = [];
if (this.webview?.insetMapping) {
this.webview?.insetMapping.forEach((value, key) => {
let cell = value.cell;
let index = this.notebookViewModel!.getViewCellIndex(cell);
let cellTop = this.list?.getAbsoluteTop(index) || 0;
if (this.webview!.shouldUpdateInset(cell, key, cellTop)) {
updateItems.push({
cell: cell,
output: key,
cellTop: cellTop
});
}
});
if (updateItems.length) {
this.webview?.updateViewScrollTop(-scrollTop, updateItems);
}
}
}));
this.localStore.add(this.list!.onDidChangeFocus((e) => {
if (e.elements.length > 0) {
this.notebookService.updateNotebookActiveCell(input.viewType!, input.resource!, e.elements[0].handle);
}
}));
this.list?.splice(0, this.list?.length || 0);
this.list?.splice(0, 0, this.notebookViewModel!.viewCells as CellViewModel[]);
this.list?.layout();
}
private saveTextEditorViewState(input: NotebookEditorInput): void {
if (this.group && this.notebookViewModel) {
const state = this.notebookViewModel.saveEditorViewState();
this.editorMemento.saveEditorState(this.group, input.resource, state);
}
}
private loadTextEditorViewState(input: NotebookEditorInput): INotebookEditorViewState | undefined {
if (this.group) {
return this.editorMemento.loadEditorState(this.group, input.resource);
}
return;
}
layout(dimension: DOM.Dimension): void {
this.dimension = new DOM.Dimension(dimension.width, dimension.height);
DOM.toggleClass(this.rootElement, 'mid-width', dimension.width < 1000 && dimension.width >= 600);
DOM.toggleClass(this.rootElement, 'narrow-width', dimension.width < 600);
DOM.size(this.body, dimension.width, dimension.height);
this.list?.layout(dimension.height, dimension.width);
}
protected saveState(): void {
if (this.input instanceof NotebookEditorInput) {
this.saveTextEditorViewState(this.input);
}
super.saveState();
}
//#endregion
//#region Editor Features
selectElement(cell: ICellViewModel) {
const index = this.notebookViewModel?.getViewCellIndex(cell);
if (index !== undefined) {
this.list?.setSelection([index]);
this.list?.setFocus([index]);
}
}
revealInView(cell: ICellViewModel) {
const index = this.notebookViewModel?.getViewCellIndex(cell);
if (index !== undefined) {
this.list?.revealInView(index);
}
}
revealInCenterIfOutsideViewport(cell: ICellViewModel) {
const index = this.notebookViewModel?.getViewCellIndex(cell);
if (index !== undefined) {
this.list?.revealInCenterIfOutsideViewport(index);
}
}
revealInCenter(cell: ICellViewModel) {
const index = this.notebookViewModel?.getViewCellIndex(cell);
if (index !== undefined) {
this.list?.revealInCenter(index);
}
}
revealLineInView(cell: ICellViewModel, line: number): void {
const index = this.notebookViewModel?.getViewCellIndex(cell);
if (index !== undefined) {
this.list?.revealLineInView(index, line);
}
}
revealLineInCenter(cell: ICellViewModel, line: number) {
const index = this.notebookViewModel?.getViewCellIndex(cell);
if (index !== undefined) {
this.list?.revealLineInCenter(index, line);
}
}
revealLineInCenterIfOutsideViewport(cell: ICellViewModel, line: number) {
const index = this.notebookViewModel?.getViewCellIndex(cell);
if (index !== undefined) {
this.list?.revealLineInCenterIfOutsideViewport(index, line);
}
}
revealRangeInView(cell: ICellViewModel, range: Range): void {
const index = this.notebookViewModel?.getViewCellIndex(cell);
if (index !== undefined) {
this.list?.revealRangeInView(index, range);
}
}
revealRangeInCenter(cell: ICellViewModel, range: Range): void {
const index = this.notebookViewModel?.getViewCellIndex(cell);
if (index !== undefined) {
this.list?.revealRangeInCenter(index, range);
}
}
revealRangeInCenterIfOutsideViewport(cell: ICellViewModel, range: Range): void {
const index = this.notebookViewModel?.getViewCellIndex(cell);
if (index !== undefined) {
this.list?.revealRangeInCenterIfOutsideViewport(index, range);
}
}
setCellSelection(cell: ICellViewModel, range: Range): void {
const index = this.notebookViewModel?.getViewCellIndex(cell);
if (index !== undefined) {
this.list?.setCellSelection(index, range);
}
}
changeDecorations(callback: (changeAccessor: IModelDecorationsChangeAccessor) => any): any {
return this.notebookViewModel?.changeDecorations(callback);
}
//#endregion
//#region Find Delegate
public showFind() {
this.findWidget.reveal();
}
public hideFind() {
this.findWidget.hide();
this.focus();
}
//#endregion
//#region Cell operations
layoutNotebookCell(cell: ICellViewModel, height: number) {
let relayout = (cell: ICellViewModel, height: number) => {
let index = this.notebookViewModel!.getViewCellIndex(cell);
if (index >= 0) {
this.list?.updateElementHeight(index, height);
}
};
DOM.scheduleAtNextAnimationFrame(() => {
relayout(cell, height);
});
}
async insertNotebookCell(cell: ICellViewModel, type: CellKind, direction: 'above' | 'below', initialText: string = ''): Promise<void> {
const newLanguages = this.notebookViewModel!.languages;
const language = newLanguages && newLanguages.length ? newLanguages[0] : 'markdown';
const index = this.notebookViewModel!.getViewCellIndex(cell);
const insertIndex = direction === 'above' ? index : index + 1;
const newModeCell = await this.notebookService.createNotebookCell(this.notebookViewModel!.viewType, this.notebookViewModel!.uri, insertIndex, language, type);
newModeCell!.source = initialText.split(/\r?\n/g);
const newCell = this.notebookViewModel!.insertCell(insertIndex, newModeCell!, true);
this.list?.setFocus([insertIndex]);
if (type === CellKind.Markdown) {
newCell.state = CellState.Editing;
}
DOM.scheduleAtNextAnimationFrame(() => {
this.list?.revealInCenterIfOutsideViewport(insertIndex);
});
}
async deleteNotebookCell(cell: ICellViewModel): Promise<void> {
(cell as CellViewModel).save();
const index = this.notebookViewModel!.getViewCellIndex(cell);
await this.notebookService.deleteNotebookCell(this.notebookViewModel!.viewType, this.notebookViewModel!.uri, index);
this.notebookViewModel!.deleteCell(index, true);
}
moveCellDown(cell: ICellViewModel): void {
const index = this.notebookViewModel!.getViewCellIndex(cell);
const newIdx = index + 1;
this.moveCellToIndex(cell, index, newIdx);
}
moveCellUp(cell: ICellViewModel): void {
const index = this.notebookViewModel!.getViewCellIndex(cell);
const newIdx = index - 1;
this.moveCellToIndex(cell, index, newIdx);
}
private moveCellToIndex(cell: ICellViewModel, index: number, newIdx: number): void {
if (!this.notebookViewModel!.moveCellToIdx(index, newIdx, true)) {
return;
}
DOM.scheduleAtNextAnimationFrame(() => {
this.list?.revealInCenterIfOutsideViewport(index + 1);
});
}
editNotebookCell(cell: CellViewModel): void {
cell.state = CellState.Editing;
this.renderedEditors.get(cell)?.focus();
}
saveNotebookCell(cell: ICellViewModel): void {
cell.state = CellState.Preview;
}
getActiveCell() {
let elements = this.list?.getFocusedElements();
if (elements && elements.length) {
return elements[0];
}
return undefined;
}
focusNotebookCell(cell: ICellViewModel, focusEditor: boolean) {
const index = this.notebookViewModel!.getViewCellIndex(cell);
if (focusEditor) {
this.list?.setFocus([index]);
this.list?.setSelection([index]);
this.list?.focusView();
cell.state = CellState.Editing;
cell.focusMode = CellFocusMode.Editor;
} else {
let itemDOM = this.list?.domElementAtIndex(index);
if (document.activeElement && itemDOM && itemDOM.contains(document.activeElement)) {
(document.activeElement as HTMLElement).blur();
}
cell.state = CellState.Preview;
cell.focusMode = CellFocusMode.Editor;
this.list?.setFocus([index]);
this.list?.setSelection([index]);
this.list?.focusView();
}
}
//#endregion
//#region MISC
getLayoutInfo(): NotebookLayoutInfo {
if (!this.list) {
throw new Error('Editor is not initalized successfully');
}
return {
width: this.dimension!.width,
height: this.dimension!.height,
fontInfo: this.fontInfo!
};
}
getFontInfo(): BareFontInfo | undefined {
return this.fontInfo;
}
triggerScroll(event: IMouseWheelEvent) {
this.list?.triggerScrollFromMouseWheelEvent(event);
}
createInset(cell: CellViewModel, output: IOutput, shadowContent: string, offset: number) {
if (!this.webview) {
return;
}
let preloads = this.notebookViewModel!.renderers;
if (!this.webview!.insetMapping.has(output)) {
let index = this.notebookViewModel!.getViewCellIndex(cell);
let cellTop = this.list?.getAbsoluteTop(index) || 0;
this.webview!.createInset(cell, output, cellTop, offset, shadowContent, preloads);
} else {
let index = this.notebookViewModel!.getViewCellIndex(cell);
let cellTop = this.list?.getAbsoluteTop(index) || 0;
let scrollTop = this.list?.scrollTop || 0;
this.webview!.updateViewScrollTop(-scrollTop, [{ cell: cell, output: output, cellTop: cellTop }]);
}
}
removeInset(output: IOutput) {
if (!this.webview) {
return;
}
this.webview!.removeInset(output);
}
getOutputRenderer(): OutputRenderer {
return this.outputRenderer;
}
//#endregion
}
const embeddedEditorBackground = 'walkThrough.embeddedEditorBackground';
registerThemingParticipant((theme, collector) => {
const color = getExtraColor(theme, embeddedEditorBackground, { dark: 'rgba(0, 0, 0, .4)', extra_dark: 'rgba(200, 235, 255, .064)', light: '#f4f4f4', hc: null });
if (color) {
collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .cell .monaco-editor-background,
.monaco-workbench .part.editor > .content .notebook-editor .cell .margin-view-overlays { background: ${color}; }`);
}
const link = theme.getColor(textLinkForeground);
if (link) {
collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .cell a { color: ${link}; }`);
}
const activeLink = theme.getColor(textLinkActiveForeground);
if (activeLink) {
collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .cell a:hover,
.monaco-workbench .part.editor > .content .notebook-editor .cell a:active { color: ${activeLink}; }`);
}
const shortcut = theme.getColor(textPreformatForeground);
if (shortcut) {
collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor code,
.monaco-workbench .part.editor > .content .notebook-editor .shortcut { color: ${shortcut}; }`);
}
const border = theme.getColor(contrastBorder);
if (border) {
collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .monaco-editor { border-color: ${border}; }`);
}
const quoteBackground = theme.getColor(textBlockQuoteBackground);
if (quoteBackground) {
collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor blockquote { background: ${quoteBackground}; }`);
}
const quoteBorder = theme.getColor(textBlockQuoteBorder);
if (quoteBorder) {
collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor blockquote { border-color: ${quoteBorder}; }`);
}
const inactiveListItem = theme.getColor('list.inactiveSelectionBackground');
if (inactiveListItem) {
collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .output { background-color: ${inactiveListItem}; }`);
}
// Cell Margin
collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .monaco-list-row > div.cell { padding: 8px ${CELL_MARGIN}px 8px ${CELL_MARGIN}px; }`);
collector.addRule(`.monaco-workbench .part.editor > .content .notebook-editor .output { margin: 8px ${CELL_MARGIN}px; }`);
});
| src/vs/workbench/contrib/notebook/browser/notebookEditor.ts | 1 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.002294014673680067,
0.0002402247191639617,
0.0001631640043342486,
0.0001731362281134352,
0.00030175421852618456
] |
{
"id": 6,
"code_window": [
"\t\t\t\t// we only validate the first focused element\n",
"\t\t\t\tconst focusedElement = e.elements[0];\n",
"\n",
"\t\t\t\tcursorSelectionLisener = focusedElement.onDidChangeCursorSelection(() => {\n",
"\t\t\t\t\trecomputeContext(focusedElement);\n",
"\t\t\t\t});\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tcursorSelectionListener = focusedElement.onDidChangeCursorSelection(() => {\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/view/notebookCellList.ts",
"type": "replace",
"edit_start_line_idx": 87
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { mixin, deepClone } from 'vs/base/common/objects';
import { Event, Emitter } from 'vs/base/common/event';
import type * as vscode from 'vscode';
import { ExtHostWorkspace, IExtHostWorkspace } from 'vs/workbench/api/common/extHostWorkspace';
import { ExtHostConfigurationShape, MainThreadConfigurationShape, IConfigurationInitData, MainContext } from './extHost.protocol';
import { ConfigurationTarget as ExtHostConfigurationTarget } from './extHostTypes';
import { ConfigurationTarget, IConfigurationChange, IConfigurationData, IConfigurationOverrides } from 'vs/platform/configuration/common/configuration';
import { Configuration, ConfigurationChangeEvent } from 'vs/platform/configuration/common/configurationModels';
import { ConfigurationScope, OVERRIDE_PROPERTY_PATTERN } from 'vs/platform/configuration/common/configurationRegistry';
import { isObject } from 'vs/base/common/types';
import { ExtensionIdentifier, IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { Barrier } from 'vs/base/common/async';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
import { ILogService } from 'vs/platform/log/common/log';
import { Workspace } from 'vs/platform/workspace/common/workspace';
import { URI } from 'vs/base/common/uri';
function lookUp(tree: any, key: string) {
if (key) {
const parts = key.split('.');
let node = tree;
for (let i = 0; node && i < parts.length; i++) {
node = node[parts[i]];
}
return node;
}
}
type ConfigurationInspect<T> = {
key: string;
defaultValue?: T;
globalValue?: T;
workspaceValue?: T,
workspaceFolderValue?: T,
defaultLanguageValue?: T;
globalLanguageValue?: T;
workspaceLanguageValue?: T;
workspaceFolderLanguageValue?: T;
languageIds?: string[];
};
function isUri(thing: any): thing is vscode.Uri {
return thing instanceof URI;
}
function isResourceLanguage(thing: any): thing is { uri: URI, languageId: string } {
return thing
&& thing.uri instanceof URI
&& (thing.languageId && typeof thing.languageId === 'string');
}
function isLanguage(thing: any): thing is { languageId: string } {
return thing
&& !thing.uri
&& (thing.languageId && typeof thing.languageId === 'string');
}
function isWorkspaceFolder(thing: any): thing is vscode.WorkspaceFolder {
return thing
&& thing.uri instanceof URI
&& (!thing.name || typeof thing.name === 'string')
&& (!thing.index || typeof thing.index === 'number');
}
function scopeToOverrides(scope: vscode.ConfigurationScope | undefined | null): IConfigurationOverrides | undefined {
if (isUri(scope)) {
return { resource: scope };
}
if (isResourceLanguage(scope)) {
return { resource: scope.uri, overrideIdentifier: scope.languageId };
}
if (isLanguage(scope)) {
return { overrideIdentifier: scope.languageId };
}
if (isWorkspaceFolder(scope)) {
return { resource: scope.uri };
}
if (scope === null) {
return { resource: null };
}
return undefined;
}
export class ExtHostConfiguration implements ExtHostConfigurationShape {
readonly _serviceBrand: undefined;
private readonly _proxy: MainThreadConfigurationShape;
private readonly _logService: ILogService;
private readonly _extHostWorkspace: ExtHostWorkspace;
private readonly _barrier: Barrier;
private _actual: ExtHostConfigProvider | null;
constructor(
@IExtHostRpcService extHostRpc: IExtHostRpcService,
@IExtHostWorkspace extHostWorkspace: IExtHostWorkspace,
@ILogService logService: ILogService,
) {
this._proxy = extHostRpc.getProxy(MainContext.MainThreadConfiguration);
this._extHostWorkspace = extHostWorkspace;
this._logService = logService;
this._barrier = new Barrier();
this._actual = null;
}
public getConfigProvider(): Promise<ExtHostConfigProvider> {
return this._barrier.wait().then(_ => this._actual!);
}
$initializeConfiguration(data: IConfigurationInitData): void {
this._actual = new ExtHostConfigProvider(this._proxy, this._extHostWorkspace, data, this._logService);
this._barrier.open();
}
$acceptConfigurationChanged(data: IConfigurationInitData, change: IConfigurationChange): void {
this.getConfigProvider().then(provider => provider.$acceptConfigurationChanged(data, change));
}
}
export class ExtHostConfigProvider {
private readonly _onDidChangeConfiguration = new Emitter<vscode.ConfigurationChangeEvent>();
private readonly _proxy: MainThreadConfigurationShape;
private readonly _extHostWorkspace: ExtHostWorkspace;
private _configurationScopes: Map<string, ConfigurationScope | undefined>;
private _configuration: Configuration;
private _logService: ILogService;
constructor(proxy: MainThreadConfigurationShape, extHostWorkspace: ExtHostWorkspace, data: IConfigurationInitData, logService: ILogService) {
this._proxy = proxy;
this._logService = logService;
this._extHostWorkspace = extHostWorkspace;
this._configuration = Configuration.parse(data);
this._configurationScopes = this._toMap(data.configurationScopes);
}
get onDidChangeConfiguration(): Event<vscode.ConfigurationChangeEvent> {
return this._onDidChangeConfiguration && this._onDidChangeConfiguration.event;
}
$acceptConfigurationChanged(data: IConfigurationInitData, change: IConfigurationChange) {
const previous = { data: this._configuration.toData(), workspace: this._extHostWorkspace.workspace };
this._configuration = Configuration.parse(data);
this._configurationScopes = this._toMap(data.configurationScopes);
this._onDidChangeConfiguration.fire(this._toConfigurationChangeEvent(change, previous));
}
getConfiguration(section?: string, scope?: vscode.ConfigurationScope | null, extensionDescription?: IExtensionDescription): vscode.WorkspaceConfiguration {
const overrides = scopeToOverrides(scope) || {};
const config = this._toReadonlyValue(section
? lookUp(this._configuration.getValue(undefined, overrides, this._extHostWorkspace.workspace), section)
: this._configuration.getValue(undefined, overrides, this._extHostWorkspace.workspace));
if (section) {
this._validateConfigurationAccess(section, overrides, extensionDescription?.identifier);
}
function parseConfigurationTarget(arg: boolean | ExtHostConfigurationTarget): ConfigurationTarget | null {
if (arg === undefined || arg === null) {
return null;
}
if (typeof arg === 'boolean') {
return arg ? ConfigurationTarget.USER : ConfigurationTarget.WORKSPACE;
}
switch (arg) {
case ExtHostConfigurationTarget.Global: return ConfigurationTarget.USER;
case ExtHostConfigurationTarget.Workspace: return ConfigurationTarget.WORKSPACE;
case ExtHostConfigurationTarget.WorkspaceFolder: return ConfigurationTarget.WORKSPACE_FOLDER;
}
}
const result: vscode.WorkspaceConfiguration = {
has(key: string): boolean {
return typeof lookUp(config, key) !== 'undefined';
},
get: <T>(key: string, defaultValue?: T) => {
this._validateConfigurationAccess(section ? `${section}.${key}` : key, overrides, extensionDescription?.identifier);
let result = lookUp(config, key);
if (typeof result === 'undefined') {
result = defaultValue;
} else {
let clonedConfig: any | undefined = undefined;
const cloneOnWriteProxy = (target: any, accessor: string): any => {
let clonedTarget: any | undefined = undefined;
const cloneTarget = () => {
clonedConfig = clonedConfig ? clonedConfig : deepClone(config);
clonedTarget = clonedTarget ? clonedTarget : lookUp(clonedConfig, accessor);
};
return isObject(target) ?
new Proxy(target, {
get: (target: any, property: PropertyKey) => {
if (typeof property === 'string' && property.toLowerCase() === 'tojson') {
cloneTarget();
return () => clonedTarget;
}
if (clonedConfig) {
clonedTarget = clonedTarget ? clonedTarget : lookUp(clonedConfig, accessor);
return clonedTarget[property];
}
const result = target[property];
if (typeof property === 'string') {
return cloneOnWriteProxy(result, `${accessor}.${property}`);
}
return result;
},
set: (_target: any, property: PropertyKey, value: any) => {
cloneTarget();
if (clonedTarget) {
clonedTarget[property] = value;
}
return true;
},
deleteProperty: (_target: any, property: PropertyKey) => {
cloneTarget();
if (clonedTarget) {
delete clonedTarget[property];
}
return true;
},
defineProperty: (_target: any, property: PropertyKey, descriptor: any) => {
cloneTarget();
if (clonedTarget) {
Object.defineProperty(clonedTarget, property, descriptor);
}
return true;
}
}) : target;
};
result = cloneOnWriteProxy(result, key);
}
return result;
},
update: (key: string, value: any, extHostConfigurationTarget: ExtHostConfigurationTarget | boolean, scopeToLanguage?: boolean) => {
key = section ? `${section}.${key}` : key;
const target = parseConfigurationTarget(extHostConfigurationTarget);
if (value !== undefined) {
return this._proxy.$updateConfigurationOption(target, key, value, overrides, scopeToLanguage);
} else {
return this._proxy.$removeConfigurationOption(target, key, overrides, scopeToLanguage);
}
},
inspect: <T>(key: string): ConfigurationInspect<T> | undefined => {
key = section ? `${section}.${key}` : key;
const config = deepClone(this._configuration.inspect<T>(key, overrides, this._extHostWorkspace.workspace));
if (config) {
return {
key,
defaultValue: config.default?.value,
globalValue: config.user?.value,
workspaceValue: config.workspace?.value,
workspaceFolderValue: config.workspaceFolder?.value,
defaultLanguageValue: config.default?.override,
globalLanguageValue: config.user?.override,
workspaceLanguageValue: config.workspace?.override,
workspaceFolderLanguageValue: config.workspaceFolder?.override,
languageIds: config.overrideIdentifiers
};
}
return undefined;
}
};
if (typeof config === 'object') {
mixin(result, config, false);
}
return <vscode.WorkspaceConfiguration>Object.freeze(result);
}
private _toReadonlyValue(result: any): any {
const readonlyProxy = (target: any): any => {
return isObject(target) ?
new Proxy(target, {
get: (target: any, property: PropertyKey) => readonlyProxy(target[property]),
set: (_target: any, property: PropertyKey, _value: any) => { throw new Error(`TypeError: Cannot assign to read only property '${String(property)}' of object`); },
deleteProperty: (_target: any, property: PropertyKey) => { throw new Error(`TypeError: Cannot delete read only property '${String(property)}' of object`); },
defineProperty: (_target: any, property: PropertyKey) => { throw new Error(`TypeError: Cannot define property '${String(property)}' for a readonly object`); },
setPrototypeOf: (_target: any) => { throw new Error(`TypeError: Cannot set prototype for a readonly object`); },
isExtensible: () => false,
preventExtensions: () => true
}) : target;
};
return readonlyProxy(result);
}
private _validateConfigurationAccess(key: string, overrides?: IConfigurationOverrides, extensionId?: ExtensionIdentifier): void {
const scope = OVERRIDE_PROPERTY_PATTERN.test(key) ? ConfigurationScope.RESOURCE : this._configurationScopes.get(key);
const extensionIdText = extensionId ? `[${extensionId.value}] ` : '';
if (ConfigurationScope.RESOURCE === scope) {
if (typeof overrides?.resource === 'undefined') {
this._logService.warn(`${extensionIdText}Accessing a resource scoped configuration without providing a resource is not expected. To get the effective value for '${key}', provide the URI of a resource or 'null' for any resource.`);
}
return;
}
if (ConfigurationScope.WINDOW === scope) {
if (overrides?.resource) {
this._logService.warn(`${extensionIdText}Accessing a window scoped configuration for a resource is not expected. To associate '${key}' to a resource, define its scope to 'resource' in configuration contributions in 'package.json'.`);
}
return;
}
}
private _toConfigurationChangeEvent(change: IConfigurationChange, previous: { data: IConfigurationData, workspace: Workspace | undefined }): vscode.ConfigurationChangeEvent {
const event = new ConfigurationChangeEvent(change, previous, this._configuration, this._extHostWorkspace.workspace);
return Object.freeze({
affectsConfiguration: (section: string, scope?: vscode.ConfigurationScope) => event.affectsConfiguration(section, scopeToOverrides(scope))
});
}
private _toMap(scopes: [string, ConfigurationScope | undefined][]): Map<string, ConfigurationScope | undefined> {
return scopes.reduce((result, scope) => { result.set(scope[0], scope[1]); return result; }, new Map<string, ConfigurationScope | undefined>());
}
}
export const IExtHostConfiguration = createDecorator<IExtHostConfiguration>('IExtHostConfiguration');
export interface IExtHostConfiguration extends ExtHostConfiguration { }
| src/vs/workbench/api/common/extHostConfiguration.ts | 0 | https://github.com/microsoft/vscode/commit/542818bfc9a8f27ad19f3cb3c366309b83007b99 | [
0.002861789893358946,
0.00025094873853959143,
0.0001639407710172236,
0.0001725216570775956,
0.00045450153993442655
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.