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": 1,
"code_window": [
" onChange={this.handleChange('xsGutter')}\n",
" row\n",
" >\n",
" <LabelRadio label=\"false\" value=\"false\" />\n",
" <LabelRadio label=\"8\" value=\"8\" />\n",
" <LabelRadio label=\"16\" value=\"16\" />\n",
" <LabelRadio label=\"24\" value=\"24\" />\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" <LabelRadio label=\"0\" value=\"0\" />\n"
],
"file_path": "docs/site/src/pages/layout/responsive-ui/GuttersLayout.js",
"type": "replace",
"edit_start_line_idx": 78
} | // @flow weak
import React from 'react';
import Divider from 'material-ui/Divider';
export default function InsetDivider() {
return (
<div style={{ padding: 2, width: 100 }}>
<Divider inset />
</div>
);
}
| test/regressions/site/src/tests/Divider/InsetDivider.js | 0 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.00017465456039644778,
0.00017273938283324242,
0.00017082421982195228,
0.00017273938283324242,
0.000001915170287247747
] |
{
"id": 1,
"code_window": [
" onChange={this.handleChange('xsGutter')}\n",
" row\n",
" >\n",
" <LabelRadio label=\"false\" value=\"false\" />\n",
" <LabelRadio label=\"8\" value=\"8\" />\n",
" <LabelRadio label=\"16\" value=\"16\" />\n",
" <LabelRadio label=\"24\" value=\"24\" />\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" <LabelRadio label=\"0\" value=\"0\" />\n"
],
"file_path": "docs/site/src/pages/layout/responsive-ui/GuttersLayout.js",
"type": "replace",
"edit_start_line_idx": 78
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M255.125 99.406c-65.804 0-124.928 29.754-167.656 69.875-42.73 40.122-69.75 90.556-69.75 135.126 0 44.57 29.306 75.8 72.56 93.78 43.257 17.983 101.178 24.845 164.845 24.845s121.588-6.86 164.844-24.842c43.254-17.982 72.53-49.212 72.53-93.782 0-44.57-26.99-95.004-69.72-135.125-42.727-40.12-101.85-69.874-167.655-69.874zm0 18.688c60.148 0 115.033 27.43 154.844 64.812 39.81 37.382 63.842 84.752 63.842 121.5 0 36.748-21.747 60.17-61.03 76.5-39.285 16.33-95.373 23.438-157.657 23.438-62.284 0-118.404-7.107-157.688-23.438-39.283-16.33-61.03-39.752-61.03-76.5s24.032-84.118 63.843-121.5c39.81-37.38 94.727-64.812 154.875-64.812zm-54.72 38.594c-3.344-.012-7.06.508-11.124 1.656-20.917 5.907-33.254 41.475-55.06 62.28-24.13 23.022-62.7 40.588-67.907 72.657-3.98 18.225 7.183 36.783 25.374 41.658 18.726 5.017 38.233-6.243 43.25-24.97.723-2.695 1.083-5.41 1.157-8.093h.156c-1.697-38.35 7.258-90.663 56.03-93.5 39.072-2.273 40.46-51.575 8.126-51.688zm87.345 5.218c-11.417.332-23.452 6.93-23.188 18 .53 22.14 37.174 29.432 42.657 1.53 2.74-13.95-8.053-19.862-19.47-19.53zm60 19.438c-18.423.31-18.102 16.73-8.47 23.062 49.25 32.365 8.474 45.84-16.686 32.03-23.675-12.998-87.44-19.36-111.47 3.94-19.138 18.553-3.26 53.928 26.407 32.78 49.634-35.375 94.1-15.667 113.5 28.78l.064-.03c9.498 21.795 33.91 34.08 57.53 27.75 26.004-6.967 41.594-33.934 34.626-59.937-1.334-4.978-3.41-9.56-6.063-13.69-11.404-37.086-37.062-62.783-77.218-73.03-4.758-1.214-8.808-1.713-12.22-1.656zm47.78 70.75c13.585-.253 25.967 8.665 29.658 22.437 4.353 16.248-5.16 32.71-21.407 37.064-16.247 4.354-32.677-5.128-37.03-21.375-4.353-16.248 5.127-32.71 21.375-37.064 2.03-.544 4.08-.875 6.094-1 .44-.027.873-.054 1.31-.062zm-295.186 32.094c.48-.012.952 0 1.437.03 1.11.072 2.224.263 3.345.563 8.97 2.405 14.153 11.376 11.75 20.345-2.404 8.97-11.374 14.153-20.344 11.75-8.97-2.403-14.152-11.373-11.75-20.344 1.973-7.358 8.378-12.178 15.564-12.342zm179.53 10.562c-15.81.215-34.724 5.274-47.468 12.97-14.87 5.774-25.5 20.262-25.5 37.092 0 21.845 17.907 39.75 39.75 39.75.43 0 .854-.017 1.28-.03 32.518 2.444 76.975-14.784 76.47-31.813-.573-19.364-36.953-.27-38-21.876-.47-9.746 27.4-11.914 21.03-25.5-3.588-7.66-14.52-10.77-27.56-10.594zm-33.218 28.97c11.743 0 21.094 9.35 21.094 21.092 0 11.745-9.35 21.063-21.094 21.063-11.743 0-21.062-9.318-21.062-21.063 0-11.744 9.32-21.093 21.062-21.093z" /></svg> | packages/icon-builder/test/fixtures/game-icons/svg/icons/lorc/originals/svg/000000/transparent/acid-blob.svg | 0 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.00022516309400089085,
0.00022516309400089085,
0.00022516309400089085,
0.00022516309400089085,
0
] |
{
"id": 2,
"code_window": [
"import { createStyleSheet } from 'jss-theme-reactor';\n",
"import classNames from 'classnames';\n",
"\n",
"const GUTTERS = [8, 16, 24, 40];\n",
"const GRID_SIZES = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];\n",
"\n",
"function generateGrid(globalStyles, theme, breakpoint) {\n",
" // For the auto layouting\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"const GUTTERS = [0, 8, 16, 24, 40];\n",
"const GRID_SIZES = [true, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];\n"
],
"file_path": "src/Layout/Layout.js",
"type": "replace",
"edit_start_line_idx": 18
} | // @flow weak
import React, { Component, PropTypes } from 'react';
import { createStyleSheet } from 'jss-theme-reactor';
import Layout from 'material-ui/Layout';
import { LabelRadio, RadioGroup } from 'material-ui/Radio';
import Paper from 'material-ui/Paper';
import { FormLabel } from 'material-ui/Form';
const styleSheet = createStyleSheet('GuttersLayout', () => {
return {
root: {
flexGrow: 1,
},
paper: {
height: 140,
width: 100,
},
control: {
padding: 12,
},
};
});
const CELLS = [
{},
{},
{},
];
export default class GuttersLayout extends Component {
static contextTypes = {
styleManager: PropTypes.object.isRequired,
}
state = {
xsGutter: '16',
}
handleChange = (key) => (event, value) => {
this.setState({
[key]: value,
});
}
render() {
const classes = this.context.styleManager.render(styleSheet);
const {
xsGutter,
} = this.state;
return (
<Layout container className={classes.root}>
<Layout item xs={12}>
<Layout
container
className={classes.demo}
xsJustify="center"
xsGutter={xsGutter === 'false' ? false : Number(xsGutter)}
>
{CELLS.map((cell, i) => (
<Layout key={i} item>
<Paper className={classes.paper} />
</Layout>
))}
</Layout>
</Layout>
<Layout item xs={12}>
<Paper className={classes.control}>
<Layout container>
<Layout item>
<FormLabel>xsGutter</FormLabel>
<RadioGroup
aria-label="xsGutter"
selectedValue={xsGutter}
onChange={this.handleChange('xsGutter')}
row
>
<LabelRadio label="false" value="false" />
<LabelRadio label="8" value="8" />
<LabelRadio label="16" value="16" />
<LabelRadio label="24" value="24" />
<LabelRadio label="40" value="40" />
</RadioGroup>
</Layout>
</Layout>
</Paper>
</Layout>
</Layout>
);
}
}
| docs/site/src/pages/layout/responsive-ui/GuttersLayout.js | 1 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.005785178393125534,
0.0015488232020288706,
0.00016843515913933516,
0.0001726695627439767,
0.0021581898909062147
] |
{
"id": 2,
"code_window": [
"import { createStyleSheet } from 'jss-theme-reactor';\n",
"import classNames from 'classnames';\n",
"\n",
"const GUTTERS = [8, 16, 24, 40];\n",
"const GRID_SIZES = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];\n",
"\n",
"function generateGrid(globalStyles, theme, breakpoint) {\n",
" // For the auto layouting\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"const GUTTERS = [0, 8, 16, 24, 40];\n",
"const GRID_SIZES = [true, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];\n"
],
"file_path": "src/Layout/Layout.js",
"type": "replace",
"edit_start_line_idx": 18
} | module.exports = {
env: {
mocha: true,
},
globals: {
expect: false,
},
rules: {
'no-unused-expressions': 'off',
},
};
| test/integration/.eslintrc.js | 0 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.000173022854141891,
0.0001705627073533833,
0.00016810254601296037,
0.0001705627073533833,
0.000002460154064465314
] |
{
"id": 2,
"code_window": [
"import { createStyleSheet } from 'jss-theme-reactor';\n",
"import classNames from 'classnames';\n",
"\n",
"const GUTTERS = [8, 16, 24, 40];\n",
"const GRID_SIZES = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];\n",
"\n",
"function generateGrid(globalStyles, theme, breakpoint) {\n",
" // For the auto layouting\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"const GUTTERS = [0, 8, 16, 24, 40];\n",
"const GRID_SIZES = [true, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];\n"
],
"file_path": "src/Layout/Layout.js",
"type": "replace",
"edit_start_line_idx": 18
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M255.76 44.764c-6.176 0-12.353 1.384-17.137 4.152L85.87 137.276c-9.57 5.536-9.57 14.29 0 19.826l152.753 88.36c9.57 5.536 24.703 5.536 34.272 0l152.753-88.36c9.57-5.535 9.57-14.29 0-19.825l-152.753-88.36c-4.785-2.77-10.96-4.153-17.135-4.153zm1.86 12.423a31.953 18.96 0 0 1 21.194 5.536 31.953 18.96 0 0 1-45.187 26.812 31.953 18.96 0 0 1 23.992-32.347zm58.43 35.208a31.953 18.96 0 0 1 22.13 32.363 31.953 18.96 0 0 1-45.19-26.813 31.953 18.96 0 0 1 23.06-5.55zm-177.603 34.98a31.953 18.96 0 0 1 .002 0 31.953 18.96 0 0 1 21.195 5.535 31.953 18.96 0 0 1-45.19 26.813 31.953 18.96 0 0 1 23.992-32.348zm237.903.26a31.953 18.96 0 0 1 .002 0 31.953 18.96 0 0 1 21.195 5.535 31.953 18.96 0 0 1-45.19 26.812 31.953 18.96 0 0 1 23.993-32.347zm-179.03 35.21a31.953 18.96 0 0 1 22.127 32.362 31.953 18.96 0 1 1-45.187-26.812 31.953 18.96 0 0 1 23.06-5.55zM75.67 173.84c-5.753-.155-9.664 4.336-9.664 12.28v157.696c0 11.052 7.57 24.163 17.14 29.69l146.93 84.848c9.57 5.526 17.14 1.156 17.14-9.895V290.76c0-11.052-7.57-24.16-17.14-29.688l-146.93-84.847c-2.69-1.555-5.225-2.327-7.476-2.387zm360.773.002c-2.25.06-4.783.83-7.474 2.385l-146.935 84.847c-9.57 5.527-17.14 18.638-17.14 29.69v157.7c0 11.05 7.57 15.418 17.14 9.89L428.97 373.51c9.57-5.527 17.137-18.636 17.137-29.688v-157.7c0-7.942-3.91-12.432-9.664-12.278zM89.297 195.77a31.236 18.008 58.094 0 1 33.818 41.183 31.236 18.008 58.094 1 1-45-25.98 31.236 18.008 58.094 0 1 11.182-15.203zm333.52 0A18.008 31.236 31.906 0 1 434 210.973a18.008 31.236 31.906 0 1-45 25.98 18.008 31.236 31.906 0 1 33.818-41.183zm-165.198 2.314a31.953 18.96 0 0 1 21.194 5.535 31.953 18.96 0 0 1-45.187 26.812 31.953 18.96 0 0 1 23.992-32.348zm-56.323 62.35a31.236 18.008 58.094 0 1 33.818 41.183 31.236 18.008 58.094 1 1-45-25.98 31.236 18.008 58.094 0 1 11.182-15.203zm109.52 0A18.008 31.236 31.906 0 1 322 275.637a18.008 31.236 31.906 0 1-45 25.98 18.008 31.236 31.906 0 1 33.818-41.183zM145.296 289.1a31.236 18.008 58.094 0 1 33.818 41.183 31.236 18.008 58.094 0 1-45-25.98 31.236 18.008 58.094 0 1 11.182-15.203zm-55.998 29.38a31.236 18.008 58.094 0 1 33.818 41.184 31.236 18.008 58.094 1 1-45-25.98 31.236 18.008 58.094 0 1 11.182-15.204zm333.52 0A18.008 31.236 31.906 0 1 434 333.684a18.008 31.236 31.906 0 1-45 25.98 18.008 31.236 31.906 0 1 33.818-41.184zm-221.52 64.663a31.236 18.008 58.094 0 1 33.818 41.183 31.236 18.008 58.094 1 1-45-25.98 31.236 18.008 58.094 0 1 11.182-15.203zm109.52 0A18.008 31.236 31.906 0 1 322 398.346a18.008 31.236 31.906 0 1-45 25.98 18.008 31.236 31.906 0 1 33.818-41.183z" /></svg> | packages/icon-builder/test/fixtures/game-icons/svg/icons/delapouite/dice/svg/000000/transparent/perspective-dice-six-faces-six.svg | 0 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.0004547329153865576,
0.0004547329153865576,
0.0004547329153865576,
0.0004547329153865576,
0
] |
{
"id": 2,
"code_window": [
"import { createStyleSheet } from 'jss-theme-reactor';\n",
"import classNames from 'classnames';\n",
"\n",
"const GUTTERS = [8, 16, 24, 40];\n",
"const GRID_SIZES = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];\n",
"\n",
"function generateGrid(globalStyles, theme, breakpoint) {\n",
" // For the auto layouting\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"const GUTTERS = [0, 8, 16, 24, 40];\n",
"const GRID_SIZES = [true, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];\n"
],
"file_path": "src/Layout/Layout.js",
"type": "replace",
"edit_start_line_idx": 18
} | // @flow weak
import React, { Component, Children, cloneElement, PropTypes } from 'react';
import { createStyleSheet } from 'jss-theme-reactor';
import classNames from 'classnames';
import FormGroup from '../Form/FormGroup';
import { find } from '../utils/helpers';
export const styleSheet = createStyleSheet('RadioGroup', () => {
return {
root: {
flex: '1 1 auto',
margin: 0,
padding: 0,
},
};
});
class RadioGroup extends Component {
static propTypes = {
children: PropTypes.node,
/**
* The CSS class name of the root element.
*/
className: PropTypes.string,
name: PropTypes.string,
onBlur: PropTypes.func,
onChange: PropTypes.func,
onKeyDown: PropTypes.func,
selectedValue: PropTypes.string,
};
static contextTypes = {
styleManager: PropTypes.object.isRequired,
};
radios = undefined;
focus = () => {
if (!this.radios || !this.radios.length) {
return;
}
const focusRadios = this.radios.filter((n) => !n.props.disabled);
if (!focusRadios.length) {
return;
}
const selectedRadio = find(focusRadios, (n) => n.props.checked);
if (selectedRadio) {
selectedRadio.focus();
return;
}
focusRadios[0].focus();
};
handleRadioChange = (event, checked) => {
if (checked && this.props.onChange) {
this.props.onChange(event, event.target.value);
}
};
render() {
const {
children,
className: classNameProp,
name,
selectedValue,
onChange, // eslint-disable-line no-unused-vars
...other
} = this.props;
const classes = this.context.styleManager.render(styleSheet);
this.radios = [];
return (
<FormGroup
className={classNames(classes.root, classNameProp)}
data-mui-test="RadioGroup"
role="radiogroup"
{...other}
>
{Children.map(children, (child, index) => {
const selected = selectedValue === child.props.value;
return cloneElement(child, {
key: index,
name,
ref: (c) => { this.radios.push(c); },
checked: selected,
onChange: this.handleRadioChange,
});
})}
</FormGroup>
);
}
}
export default RadioGroup;
| src/Radio/RadioGroup.js | 0 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.04729078337550163,
0.006564450450241566,
0.00016813412366900593,
0.0001780131133273244,
0.014324786141514778
] |
{
"id": 3,
"code_window": [
" flexGrow: 1,\n",
" maxWidth: '100%',\n",
" },\n",
" };\n",
"\n",
" GRID_SIZES.forEach((size) => {\n",
" // Only keep 6 significant numbers.\n",
" const width = `${Math.round((size / 12) * (10 ** 6)) / (10 ** 4)}%`;\n",
"\n",
" /* eslint-disable max-len */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" GRID_SIZES.forEach((size, index) => {\n",
" if (index === 0) { // Skip the first one as handle above.\n",
" return;\n",
" }\n",
"\n"
],
"file_path": "src/Layout/Layout.js",
"type": "replace",
"edit_start_line_idx": 31
} | // @flow weak
import React, { Component, PropTypes } from 'react';
import { createStyleSheet } from 'jss-theme-reactor';
import Layout from 'material-ui/Layout';
import { LabelRadio, RadioGroup } from 'material-ui/Radio';
import Paper from 'material-ui/Paper';
import { FormLabel } from 'material-ui/Form';
const styleSheet = createStyleSheet('GuttersLayout', () => {
return {
root: {
flexGrow: 1,
},
paper: {
height: 140,
width: 100,
},
control: {
padding: 12,
},
};
});
const CELLS = [
{},
{},
{},
];
export default class GuttersLayout extends Component {
static contextTypes = {
styleManager: PropTypes.object.isRequired,
}
state = {
xsGutter: '16',
}
handleChange = (key) => (event, value) => {
this.setState({
[key]: value,
});
}
render() {
const classes = this.context.styleManager.render(styleSheet);
const {
xsGutter,
} = this.state;
return (
<Layout container className={classes.root}>
<Layout item xs={12}>
<Layout
container
className={classes.demo}
xsJustify="center"
xsGutter={xsGutter === 'false' ? false : Number(xsGutter)}
>
{CELLS.map((cell, i) => (
<Layout key={i} item>
<Paper className={classes.paper} />
</Layout>
))}
</Layout>
</Layout>
<Layout item xs={12}>
<Paper className={classes.control}>
<Layout container>
<Layout item>
<FormLabel>xsGutter</FormLabel>
<RadioGroup
aria-label="xsGutter"
selectedValue={xsGutter}
onChange={this.handleChange('xsGutter')}
row
>
<LabelRadio label="false" value="false" />
<LabelRadio label="8" value="8" />
<LabelRadio label="16" value="16" />
<LabelRadio label="24" value="24" />
<LabelRadio label="40" value="40" />
</RadioGroup>
</Layout>
</Layout>
</Paper>
</Layout>
</Layout>
);
}
}
| docs/site/src/pages/layout/responsive-ui/GuttersLayout.js | 1 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.0003172288998030126,
0.0001920750510180369,
0.0001620913972146809,
0.00017208312056027353,
0.00004705411629402079
] |
{
"id": 3,
"code_window": [
" flexGrow: 1,\n",
" maxWidth: '100%',\n",
" },\n",
" };\n",
"\n",
" GRID_SIZES.forEach((size) => {\n",
" // Only keep 6 significant numbers.\n",
" const width = `${Math.round((size / 12) * (10 ** 6)) / (10 ** 4)}%`;\n",
"\n",
" /* eslint-disable max-len */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" GRID_SIZES.forEach((size, index) => {\n",
" if (index === 0) { // Skip the first one as handle above.\n",
" return;\n",
" }\n",
"\n"
],
"file_path": "src/Layout/Layout.js",
"type": "replace",
"edit_start_line_idx": 31
} | Game Icons Test Fixtures
========================
Source: http://game-icons.net/
Date: July 7, 2015
License: [CC BY 3.0](http://creativecommons.org/licenses/by/3.0/)
Extracted from SVG (B/T) set.
Layout:
``svg/`` - follows structure of unzipped game-icons assets.
| packages/icon-builder/test/fixtures/game-icons/README.md | 0 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.00016823355690576136,
0.00016685010632500052,
0.0001654666557442397,
0.00016685010632500052,
0.0000013834505807608366
] |
{
"id": 3,
"code_window": [
" flexGrow: 1,\n",
" maxWidth: '100%',\n",
" },\n",
" };\n",
"\n",
" GRID_SIZES.forEach((size) => {\n",
" // Only keep 6 significant numbers.\n",
" const width = `${Math.round((size / 12) * (10 ** 6)) / (10 ** 4)}%`;\n",
"\n",
" /* eslint-disable max-len */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" GRID_SIZES.forEach((size, index) => {\n",
" if (index === 0) { // Skip the first one as handle above.\n",
" return;\n",
" }\n",
"\n"
],
"file_path": "src/Layout/Layout.js",
"type": "replace",
"edit_start_line_idx": 31
} | // @flow weak
import React, { Component, PropTypes } from 'react';
import { createStyleSheet } from 'jss-theme-reactor';
const globalStyleSheet = createStyleSheet('global', (theme) => {
const { palette, typography } = theme;
return {
'@global': {
html: {
boxSizing: 'border-box',
},
'*, *:before, *:after': {
boxSizing: 'inherit',
},
body: {
margin: 0,
background: palette.background.default,
fontFamily: typography.fontFamily,
color: palette.text.primary,
lineHeight: '1.2',
overflowX: 'hidden',
WebkitFontSmoothing: 'antialiased',
},
a: {
color: palette.accent.A400,
textDecoration: 'none',
},
'a:hover': {
textDecoration: 'underline',
},
p: {
lineHeight: '1.6',
},
},
};
});
const styleSheet = createStyleSheet('TestViewer', () => {
return {
root: {
display: 'flex',
width: '100%',
height: '100vh',
alignItems: 'center',
justifyContent: 'center',
},
};
});
export default class TestViewer extends Component {
static propTypes = {
children: PropTypes.node,
dispatch: PropTypes.func,
routes: PropTypes.array,
};
static contextTypes = {
styleManager: PropTypes.object.isRequired,
};
componentWillMount() {
this.context.styleManager.render(globalStyleSheet);
}
render() {
const { children } = this.props;
const classes = this.context.styleManager.render(styleSheet);
return (
<div className={classes.root}>
{children}
</div>
);
}
}
| test/regressions/site/src/TestViewer.js | 0 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.00020051680621691048,
0.00017612401279620826,
0.00016858745948411524,
0.00017374752496834844,
0.000009453418897464871
] |
{
"id": 3,
"code_window": [
" flexGrow: 1,\n",
" maxWidth: '100%',\n",
" },\n",
" };\n",
"\n",
" GRID_SIZES.forEach((size) => {\n",
" // Only keep 6 significant numbers.\n",
" const width = `${Math.round((size / 12) * (10 ** 6)) / (10 ** 4)}%`;\n",
"\n",
" /* eslint-disable max-len */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" GRID_SIZES.forEach((size, index) => {\n",
" if (index === 0) { // Skip the first one as handle above.\n",
" return;\n",
" }\n",
"\n"
],
"file_path": "src/Layout/Layout.js",
"type": "replace",
"edit_start_line_idx": 31
} | ListItemIcon
============
Props
-----
| Name | Type | Default | Description |
|:-----|:-----|:--------|:------------|
| <span style="color: #31a148">children *</span> | element | | |
| className | string | | The CSS class name of the root element. |
Any other properties supplied will be spread to the root element.
| docs/api/List/ListItemIcon.md | 0 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.00017144724552053958,
0.00017101122648455203,
0.00017057520744856447,
0.00017101122648455203,
4.36019035987556e-7
] |
{
"id": 4,
"code_window": [
"\n",
"function generateGutter(theme, breakpoint) {\n",
" const styles = {};\n",
"\n",
" GUTTERS.forEach((gutter) => {\n",
" styles[`gutter-${breakpoint}-${gutter}`] = {\n",
" margin: -gutter / 2,\n",
" '& > $typeItem': {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" GUTTERS.forEach((gutter, index) => {\n",
" if (index === 0) { // Skip the default style.\n",
" return;\n",
" }\n",
"\n"
],
"file_path": "src/Layout/Layout.js",
"type": "replace",
"edit_start_line_idx": 50
} | // @flow weak
import React, { Component, PropTypes } from 'react';
import { createStyleSheet } from 'jss-theme-reactor';
import Layout from 'material-ui/Layout';
import { LabelRadio, RadioGroup } from 'material-ui/Radio';
import Paper from 'material-ui/Paper';
import { FormLabel } from 'material-ui/Form';
const styleSheet = createStyleSheet('GuttersLayout', () => {
return {
root: {
flexGrow: 1,
},
paper: {
height: 140,
width: 100,
},
control: {
padding: 12,
},
};
});
const CELLS = [
{},
{},
{},
];
export default class GuttersLayout extends Component {
static contextTypes = {
styleManager: PropTypes.object.isRequired,
}
state = {
xsGutter: '16',
}
handleChange = (key) => (event, value) => {
this.setState({
[key]: value,
});
}
render() {
const classes = this.context.styleManager.render(styleSheet);
const {
xsGutter,
} = this.state;
return (
<Layout container className={classes.root}>
<Layout item xs={12}>
<Layout
container
className={classes.demo}
xsJustify="center"
xsGutter={xsGutter === 'false' ? false : Number(xsGutter)}
>
{CELLS.map((cell, i) => (
<Layout key={i} item>
<Paper className={classes.paper} />
</Layout>
))}
</Layout>
</Layout>
<Layout item xs={12}>
<Paper className={classes.control}>
<Layout container>
<Layout item>
<FormLabel>xsGutter</FormLabel>
<RadioGroup
aria-label="xsGutter"
selectedValue={xsGutter}
onChange={this.handleChange('xsGutter')}
row
>
<LabelRadio label="false" value="false" />
<LabelRadio label="8" value="8" />
<LabelRadio label="16" value="16" />
<LabelRadio label="24" value="24" />
<LabelRadio label="40" value="40" />
</RadioGroup>
</Layout>
</Layout>
</Paper>
</Layout>
</Layout>
);
}
}
| docs/site/src/pages/layout/responsive-ui/GuttersLayout.js | 1 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.11018606275320053,
0.01244411151856184,
0.00016885065997485071,
0.00025362230371683836,
0.03271537274122238
] |
{
"id": 4,
"code_window": [
"\n",
"function generateGutter(theme, breakpoint) {\n",
" const styles = {};\n",
"\n",
" GUTTERS.forEach((gutter) => {\n",
" styles[`gutter-${breakpoint}-${gutter}`] = {\n",
" margin: -gutter / 2,\n",
" '& > $typeItem': {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" GUTTERS.forEach((gutter, index) => {\n",
" if (index === 0) { // Skip the default style.\n",
" return;\n",
" }\n",
"\n"
],
"file_path": "src/Layout/Layout.js",
"type": "replace",
"edit_start_line_idx": 50
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M255.76 44.764c-6.176 0-12.353 1.384-17.137 4.152L85.87 137.276c-9.57 5.536-9.57 14.29 0 19.826l152.753 88.36c9.57 5.536 24.703 5.536 34.272 0l152.753-88.36c9.57-5.535 9.57-14.29 0-19.825l-152.753-88.36c-4.785-2.77-10.96-4.153-17.135-4.153zm-.824 53.11c9.013.097 17.117 2.162 24.31 6.192 4.92 2.758 8.143 5.903 9.666 9.438 1.473 3.507 1.56 8.13.26 13.865l-1.6 5.706c-1.06 4.083-1.28 7.02-.66 8.81.57 1.764 1.983 3.278 4.242 4.544l3.39 1.898-33.235 18.62-3.693-2.067c-4.118-2.306-6.744-4.912-7.883-7.82-1.188-2.935-.99-7.603.594-14.005l1.524-5.748c.887-3.423.973-6.23.26-8.418-.653-2.224-2.134-3.983-4.444-5.277-3.515-1.97-7.726-2.676-12.63-2.123-4.956.526-10.072 2.268-15.35 5.225-4.972 2.785-9.487 6.272-13.55 10.46-4.112 4.162-7.64 8.924-10.587 14.288L171.9 138.21c5.318-5.34 10.543-10.01 15.676-14.013 5.134-4 10.554-7.6 16.262-10.8 14.976-8.39 28.903-13.38 41.78-14.967 3.208-.404 6.315-.59 9.32-.557zm50.757 56.7l26.815 15.024-33.235 18.62-26.816-15.023 33.236-18.62zM75.67 173.84c-5.753-.155-9.664 4.336-9.664 12.28v157.696c0 11.052 7.57 24.163 17.14 29.69l146.93 84.848c9.57 5.526 17.14 1.156 17.14-9.895V290.76c0-11.052-7.57-24.16-17.14-29.688l-146.93-84.847c-2.69-1.555-5.225-2.327-7.476-2.387zm360.773.002c-2.25.06-4.783.83-7.474 2.385l-146.935 84.847c-9.57 5.527-17.14 18.638-17.14 29.69v157.7c0 11.05 7.57 15.418 17.14 9.89L428.97 373.51c9.57-5.527 17.137-18.636 17.137-29.688v-157.7c0-7.942-3.91-12.432-9.664-12.278zm-321.545 63.752c6.553 1.366 12.538 3.038 17.954 5.013 5.415 1.976 10.643 4.417 15.68 7.325 13.213 7.63 23.286 16.324 30.218 26.082 6.932 9.7 10.398 20.046 10.398 31.04 0 5.64-1.055 10.094-3.168 13.364-2.112 3.212-5.714 5.91-10.804 8.094l-5.2 1.92c-3.682 1.442-6.093 2.928-7.23 4.46-1.137 1.472-1.705 3.502-1.705 6.092v3.885l-29.325-16.933v-4.23c0-4.72.892-8.376 2.68-10.97 1.787-2.652 5.552-5.14 11.292-7.467l5.2-2.006c3.087-1.21 5.334-2.732 6.742-4.567 1.46-1.803 2.192-4.028 2.192-6.676 0-4.027-1.3-7.915-3.9-11.66-2.6-3.804-6.227-7.05-10.885-9.74-4.387-2.532-9.126-4.29-14.217-5.272-5.09-1.04-10.398-1.254-15.922-.645v-27.11zm269.54 8.607c1.522 0 2.932.165 4.232.493 6.932 1.696 10.398 8.04 10.398 19.034 0 5.64-1.056 11.314-3.168 17.023-2.112 5.65-5.714 12.507-10.804 20.568l-5.2 7.924c-3.682 5.695-6.093 9.963-7.23 12.807-1.137 2.785-1.705 5.473-1.705 8.063v3.885l-29.325 16.932v-4.23c0-4.72.894-9.41 2.68-14.067 1.79-4.715 5.552-11.55 11.292-20.504l5.2-8.01c3.087-4.776 5.334-8.894 6.742-12.354 1.46-3.492 2.192-6.562 2.192-9.21 0-4.028-1.3-6.414-3.898-7.158-2.6-.8-6.23.142-10.887 2.83-4.387 2.533-9.124 6.25-14.215 11.145-5.09 4.84-10.398 10.752-15.922 17.74v-27.11c6.553-6.2 12.536-11.44 17.95-15.718 5.417-4.278 10.645-7.87 15.68-10.777 10.738-6.2 19.4-9.302 25.99-9.307zm-252.723 94.515l29.326 16.93v30.736l-29.325-16.93v-30.735zm239.246 8.06v30.735l-29.325 16.93v-30.733l29.326-16.932z" /></svg> | packages/icon-builder/test/fixtures/game-icons/svg/icons/delapouite/dice/svg/000000/transparent/perspective-dice-six-faces-random.svg | 0 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.0002695241419132799,
0.0002695241419132799,
0.0002695241419132799,
0.0002695241419132799,
0
] |
{
"id": 4,
"code_window": [
"\n",
"function generateGutter(theme, breakpoint) {\n",
" const styles = {};\n",
"\n",
" GUTTERS.forEach((gutter) => {\n",
" styles[`gutter-${breakpoint}-${gutter}`] = {\n",
" margin: -gutter / 2,\n",
" '& > $typeItem': {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" GUTTERS.forEach((gutter, index) => {\n",
" if (index === 0) { // Skip the default style.\n",
" return;\n",
" }\n",
"\n"
],
"file_path": "src/Layout/Layout.js",
"type": "replace",
"edit_start_line_idx": 50
} | // @flow weak
import React, { PropTypes } from 'react';
import { createStyleSheet } from 'jss-theme-reactor';
import classNames from 'classnames';
import marked from 'marked';
import prism from 'docs/site/src/utils/prism';
marked.setOptions({
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: true,
smartypants: false,
highlight(code) {
return prism.highlight(code, prism.languages.jsx);
},
});
const styleSheet = createStyleSheet('MarkdownElement', (theme) => ({
root: {
marginTop: 20,
marginBottom: 20,
padding: '0 10px',
'& pre': {
margin: '25px 0',
padding: '12px 18px',
backgroundColor: theme.palette.background.paper,
borderRadius: 3,
},
'& code': {
lineHeight: 1.6,
fontFamily: 'Consolas, "Liberation Mono", Menlo, Courier, monospace',
padding: '3px 6px',
color: theme.palette.text.primary,
backgroundColor: theme.palette.background.paper,
fontSize: 14,
},
'& h1': {
...theme.typography.display2,
color: theme.palette.text.secondary,
margin: '1em 0 0.7em',
},
'& h2': {
...theme.typography.display1,
color: theme.palette.text.secondary,
margin: '1em 0 0.7em',
},
'& h3': {
...theme.typography.headline,
color: theme.palette.text.secondary,
margin: '1em 0 0.7em',
},
'& p, & ul': {
lineHeight: '1.6',
},
'& p code, & ul code': {
fontSize: 14,
},
'& table': {
width: '100%',
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: '8px 56px 8px 24px',
textAlign: 'left',
},
'& td:last-child': {
paddingRight: 24,
},
'& td compact': {
paddingRight: 24,
},
'& td code': {
fontSize: 13,
},
'& th': {
whiteSpace: 'pre',
borderBottom: `1px solid ${theme.palette.text.lightDivider}`,
padding: '0 56px 0 24px',
textAlign: 'left',
},
'& th:last-child': {
paddingRight: 24,
},
'& tr': {
height: 48,
},
'& thead tr': {
height: 64,
},
'& strong': {
fontWeight: theme.typography.fontWeightMedium,
},
},
}));
function MarkdownElement(props, context) {
const {
className,
text,
} = props;
const classes = context.styleManager.render(styleSheet);
/* eslint-disable react/no-danger */
return (
<div
className={classNames(classes.root, 'markdown-body', className)}
dangerouslySetInnerHTML={{ __html: marked(text) }}
/>
);
/* eslint-enable */
}
MarkdownElement.propTypes = {
className: PropTypes.string,
text: PropTypes.string.isRequired,
};
MarkdownElement.contextTypes = {
styleManager: PropTypes.object.isRequired,
};
export default MarkdownElement;
| docs/site/src/components/MarkdownElement.js | 0 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.0005369727732613683,
0.00019711839559022337,
0.0001654440857237205,
0.00017203646712005138,
0.00009108292579185218
] |
{
"id": 4,
"code_window": [
"\n",
"function generateGutter(theme, breakpoint) {\n",
" const styles = {};\n",
"\n",
" GUTTERS.forEach((gutter) => {\n",
" styles[`gutter-${breakpoint}-${gutter}`] = {\n",
" margin: -gutter / 2,\n",
" '& > $typeItem': {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" GUTTERS.forEach((gutter, index) => {\n",
" if (index === 0) { // Skip the default style.\n",
" return;\n",
" }\n",
"\n"
],
"file_path": "src/Layout/Layout.js",
"type": "replace",
"edit_start_line_idx": 50
} | // @flow weak
/* eslint-env mocha */
import React from 'react';
import { assert } from 'chai';
import { createShallowWithContext } from 'test/utils';
import Drawer, { styleSheet } from './Drawer';
import Slide from '../transitions/Slide';
/**
* An item that goes in lists.
*/
describe('<Drawer />', () => {
let shallow;
let classes;
before(() => {
shallow = createShallowWithContext();
classes = shallow.context.styleManager.render(styleSheet);
});
it('should render a Modal', () => {
const wrapper = shallow(
<Drawer />,
);
assert.strictEqual(wrapper.is('Modal'), true, 'should be a Modal');
});
it('should render Slide > Paper inside the Modal', () => {
const wrapper = shallow(
<Drawer />,
);
const slide = wrapper.childAt(0);
assert.strictEqual(
slide.length === 1 && slide.is(Slide),
true,
'immediate wrapper child should be Slide',
);
const paper = slide.childAt(0);
assert.strictEqual(
paper.length === 1 && paper.is('Paper'),
true,
'Slide child should be Paper',
);
assert.strictEqual(paper.hasClass(classes.paper), true, 'should have the paper class');
});
it('should set the Paper className', () => {
const wrapper = shallow(<Drawer paperClassName="woof"><h1>Hello</h1></Drawer>);
const paper = wrapper.find('Paper');
assert.strictEqual(paper.hasClass(classes.paper), true, 'should have the paper class');
assert.strictEqual(paper.hasClass('woof'), true, 'should have the woof class');
});
it('should be closed by default', () => {
const wrapper = shallow(<Drawer><h1>Hello</h1></Drawer>);
const modal = wrapper;
const slide = modal.find(Slide);
assert.strictEqual(modal.prop('show'), false, 'should not show the modal');
assert.strictEqual(slide.prop('in'), false, 'should not transition in');
});
describe('opening and closing', () => {
let wrapper;
before(() => {
wrapper = shallow(<Drawer><h1>Hello</h1></Drawer>);
});
it('should start closed', () => {
assert.strictEqual(wrapper.prop('show'), false, 'should not show the modal');
assert.strictEqual(wrapper.find(Slide).prop('in'), false, 'should not transition in');
});
it('should open', () => {
wrapper.setProps({ open: true });
assert.strictEqual(wrapper.prop('show'), true, 'should show the modal');
assert.strictEqual(wrapper.find(Slide).prop('in'), true, 'should transition in');
});
it('should close', () => {
wrapper.setProps({ open: false });
assert.strictEqual(wrapper.prop('show'), false, 'should not show the modal');
assert.strictEqual(wrapper.find(Slide).prop('in'), false, 'should not transition in');
});
});
describe('docked', () => {
let wrapper;
before(() => {
wrapper = shallow(<Drawer docked><h1>Hello</h1></Drawer>);
});
it('should render a div instead of a Modal when docked', () => {
assert.strictEqual(wrapper.is('div'), true, 'should be a div element');
assert.strictEqual(wrapper.hasClass(classes.docked), true, 'should have the docked class');
});
it('should render Slide > Paper inside the div', () => {
const slide = wrapper.childAt(0);
assert.strictEqual(
slide.length === 1 && slide.is(Slide),
true,
'immediate wrapper child should be Slide',
);
const paper = slide.childAt(0);
assert.strictEqual(
paper.length === 1 && paper.is('Paper'),
true,
'Slide child should be Paper',
);
});
});
describe('slide direction', () => {
let wrapper;
before(() => {
wrapper = shallow(<Drawer />);
});
it('should return the opposing slide direction', () => {
wrapper.setProps({
anchor: 'left',
});
assert.strictEqual(wrapper.find(Slide).props().direction, 'right');
wrapper.setProps({
anchor: 'right',
});
assert.strictEqual(wrapper.find(Slide).props().direction, 'left');
wrapper.setProps({
anchor: 'top',
});
assert.strictEqual(wrapper.find(Slide).props().direction, 'down');
wrapper.setProps({
anchor: 'bottom',
});
assert.strictEqual(wrapper.find(Slide).props().direction, 'up');
});
});
});
| src/Drawer/Drawer.spec.js | 0 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.0001769095251802355,
0.00017436197958886623,
0.00016988356946967542,
0.00017478226800449193,
0.000002011762035181164
] |
{
"id": 5,
"code_window": [
" return (\n",
" <ComponentProp\n",
" className={classNames({\n",
" [classes.typeContainer]: container,\n",
" [classes.typeItem]: item,\n",
" [classes[`gutter-xs-${xsGutter}`]]: container && xsGutter !== false,\n",
" [classes[`direction-xs-${xsDirection}`]]: xsDirection !== Layout.defaultProps.xsDirection,\n",
" [classes[`wrap-xs-${xsWrap}`]]: xsWrap !== Layout.defaultProps.xsWrap,\n",
" [classes[`align-xs-${xsAlign}`]]: xsAlign !== Layout.defaultProps.xsAlign,\n",
" [classes[`justify-xs-${xsJustify}`]]: xsJustify !== Layout.defaultProps.xsJustify,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" [classes[`gutter-xs-${xsGutter}`]]: container && xsGutter !== 0,\n"
],
"file_path": "src/Layout/Layout.js",
"type": "replace",
"edit_start_line_idx": 148
} | // @flow weak
/**
* A layout component using the following libs as inspiration.
*
* For the implementation:
* - http://v4-alpha.getbootstrap.com/layout/flexbox-grid/
* - https://github.com/kristoferjoseph/flexboxgrid/blob/master/src/css/flexboxgrid.css
* - https://github.com/roylee0704/react-flexbox-grid
* - https://material.angularjs.org/latest/layout/introduction
*
* Follow this flexbox Guide to better understand the underlying model:
* - https://css-tricks.com/snippets/css/a-guide-to-flexbox/
*/
import React, { PropTypes } from 'react';
import { createStyleSheet } from 'jss-theme-reactor';
import classNames from 'classnames';
const GUTTERS = [8, 16, 24, 40];
const GRID_SIZES = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
function generateGrid(globalStyles, theme, breakpoint) {
// For the auto layouting
const styles = {
[`grid-${breakpoint}`]: {
flexBasis: 0,
flexGrow: 1,
maxWidth: '100%',
},
};
GRID_SIZES.forEach((size) => {
// Only keep 6 significant numbers.
const width = `${Math.round((size / 12) * (10 ** 6)) / (10 ** 4)}%`;
/* eslint-disable max-len */
// Close to the bootstrap implementation: https://github.com/twbs/bootstrap/blob/b0508a975d711d6b24c01f57dd5445c22699fac4/scss/mixins/_grid.scss#L69
/* eslint-enable max-len */
styles[`grid-${breakpoint}-${size}`] = {
flexBasis: width,
maxWidth: width,
};
});
globalStyles[theme.breakpoints.up(breakpoint)] = styles;
}
function generateGutter(theme, breakpoint) {
const styles = {};
GUTTERS.forEach((gutter) => {
styles[`gutter-${breakpoint}-${gutter}`] = {
margin: -gutter / 2,
'& > $typeItem': {
padding: gutter / 2,
},
};
});
return styles;
}
export const styleSheet = createStyleSheet('Layout', (theme) => {
// Default CSS values
// flex: '0 1 auto',
// flexDirection: 'row',
// alignItems: 'flex-start',
// flexWrap: 'nowrap',
// justifyContent: 'flex-start',
return {
typeContainer: {
display: 'flex',
flexWrap: 'wrap',
},
typeItem: {
flex: '0 0 auto',
},
'direction-xs-column': {
flexDirection: 'column',
},
'direction-xs-column-reverse': {
flexDirection: 'column-reverse',
},
'direction-xs-row-reverse': {
flexDirection: 'row-reverse',
},
'wrap-xs-nowrap': {
flexWrap: 'nowrap',
},
'align-xs-center': {
alignItems: 'center',
},
'align-xs-flex-end': {
alignItems: 'flex-end',
},
'align-xs-stretch': {
alignItems: 'stretch',
},
'justify-xs-center': {
justifyContent: 'center',
},
'justify-xs-flex-end': {
justifyContent: 'flex-end',
},
'justify-xs-space-between': {
justifyContent: 'space-between',
},
'justify-xs-space-around': {
justifyContent: 'space-around',
},
...generateGutter(theme, 'xs'),
...theme.breakpoints.keys.reduce((styles, key) => {
// Use side effect for performance.
generateGrid(styles, theme, key);
return styles;
}, {}),
};
});
function Layout(props, context) {
const {
children,
className,
component: ComponentProp,
container,
item,
xsAlign,
xsDirection,
xs,
sm,
md,
lg,
xl,
xsGutter,
xsJustify,
xsWrap,
...other
} = props;
const classes = context.styleManager.render(styleSheet);
return (
<ComponentProp
className={classNames({
[classes.typeContainer]: container,
[classes.typeItem]: item,
[classes[`gutter-xs-${xsGutter}`]]: container && xsGutter !== false,
[classes[`direction-xs-${xsDirection}`]]: xsDirection !== Layout.defaultProps.xsDirection,
[classes[`wrap-xs-${xsWrap}`]]: xsWrap !== Layout.defaultProps.xsWrap,
[classes[`align-xs-${xsAlign}`]]: xsAlign !== Layout.defaultProps.xsAlign,
[classes[`justify-xs-${xsJustify}`]]: xsJustify !== Layout.defaultProps.xsJustify,
[classes['grid-xs']]: xs === true,
[classes[`grid-xs-${xs}`]]: xs && xs !== true,
[classes['grid-sm']]: sm === true,
[classes[`grid-sm-${sm}`]]: sm && sm !== true,
[classes['grid-md']]: md === true,
[classes[`grid-md-${md}`]]: md && md !== true,
[classes['grid-lg']]: lg === true,
[classes[`grid-lg-${lg}`]]: lg && lg !== true,
[classes['grid-xl']]: xl === true,
[classes[`grid-xl-${xl}`]]: xl && xl !== true,
}, className)}
{...other}
>
{children}
</ComponentProp>
);
}
const gridPropType = PropTypes.oneOfType([
PropTypes.bool,
PropTypes.oneOf(GRID_SIZES),
]);
Layout.propTypes = {
/**
* The content of the component.
*/
children: PropTypes.node,
/**
* The CSS class name of the root element.
*/
className: PropTypes.string,
/**
* The element or component used for the root node.
*/
component: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func,
]),
/**
* It true, the component will have the flex *container* behavior.
* You should be wrapping *items* with a *container*.
*/
container: PropTypes.bool,
/**
* It true, the component will have the flex *item* behavior.
* You should be wrapping *items* with a *container*.
*/
item: PropTypes.bool,
/**
* Defines the number of grids the component is going to use.
* It's applied for all the screen sizes with the lowest priority.
*/
xs: gridPropType,
/**
* Defines the number of grids the component is going to use.
* It's applied for the `sm` breakpoint and wider screens if not overridden.
*/
sm: gridPropType, // eslint-disable-line react/sort-prop-types
/**
* Defines the number of grids the component is going to use.
* It's applied for the `md` breakpoint and wider screens if not overridden.
*/
md: gridPropType, // eslint-disable-line react/sort-prop-types
/**
* Defines the number of grids the component is going to use.
* It's applied for the `lg` breakpoint and wider screens if not overridden.
*/
lg: gridPropType, // eslint-disable-line react/sort-prop-types
/**
* Defines the number of grids the component is going to use.
* It's applied for the `xl` breakpoint and wider screens.
*/
xl: gridPropType, // eslint-disable-line react/sort-prop-types
/**
* Defines the `align-items` style property.
* It's applied for all the screen sizes.
*/
xsAlign: PropTypes.oneOf([
'flex-start',
'center',
'flex-end',
'stretch',
]),
/**
* Defines the `flex-direction` style property.
* It's applied for all the screen sizes.
*/
xsDirection: PropTypes.oneOf([
'row',
'row-reverse',
'column',
'column-reverse',
]),
/**
* Defines the space between the type `item` component.
* It can only be used on a type `container` component.
*/
xsGutter: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.oneOf(GUTTERS),
]),
/**
* Defines the `justify-content` style property.
* It's applied for all the screen sizes.
*/
xsJustify: PropTypes.oneOf([
'flex-start',
'center',
'flex-end',
'space-between',
'space-around',
]),
/**
* Defines the `flex-wrap` style property.
* It's applied for all the screen sizes.
*/
xsWrap: PropTypes.oneOf([
'nowrap',
'wrap',
'wrap-reverse',
]),
};
Layout.defaultProps = {
component: 'div',
container: false,
item: false,
xsAlign: 'flex-start',
xsDirection: 'row',
xsGutter: 16,
xsJustify: 'flex-start',
xsWrap: 'wrap',
};
Layout.contextTypes = {
styleManager: PropTypes.object.isRequired,
};
export default Layout;
| src/Layout/Layout.js | 1 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.9956613183021545,
0.036622487008571625,
0.00016298719856422395,
0.00019507078104652464,
0.17854224145412445
] |
{
"id": 5,
"code_window": [
" return (\n",
" <ComponentProp\n",
" className={classNames({\n",
" [classes.typeContainer]: container,\n",
" [classes.typeItem]: item,\n",
" [classes[`gutter-xs-${xsGutter}`]]: container && xsGutter !== false,\n",
" [classes[`direction-xs-${xsDirection}`]]: xsDirection !== Layout.defaultProps.xsDirection,\n",
" [classes[`wrap-xs-${xsWrap}`]]: xsWrap !== Layout.defaultProps.xsWrap,\n",
" [classes[`align-xs-${xsAlign}`]]: xsAlign !== Layout.defaultProps.xsAlign,\n",
" [classes[`justify-xs-${xsJustify}`]]: xsJustify !== Layout.defaultProps.xsJustify,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" [classes[`gutter-xs-${xsGutter}`]]: container && xsGutter !== 0,\n"
],
"file_path": "src/Layout/Layout.js",
"type": "replace",
"edit_start_line_idx": 148
} | // @flow weak
/* eslint-env mocha */
import React from 'react';
import { assert } from 'chai';
import { createShallowWithContext } from 'test/utils';
import CardHeader, { styleSheet } from './CardHeader';
describe('<CardHeader />', () => {
let shallow;
let classes;
before(() => {
shallow = createShallowWithContext();
classes = shallow.context.styleManager.render(styleSheet);
});
it('should render CardContent', () => {
const wrapper = shallow(
<CardHeader />,
);
assert.strictEqual(wrapper.is('CardContent'), true, 'should be CardContent');
});
it('should have the cardHeader class', () => {
const wrapper = shallow(
<CardHeader />,
);
assert.strictEqual(wrapper.hasClass(classes.cardHeader), true);
});
describe('without an avatar', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(
<CardHeader
title="Title"
subhead="Subhead"
/>,
);
});
it('should render the title as headline text', () => {
const title = wrapper.childAt(0);
assert.strictEqual(title.is('Text'), true);
assert.strictEqual(title.prop('type'), 'headline');
});
it('should render the subead as body1 secondary text', () => {
const subhead = wrapper.childAt(1);
assert.strictEqual(subhead.is('Text'), true);
assert.strictEqual(subhead.prop('type'), 'body1');
assert.strictEqual(subhead.prop('secondary'), true);
});
});
describe('with an avatar', () => {
let wrapper;
let avatar;
beforeEach(() => {
avatar = <span />;
wrapper = shallow(
<CardHeader
avatar={avatar}
title="Title"
subhead="Subhead"
/>,
);
});
it('should render the avatar inside the first child', () => {
const container = wrapper.childAt(0);
assert.strictEqual(container.is('div'), true);
assert.strictEqual(container.hasClass(classes.avatar), true);
assert.strictEqual(container.childAt(0).equals(avatar), true);
});
it('should render the title as body2 text inside the second child', () => {
const container = wrapper.childAt(1);
assert.strictEqual(container.hasClass(classes.content), true, 'should have the content class');
const title = container.childAt(0);
assert.strictEqual(title.is('Text'), true);
assert.strictEqual(title.prop('type'), 'body2');
});
it('should render the subead as body2 secondary text inside the second child', () => {
const container = wrapper.childAt(1);
assert.strictEqual(container.hasClass(classes.content), true, 'should have the content class');
const subhead = container.childAt(1);
assert.strictEqual(subhead.is('Text'), true);
assert.strictEqual(subhead.prop('type'), 'body2');
assert.strictEqual(subhead.prop('secondary'), true);
});
});
});
| src/Card/CardHeader.spec.js | 0 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.0022893669083714485,
0.00041551777394488454,
0.00016599809168837965,
0.00017508634482510388,
0.0006283679977059364
] |
{
"id": 5,
"code_window": [
" return (\n",
" <ComponentProp\n",
" className={classNames({\n",
" [classes.typeContainer]: container,\n",
" [classes.typeItem]: item,\n",
" [classes[`gutter-xs-${xsGutter}`]]: container && xsGutter !== false,\n",
" [classes[`direction-xs-${xsDirection}`]]: xsDirection !== Layout.defaultProps.xsDirection,\n",
" [classes[`wrap-xs-${xsWrap}`]]: xsWrap !== Layout.defaultProps.xsWrap,\n",
" [classes[`align-xs-${xsAlign}`]]: xsAlign !== Layout.defaultProps.xsAlign,\n",
" [classes[`justify-xs-${xsJustify}`]]: xsJustify !== Layout.defaultProps.xsJustify,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" [classes[`gutter-xs-${xsGutter}`]]: container && xsGutter !== 0,\n"
],
"file_path": "src/Layout/Layout.js",
"type": "replace",
"edit_start_line_idx": 148
} | // @flow weak
import shadows from './shadows';
import transitions from './transitions';
import createTypography from './typography';
import createBreakpoints from './breakpoints';
import createPalette from './palette';
import zIndex from './zIndex';
import createMixins from './mixins';
export function createMuiTheme(config = {}) {
const {
palette = createPalette(),
breakpoints = createBreakpoints(),
mixins = createMixins(breakpoints),
typography = createTypography(palette),
...more
} = config;
const theme = {
dir: 'ltr',
palette,
typography,
shadows,
transitions,
mixins,
breakpoints,
zIndex,
...more,
};
return theme;
}
export default createMuiTheme;
| src/styles/theme.js | 0 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.00017674564151093364,
0.00017418028437532485,
0.00017136373207904398,
0.00017430586740374565,
0.0000019415872429817682
] |
{
"id": 5,
"code_window": [
" return (\n",
" <ComponentProp\n",
" className={classNames({\n",
" [classes.typeContainer]: container,\n",
" [classes.typeItem]: item,\n",
" [classes[`gutter-xs-${xsGutter}`]]: container && xsGutter !== false,\n",
" [classes[`direction-xs-${xsDirection}`]]: xsDirection !== Layout.defaultProps.xsDirection,\n",
" [classes[`wrap-xs-${xsWrap}`]]: xsWrap !== Layout.defaultProps.xsWrap,\n",
" [classes[`align-xs-${xsAlign}`]]: xsAlign !== Layout.defaultProps.xsAlign,\n",
" [classes[`justify-xs-${xsJustify}`]]: xsJustify !== Layout.defaultProps.xsJustify,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" [classes[`gutter-xs-${xsGutter}`]]: container && xsGutter !== 0,\n"
],
"file_path": "src/Layout/Layout.js",
"type": "replace",
"edit_start_line_idx": 148
} | IconButton
==========
@see https://material.google.com/components/buttons.html
```js
import IconButton from 'material-ui/IconButton';
const Component = () => <IconButton>delete</IconButton>;
```
Props
-----
| Name | Type | Default | Description |
|:-----|:-----|:--------|:------------|
| accent | bool | false | If true, will use the theme's accent color. |
| children | node | | The icon element. If a string is passed, it will be used as a material icon font ligature. |
| className | string | | The CSS class name of the root element. |
| contrast | bool | false | If true, will use the theme's contrast color. |
| disabled | bool | false | If `true`, the button will be disabled. |
| ripple | bool | true | If false, the ripple effect will be disabled. |
Any other properties supplied will be spread to the root element.
| docs/api/IconButton/IconButton.md | 0 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.00017206434858962893,
0.00016664281429257244,
0.00016061212227214128,
0.0001672519720159471,
0.000004695151801570319
] |
{
"id": 6,
"code_window": [
" </ComponentProp>\n",
" );\n",
"}\n",
"\n",
"const gridPropType = PropTypes.oneOfType([\n",
" PropTypes.bool,\n",
" PropTypes.oneOf(GRID_SIZES),\n",
"]);\n",
"\n",
"Layout.propTypes = {\n",
" /**\n",
" * The content of the component.\n",
" */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const gridPropType = PropTypes.oneOf(GRID_SIZES);\n"
],
"file_path": "src/Layout/Layout.js",
"type": "replace",
"edit_start_line_idx": 171
} | // @flow weak
/**
* A layout component using the following libs as inspiration.
*
* For the implementation:
* - http://v4-alpha.getbootstrap.com/layout/flexbox-grid/
* - https://github.com/kristoferjoseph/flexboxgrid/blob/master/src/css/flexboxgrid.css
* - https://github.com/roylee0704/react-flexbox-grid
* - https://material.angularjs.org/latest/layout/introduction
*
* Follow this flexbox Guide to better understand the underlying model:
* - https://css-tricks.com/snippets/css/a-guide-to-flexbox/
*/
import React, { PropTypes } from 'react';
import { createStyleSheet } from 'jss-theme-reactor';
import classNames from 'classnames';
const GUTTERS = [8, 16, 24, 40];
const GRID_SIZES = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
function generateGrid(globalStyles, theme, breakpoint) {
// For the auto layouting
const styles = {
[`grid-${breakpoint}`]: {
flexBasis: 0,
flexGrow: 1,
maxWidth: '100%',
},
};
GRID_SIZES.forEach((size) => {
// Only keep 6 significant numbers.
const width = `${Math.round((size / 12) * (10 ** 6)) / (10 ** 4)}%`;
/* eslint-disable max-len */
// Close to the bootstrap implementation: https://github.com/twbs/bootstrap/blob/b0508a975d711d6b24c01f57dd5445c22699fac4/scss/mixins/_grid.scss#L69
/* eslint-enable max-len */
styles[`grid-${breakpoint}-${size}`] = {
flexBasis: width,
maxWidth: width,
};
});
globalStyles[theme.breakpoints.up(breakpoint)] = styles;
}
function generateGutter(theme, breakpoint) {
const styles = {};
GUTTERS.forEach((gutter) => {
styles[`gutter-${breakpoint}-${gutter}`] = {
margin: -gutter / 2,
'& > $typeItem': {
padding: gutter / 2,
},
};
});
return styles;
}
export const styleSheet = createStyleSheet('Layout', (theme) => {
// Default CSS values
// flex: '0 1 auto',
// flexDirection: 'row',
// alignItems: 'flex-start',
// flexWrap: 'nowrap',
// justifyContent: 'flex-start',
return {
typeContainer: {
display: 'flex',
flexWrap: 'wrap',
},
typeItem: {
flex: '0 0 auto',
},
'direction-xs-column': {
flexDirection: 'column',
},
'direction-xs-column-reverse': {
flexDirection: 'column-reverse',
},
'direction-xs-row-reverse': {
flexDirection: 'row-reverse',
},
'wrap-xs-nowrap': {
flexWrap: 'nowrap',
},
'align-xs-center': {
alignItems: 'center',
},
'align-xs-flex-end': {
alignItems: 'flex-end',
},
'align-xs-stretch': {
alignItems: 'stretch',
},
'justify-xs-center': {
justifyContent: 'center',
},
'justify-xs-flex-end': {
justifyContent: 'flex-end',
},
'justify-xs-space-between': {
justifyContent: 'space-between',
},
'justify-xs-space-around': {
justifyContent: 'space-around',
},
...generateGutter(theme, 'xs'),
...theme.breakpoints.keys.reduce((styles, key) => {
// Use side effect for performance.
generateGrid(styles, theme, key);
return styles;
}, {}),
};
});
function Layout(props, context) {
const {
children,
className,
component: ComponentProp,
container,
item,
xsAlign,
xsDirection,
xs,
sm,
md,
lg,
xl,
xsGutter,
xsJustify,
xsWrap,
...other
} = props;
const classes = context.styleManager.render(styleSheet);
return (
<ComponentProp
className={classNames({
[classes.typeContainer]: container,
[classes.typeItem]: item,
[classes[`gutter-xs-${xsGutter}`]]: container && xsGutter !== false,
[classes[`direction-xs-${xsDirection}`]]: xsDirection !== Layout.defaultProps.xsDirection,
[classes[`wrap-xs-${xsWrap}`]]: xsWrap !== Layout.defaultProps.xsWrap,
[classes[`align-xs-${xsAlign}`]]: xsAlign !== Layout.defaultProps.xsAlign,
[classes[`justify-xs-${xsJustify}`]]: xsJustify !== Layout.defaultProps.xsJustify,
[classes['grid-xs']]: xs === true,
[classes[`grid-xs-${xs}`]]: xs && xs !== true,
[classes['grid-sm']]: sm === true,
[classes[`grid-sm-${sm}`]]: sm && sm !== true,
[classes['grid-md']]: md === true,
[classes[`grid-md-${md}`]]: md && md !== true,
[classes['grid-lg']]: lg === true,
[classes[`grid-lg-${lg}`]]: lg && lg !== true,
[classes['grid-xl']]: xl === true,
[classes[`grid-xl-${xl}`]]: xl && xl !== true,
}, className)}
{...other}
>
{children}
</ComponentProp>
);
}
const gridPropType = PropTypes.oneOfType([
PropTypes.bool,
PropTypes.oneOf(GRID_SIZES),
]);
Layout.propTypes = {
/**
* The content of the component.
*/
children: PropTypes.node,
/**
* The CSS class name of the root element.
*/
className: PropTypes.string,
/**
* The element or component used for the root node.
*/
component: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func,
]),
/**
* It true, the component will have the flex *container* behavior.
* You should be wrapping *items* with a *container*.
*/
container: PropTypes.bool,
/**
* It true, the component will have the flex *item* behavior.
* You should be wrapping *items* with a *container*.
*/
item: PropTypes.bool,
/**
* Defines the number of grids the component is going to use.
* It's applied for all the screen sizes with the lowest priority.
*/
xs: gridPropType,
/**
* Defines the number of grids the component is going to use.
* It's applied for the `sm` breakpoint and wider screens if not overridden.
*/
sm: gridPropType, // eslint-disable-line react/sort-prop-types
/**
* Defines the number of grids the component is going to use.
* It's applied for the `md` breakpoint and wider screens if not overridden.
*/
md: gridPropType, // eslint-disable-line react/sort-prop-types
/**
* Defines the number of grids the component is going to use.
* It's applied for the `lg` breakpoint and wider screens if not overridden.
*/
lg: gridPropType, // eslint-disable-line react/sort-prop-types
/**
* Defines the number of grids the component is going to use.
* It's applied for the `xl` breakpoint and wider screens.
*/
xl: gridPropType, // eslint-disable-line react/sort-prop-types
/**
* Defines the `align-items` style property.
* It's applied for all the screen sizes.
*/
xsAlign: PropTypes.oneOf([
'flex-start',
'center',
'flex-end',
'stretch',
]),
/**
* Defines the `flex-direction` style property.
* It's applied for all the screen sizes.
*/
xsDirection: PropTypes.oneOf([
'row',
'row-reverse',
'column',
'column-reverse',
]),
/**
* Defines the space between the type `item` component.
* It can only be used on a type `container` component.
*/
xsGutter: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.oneOf(GUTTERS),
]),
/**
* Defines the `justify-content` style property.
* It's applied for all the screen sizes.
*/
xsJustify: PropTypes.oneOf([
'flex-start',
'center',
'flex-end',
'space-between',
'space-around',
]),
/**
* Defines the `flex-wrap` style property.
* It's applied for all the screen sizes.
*/
xsWrap: PropTypes.oneOf([
'nowrap',
'wrap',
'wrap-reverse',
]),
};
Layout.defaultProps = {
component: 'div',
container: false,
item: false,
xsAlign: 'flex-start',
xsDirection: 'row',
xsGutter: 16,
xsJustify: 'flex-start',
xsWrap: 'wrap',
};
Layout.contextTypes = {
styleManager: PropTypes.object.isRequired,
};
export default Layout;
| src/Layout/Layout.js | 1 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.9982324242591858,
0.13247232139110565,
0.00016749727365095168,
0.00027650222182273865,
0.33655479550361633
] |
{
"id": 6,
"code_window": [
" </ComponentProp>\n",
" );\n",
"}\n",
"\n",
"const gridPropType = PropTypes.oneOfType([\n",
" PropTypes.bool,\n",
" PropTypes.oneOf(GRID_SIZES),\n",
"]);\n",
"\n",
"Layout.propTypes = {\n",
" /**\n",
" * The content of the component.\n",
" */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const gridPropType = PropTypes.oneOf(GRID_SIZES);\n"
],
"file_path": "src/Layout/Layout.js",
"type": "replace",
"edit_start_line_idx": 171
} | // @flow weak
import React from 'react';
import LinearProgress from 'material-ui/Progress/LinearProgress';
export default function DeterminateLinearProgress() {
return (
<LinearProgress
mode="buffer"
value={60}
valueBuffer={80}
style={{
width: 150,
}}
/>
);
}
| test/regressions/site/src/tests/LinearProgress/BufferLinearProgress.js | 0 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.00017478431982453912,
0.00017391034634783864,
0.00017303637287113816,
0.00017391034634783864,
8.739734767004848e-7
] |
{
"id": 6,
"code_window": [
" </ComponentProp>\n",
" );\n",
"}\n",
"\n",
"const gridPropType = PropTypes.oneOfType([\n",
" PropTypes.bool,\n",
" PropTypes.oneOf(GRID_SIZES),\n",
"]);\n",
"\n",
"Layout.propTypes = {\n",
" /**\n",
" * The content of the component.\n",
" */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const gridPropType = PropTypes.oneOf(GRID_SIZES);\n"
],
"file_path": "src/Layout/Layout.js",
"type": "replace",
"edit_start_line_idx": 171
} | // @flow weak
import React from 'react';
import Text from 'material-ui/Text';
const style = {
background: '#fff',
};
export default function TextStypes() {
return (
<div style={style}>
<Text type="display4" component="h1" gutterBottom>
Display 4
</Text>
<Text type="display3" component="h2" gutterBottom>
Display 3
</Text>
<Text type="display2" component="h3" gutterBottom>
Display 2
</Text>
<Text type="display1" component="h4" gutterBottom>
Display 1
</Text>
<Text type="headline" component="h5" gutterBottom>
Headline
</Text>
<Text type="title" component="h6" gutterBottom>
Title
</Text>
<Text type="subheading" gutterBottom>
Subheading
</Text>
<Text type="body2" gutterBottom>
Body 2
</Text>
<Text type="body1" gutterBottom>
Body 1
</Text>
<Text type="caption" gutterBottom align="center">
Caption
</Text>
</div>
);
}
| test/regressions/site/src/tests/Text/TextTypes.js | 0 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.00017451138410251588,
0.00017306176596321166,
0.00017110526096075773,
0.0001737660204526037,
0.000001306786998611642
] |
{
"id": 6,
"code_window": [
" </ComponentProp>\n",
" );\n",
"}\n",
"\n",
"const gridPropType = PropTypes.oneOfType([\n",
" PropTypes.bool,\n",
" PropTypes.oneOf(GRID_SIZES),\n",
"]);\n",
"\n",
"Layout.propTypes = {\n",
" /**\n",
" * The content of the component.\n",
" */\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const gridPropType = PropTypes.oneOf(GRID_SIZES);\n"
],
"file_path": "src/Layout/Layout.js",
"type": "replace",
"edit_start_line_idx": 171
} | module.exports = {
'Docs Home': function DocsHome(browser) {
browser
.maximizeWindow()
.url(browser.launch_url)
.waitForElementVisible('[data-reactroot]', 6000)
.assert.elementPresent('img[class^=home__logo]')
.end();
},
};
| test/e2e/docs/home.js | 0 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.00017402417142875493,
0.00017173474770970643,
0.00016944532399065793,
0.00017173474770970643,
0.0000022894237190485
] |
{
"id": 7,
"code_window": [
" * Defines the space between the type `item` component.\n",
" * It can only be used on a type `container` component.\n",
" */\n",
" xsGutter: PropTypes.oneOfType([\n",
" PropTypes.bool,\n",
" PropTypes.oneOf(GUTTERS),\n",
" ]),\n",
" /**\n",
" * Defines the `justify-content` style property.\n",
" * It's applied for all the screen sizes.\n",
" */\n",
" xsJustify: PropTypes.oneOf([\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" xsGutter: PropTypes.oneOf(GUTTERS),\n"
],
"file_path": "src/Layout/Layout.js",
"type": "replace",
"edit_start_line_idx": 251
} | // @flow weak
/**
* A layout component using the following libs as inspiration.
*
* For the implementation:
* - http://v4-alpha.getbootstrap.com/layout/flexbox-grid/
* - https://github.com/kristoferjoseph/flexboxgrid/blob/master/src/css/flexboxgrid.css
* - https://github.com/roylee0704/react-flexbox-grid
* - https://material.angularjs.org/latest/layout/introduction
*
* Follow this flexbox Guide to better understand the underlying model:
* - https://css-tricks.com/snippets/css/a-guide-to-flexbox/
*/
import React, { PropTypes } from 'react';
import { createStyleSheet } from 'jss-theme-reactor';
import classNames from 'classnames';
const GUTTERS = [8, 16, 24, 40];
const GRID_SIZES = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
function generateGrid(globalStyles, theme, breakpoint) {
// For the auto layouting
const styles = {
[`grid-${breakpoint}`]: {
flexBasis: 0,
flexGrow: 1,
maxWidth: '100%',
},
};
GRID_SIZES.forEach((size) => {
// Only keep 6 significant numbers.
const width = `${Math.round((size / 12) * (10 ** 6)) / (10 ** 4)}%`;
/* eslint-disable max-len */
// Close to the bootstrap implementation: https://github.com/twbs/bootstrap/blob/b0508a975d711d6b24c01f57dd5445c22699fac4/scss/mixins/_grid.scss#L69
/* eslint-enable max-len */
styles[`grid-${breakpoint}-${size}`] = {
flexBasis: width,
maxWidth: width,
};
});
globalStyles[theme.breakpoints.up(breakpoint)] = styles;
}
function generateGutter(theme, breakpoint) {
const styles = {};
GUTTERS.forEach((gutter) => {
styles[`gutter-${breakpoint}-${gutter}`] = {
margin: -gutter / 2,
'& > $typeItem': {
padding: gutter / 2,
},
};
});
return styles;
}
export const styleSheet = createStyleSheet('Layout', (theme) => {
// Default CSS values
// flex: '0 1 auto',
// flexDirection: 'row',
// alignItems: 'flex-start',
// flexWrap: 'nowrap',
// justifyContent: 'flex-start',
return {
typeContainer: {
display: 'flex',
flexWrap: 'wrap',
},
typeItem: {
flex: '0 0 auto',
},
'direction-xs-column': {
flexDirection: 'column',
},
'direction-xs-column-reverse': {
flexDirection: 'column-reverse',
},
'direction-xs-row-reverse': {
flexDirection: 'row-reverse',
},
'wrap-xs-nowrap': {
flexWrap: 'nowrap',
},
'align-xs-center': {
alignItems: 'center',
},
'align-xs-flex-end': {
alignItems: 'flex-end',
},
'align-xs-stretch': {
alignItems: 'stretch',
},
'justify-xs-center': {
justifyContent: 'center',
},
'justify-xs-flex-end': {
justifyContent: 'flex-end',
},
'justify-xs-space-between': {
justifyContent: 'space-between',
},
'justify-xs-space-around': {
justifyContent: 'space-around',
},
...generateGutter(theme, 'xs'),
...theme.breakpoints.keys.reduce((styles, key) => {
// Use side effect for performance.
generateGrid(styles, theme, key);
return styles;
}, {}),
};
});
function Layout(props, context) {
const {
children,
className,
component: ComponentProp,
container,
item,
xsAlign,
xsDirection,
xs,
sm,
md,
lg,
xl,
xsGutter,
xsJustify,
xsWrap,
...other
} = props;
const classes = context.styleManager.render(styleSheet);
return (
<ComponentProp
className={classNames({
[classes.typeContainer]: container,
[classes.typeItem]: item,
[classes[`gutter-xs-${xsGutter}`]]: container && xsGutter !== false,
[classes[`direction-xs-${xsDirection}`]]: xsDirection !== Layout.defaultProps.xsDirection,
[classes[`wrap-xs-${xsWrap}`]]: xsWrap !== Layout.defaultProps.xsWrap,
[classes[`align-xs-${xsAlign}`]]: xsAlign !== Layout.defaultProps.xsAlign,
[classes[`justify-xs-${xsJustify}`]]: xsJustify !== Layout.defaultProps.xsJustify,
[classes['grid-xs']]: xs === true,
[classes[`grid-xs-${xs}`]]: xs && xs !== true,
[classes['grid-sm']]: sm === true,
[classes[`grid-sm-${sm}`]]: sm && sm !== true,
[classes['grid-md']]: md === true,
[classes[`grid-md-${md}`]]: md && md !== true,
[classes['grid-lg']]: lg === true,
[classes[`grid-lg-${lg}`]]: lg && lg !== true,
[classes['grid-xl']]: xl === true,
[classes[`grid-xl-${xl}`]]: xl && xl !== true,
}, className)}
{...other}
>
{children}
</ComponentProp>
);
}
const gridPropType = PropTypes.oneOfType([
PropTypes.bool,
PropTypes.oneOf(GRID_SIZES),
]);
Layout.propTypes = {
/**
* The content of the component.
*/
children: PropTypes.node,
/**
* The CSS class name of the root element.
*/
className: PropTypes.string,
/**
* The element or component used for the root node.
*/
component: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func,
]),
/**
* It true, the component will have the flex *container* behavior.
* You should be wrapping *items* with a *container*.
*/
container: PropTypes.bool,
/**
* It true, the component will have the flex *item* behavior.
* You should be wrapping *items* with a *container*.
*/
item: PropTypes.bool,
/**
* Defines the number of grids the component is going to use.
* It's applied for all the screen sizes with the lowest priority.
*/
xs: gridPropType,
/**
* Defines the number of grids the component is going to use.
* It's applied for the `sm` breakpoint and wider screens if not overridden.
*/
sm: gridPropType, // eslint-disable-line react/sort-prop-types
/**
* Defines the number of grids the component is going to use.
* It's applied for the `md` breakpoint and wider screens if not overridden.
*/
md: gridPropType, // eslint-disable-line react/sort-prop-types
/**
* Defines the number of grids the component is going to use.
* It's applied for the `lg` breakpoint and wider screens if not overridden.
*/
lg: gridPropType, // eslint-disable-line react/sort-prop-types
/**
* Defines the number of grids the component is going to use.
* It's applied for the `xl` breakpoint and wider screens.
*/
xl: gridPropType, // eslint-disable-line react/sort-prop-types
/**
* Defines the `align-items` style property.
* It's applied for all the screen sizes.
*/
xsAlign: PropTypes.oneOf([
'flex-start',
'center',
'flex-end',
'stretch',
]),
/**
* Defines the `flex-direction` style property.
* It's applied for all the screen sizes.
*/
xsDirection: PropTypes.oneOf([
'row',
'row-reverse',
'column',
'column-reverse',
]),
/**
* Defines the space between the type `item` component.
* It can only be used on a type `container` component.
*/
xsGutter: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.oneOf(GUTTERS),
]),
/**
* Defines the `justify-content` style property.
* It's applied for all the screen sizes.
*/
xsJustify: PropTypes.oneOf([
'flex-start',
'center',
'flex-end',
'space-between',
'space-around',
]),
/**
* Defines the `flex-wrap` style property.
* It's applied for all the screen sizes.
*/
xsWrap: PropTypes.oneOf([
'nowrap',
'wrap',
'wrap-reverse',
]),
};
Layout.defaultProps = {
component: 'div',
container: false,
item: false,
xsAlign: 'flex-start',
xsDirection: 'row',
xsGutter: 16,
xsJustify: 'flex-start',
xsWrap: 'wrap',
};
Layout.contextTypes = {
styleManager: PropTypes.object.isRequired,
};
export default Layout;
| src/Layout/Layout.js | 1 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.9815623164176941,
0.061059605330228806,
0.00016158954531420022,
0.0003443431342020631,
0.18867957592010498
] |
{
"id": 7,
"code_window": [
" * Defines the space between the type `item` component.\n",
" * It can only be used on a type `container` component.\n",
" */\n",
" xsGutter: PropTypes.oneOfType([\n",
" PropTypes.bool,\n",
" PropTypes.oneOf(GUTTERS),\n",
" ]),\n",
" /**\n",
" * Defines the `justify-content` style property.\n",
" * It's applied for all the screen sizes.\n",
" */\n",
" xsJustify: PropTypes.oneOf([\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" xsGutter: PropTypes.oneOf(GUTTERS),\n"
],
"file_path": "src/Layout/Layout.js",
"type": "replace",
"edit_start_line_idx": 251
} | // @flow weak
import React, { PropTypes } from 'react';
import { createStyleSheet } from 'jss-theme-reactor';
import {
Card,
CardMedia,
CardContent,
CardActions,
} from 'material-ui/Card';
import Button from 'material-ui/Button';
import Text from 'material-ui/Text';
import reptileImage from 'docs/site/assets/images/[email protected]';
const styleSheet = createStyleSheet('SimpleMediaCard', () => ({
card: { maxWidth: 345 },
}));
export default function SimpleMediaCard(props, context) {
const classes = context.styleManager.render(styleSheet);
return (
<div>
<Card className={classes.card}>
<CardMedia>
<img src={reptileImage} alt="Contemplative Reptile" />
</CardMedia>
<CardContent>
<Text type="headline" component="h2">Lizard</Text>
<Text component="p">
Lizards are a widespread group of squamate reptiles, with over
6,000 species, ranging across all continents except Antarctica
</Text>
</CardContent>
<CardActions>
<Button compact primary>Share</Button>
<Button compact primary>Learn More</Button>
</CardActions>
</Card>
</div>
);
}
SimpleMediaCard.contextTypes = {
styleManager: PropTypes.object.isRequired,
};
| docs/site/src/demos/cards/SimpleMediaCard.js | 0 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.0001698111736914143,
0.00016754331591073424,
0.0001647724857321009,
0.00016752122610341758,
0.000001659729832681478
] |
{
"id": 7,
"code_window": [
" * Defines the space between the type `item` component.\n",
" * It can only be used on a type `container` component.\n",
" */\n",
" xsGutter: PropTypes.oneOfType([\n",
" PropTypes.bool,\n",
" PropTypes.oneOf(GUTTERS),\n",
" ]),\n",
" /**\n",
" * Defines the `justify-content` style property.\n",
" * It's applied for all the screen sizes.\n",
" */\n",
" xsJustify: PropTypes.oneOf([\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" xsGutter: PropTypes.oneOf(GUTTERS),\n"
],
"file_path": "src/Layout/Layout.js",
"type": "replace",
"edit_start_line_idx": 251
} | ## Roadmap
The roadmap is a living document, and it is likely that priorities will change, but the list below should give some indication of our plans for the next major release, and for the future.
### 0.15.0
#### Breaking Changes
- Remove deprecated usage of JSON to generate children across the components.
- [[#3108](https://github.com/callemall/material-ui/pull/3108)] Remove deprecated components, methods & props.
- [[#2957](https://github.com/callemall/material-ui/issues/2957)] Standardize callback signatures.
- [[#2980](https://github.com/callemall/material-ui/issues/2980)] [[#1839](https://github.com/callemall/material-ui/issues/1839)] Standardise Datepicker for ISO 8601.
#### Deprecations
- [[#2880](https://github.com/callemall/material-ui/issues/2880)] Deprecate valueLink.
- [[#1793](https://github.com/callemall/material-ui/issues/1793)][[#2679](https://github.com/callemall/material-ui/issues/2679)] PascalCase component names and reorganise directory structure. Deprecate old names.
- [[#2697](https://github.com/callemall/material-ui/issues/2697)] Rename LeftNav and deprecate old name.
#### Core
- [[#2903](https://github.com/callemall/material-ui/issues/2903)] Enforce eslint rules.
- [[#2493](https://github.com/callemall/material-ui/pull/2493)] Use higher order components across the library to abstract themes passed down from context.
- [[#2627](https://github.com/callemall/material-ui/issues/2627)] Improve overall theme handling.
- [[#2573](https://github.com/callemall/material-ui/issues/2573)] Remove the usage of isMounted().
- [[#2437](https://github.com/callemall/material-ui/issues/2437)] Remove mixins.
#### Major features
- [[#1321](https://github.com/callemall/material-ui/pull/1321#issuecomment-174108805)] Composable AppBar component.
- [[#3132](https://github.com/callemall/material-ui/pull/3132)] New Stepper component.
- [[#2861](https://github.com/callemall/material-ui/pull/2861)] Scrollable Tabs.
- [[#2979](https://github.com/callemall/material-ui/pull/2979)] New Subheader component.
#### Documentation
- [[#1986](https://github.com/callemall/material-ui/issues/1986)]Documentation versioning.
- Add example on how to use [react-list](https://github.com/orgsync/react-list) for lists, menu items and table.
- [[#2635](https://github.com/callemall/material-ui/pull/2635)] Document the new theme calculation, and it's usage.
- [[#3191](https://github.com/callemall/material-ui/issues/3191)] Improve component property documentation.
### Future
#### Deprecations
- Deprecate & eventually remove all imperative methods.
#### Core
- Make extensive use of `popover` and `render-to-layer`.
- [[#458](https://github.com/callemall/material-ui/issues/458)] Migrate components to [ES6 Classes](https://github.com/callemall/material-ui/tree/es6-classes).
- [[#2784](https://github.com/callemall/material-ui/issues/2784)] Stateless components.
- Improve performance with `shouldComponentUpdate` and removed inefficient computations.
- Standardize API naming and available `prop` convention across the library.
- Better accessibility support.
- Better keyboard navigation support.
#### Features
- [[#2416](https://github.com/callemall/material-ui/issues/2416)] TextField as a composable component for various field types.
- Responsive components to better support MD spec for mobile component sizes, and in preparation for react-native support.
- [[#2863](https://github.com/callemall/material-ui/issues/2863)] Add missing components, and missing features from current ones.
- [[#2251](https://github.com/callemall/material-ui/issues/2251)] Full featured Table.
- Full Featured Tabs (close, [disable](https://github.com/callemall/material-ui/issues/1613), move, sizing, [scrolling](https://github.com/callemall/material-ui/pull/2861)).
- Full support for react-native
- [[#1673](https://github.com/callemall/material-ui/issues/1673)] I18n for the doc-site.
| ROADMAP.md | 0 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.00016945453535299748,
0.00016521869110874832,
0.0001631963677937165,
0.0001643931755097583,
0.0000023726672679913463
] |
{
"id": 7,
"code_window": [
" * Defines the space between the type `item` component.\n",
" * It can only be used on a type `container` component.\n",
" */\n",
" xsGutter: PropTypes.oneOfType([\n",
" PropTypes.bool,\n",
" PropTypes.oneOf(GUTTERS),\n",
" ]),\n",
" /**\n",
" * Defines the `justify-content` style property.\n",
" * It's applied for all the screen sizes.\n",
" */\n",
" xsJustify: PropTypes.oneOf([\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" xsGutter: PropTypes.oneOf(GUTTERS),\n"
],
"file_path": "src/Layout/Layout.js",
"type": "replace",
"edit_start_line_idx": 251
} | // @flow weak
import React, { Component, PropTypes } from 'react';
import { createStyleSheet } from 'jss-theme-reactor';
import classNames from 'classnames';
import Paper from '../Paper';
import Modal from '../internal/Modal';
import Fade from '../transitions/Fade';
export const styleSheet = createStyleSheet('Dialog', (theme) => {
return {
modal: {
justifyContent: 'center',
alignItems: 'center',
},
dialog: {
display: 'flex',
flexDirection: 'column',
flex: '0 1 auto',
position: 'relative',
width: '75%',
maxHeight: '90vh',
'&:focus': {
outline: 'none',
},
},
'dialogWidth-xs': {
maxWidth: theme.breakpoints.getWidth('xs'),
},
'dialogWidth-sm': {
maxWidth: theme.breakpoints.getWidth('sm'),
},
'dialogWidth-md': {
maxWidth: theme.breakpoints.getWidth('md'),
},
};
});
/**
* Dialogs are overlayed modal paper based components with a backdrop.
*
* ```jsx
* <Dialog>
* <DialogContent>...</DialogContent>
* <DialogActions>...</DialogActions>
* </Dialog>
* ```
*/
export default class Dialog extends Component {
static propTypes = {
/**
* Dialog children, usually the included sub-components.
*/
children: PropTypes.node,
/**
* The CSS class name of the root element.
*/
className: PropTypes.string,
/**
* If `true`, clicking the backdrop will fire the `onRequestClose` callback.
*/
hideOnBackdropClick: PropTypes.bool,
/**
* If `true`, hitting escape will fire the `onRequestClose` callback.
*/
hideOnEscapeKeyUp: PropTypes.bool,
/**
* Determine the max width of the dialog.
* The dialog width grows with the size of the screen, this property is useful
* on the desktop where you might need some coherent different width size across your
* application.
*/
maxWidth: PropTypes.oneOf([
'xs',
'sm',
'md',
]),
/**
* Callback fires when the backdrop is clicked on.
*/
onBackdropClick: PropTypes.func,
/**
* Callback fired before the dialog is entering.
*/
onEnter: PropTypes.func,
/**
* Callback fired when the dialog is entering.
*/
onEntering: PropTypes.func,
/**
* Callback fired when the dialog has entered.
*/
onEntered: PropTypes.func, // eslint-disable-line react/sort-prop-types
/**
* Callback fires when the escape key is pressed and the modal is in focus.
*/
onEscapeKeyUp: PropTypes.func, // eslint-disable-line react/sort-prop-types
/**
* Callback fired before the dialog is exiting.
*/
onExit: PropTypes.func,
/**
* Callback fired when the dialog is exiting.
*/
onExiting: PropTypes.func,
/**
* Callback fired when the dialog has exited.
*/
onExited: PropTypes.func, // eslint-disable-line react/sort-prop-types
/**
* Callback fired when the dialog requests to be closed.
*/
onRequestClose: PropTypes.func,
/**
* Set to true to open the Dialog.
*/
open: PropTypes.bool,
/**
* The CSS class name of the paper inner element.
*/
paperClassName: PropTypes.string,
/**
* Transition component.
*/
transition: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
/**
* Length of the transition in ms.
*/
transitionDuration: PropTypes.number,
};
static defaultProps = {
hideOnBackdropClick: true,
hideOnEscapeKeyUp: true,
maxWidth: 'sm',
open: false,
transition: Fade,
transitionDuration: 300,
};
static contextTypes = {
styleManager: PropTypes.object.isRequired,
};
render() {
const {
children,
className,
hideOnBackdropClick,
hideOnEscapeKeyUp,
maxWidth,
open,
onBackdropClick,
onEscapeKeyUp,
onEnter,
onEntering,
onEntered,
onExit,
onExiting,
onExited,
onRequestClose,
paperClassName,
transition,
transitionDuration,
...other
} = this.props;
const classes = this.context.styleManager.render(styleSheet);
const transitionProps = {
in: open,
transitionAppear: true,
transitionDuration,
onEnter,
onEntering,
onEntered,
onExit,
onExiting,
onExited,
};
let createTransitionFn;
if (typeof transition === 'function') {
createTransitionFn = React.createElement;
} else {
createTransitionFn = React.cloneElement;
}
return (
<Modal
className={classNames(classes.modal, className)}
backdropTransitionDuration={transitionDuration}
hideOnBackdropClick={hideOnBackdropClick}
hideOnEscapeKeyUp={hideOnEscapeKeyUp}
onBackdropClick={onBackdropClick}
onEscapeKeyUp={onEscapeKeyUp}
onRequestClose={onRequestClose}
show={open}
{...other}
>
{createTransitionFn(transition, transitionProps, (
<Paper
data-mui-test="Dialog"
zDepth={24}
className={classNames(classes.dialog, classes[`dialogWidth-${maxWidth}`], paperClassName)}
>
{children}
</Paper>
))}
</Modal>
);
}
}
| src/Dialog/Dialog.js | 0 | https://github.com/mui/material-ui/commit/9eff8e6b3cb6ed8e10684f78679eb979ca1e086a | [
0.0002980627177748829,
0.00018741401436273009,
0.00016607425641268492,
0.00016991082520689815,
0.00003778323298320174
] |
{
"id": 0,
"code_window": [
"import { Theme } from '../styles/createMuiTheme';\n",
"import { TransitionProps } from '../transitions/transition';\n",
"\n",
"export interface FadeProps extends TransitionProps {\n",
" theme?: Theme;\n",
"}\n",
"\n",
"declare const Fade: React.ComponentType<FadeProps>;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ref?: React.Ref<unknown>;\n"
],
"file_path": "packages/material-ui/src/Fade/Fade.d.ts",
"type": "add",
"edit_start_line_idx": 5
} | import * as React from 'react';
import { Theme } from '../styles/createMuiTheme';
import { TransitionProps } from '../transitions/transition';
export interface FadeProps extends TransitionProps {
theme?: Theme;
}
declare const Fade: React.ComponentType<FadeProps>;
export default Fade;
| packages/material-ui/src/Fade/Fade.d.ts | 1 | https://github.com/mui/material-ui/commit/4feca34edb6e62d7131ed7a9edb78d66dc67424d | [
0.9978806972503662,
0.4996528625488281,
0.001425033900886774,
0.4996528625488281,
0.4982278347015381
] |
{
"id": 0,
"code_window": [
"import { Theme } from '../styles/createMuiTheme';\n",
"import { TransitionProps } from '../transitions/transition';\n",
"\n",
"export interface FadeProps extends TransitionProps {\n",
" theme?: Theme;\n",
"}\n",
"\n",
"declare const Fade: React.ComponentType<FadeProps>;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ref?: React.Ref<unknown>;\n"
],
"file_path": "packages/material-ui/src/Fade/Fade.d.ts",
"type": "add",
"edit_start_line_idx": 5
} | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M21.71 11.29l-9-9a.9959.9959 0 0 0-1.41 0l-9 9c-.39.39-.39 1.02 0 1.41l9 9c.39.39 1.02.39 1.41 0l9-9c.39-.38.39-1.01 0-1.41zM14 14.5V12h-4v3H8v-4c0-.55.45-1 1-1h5V7.5l3.5 3.5-3.5 3.5z" /><path fill="none" d="M0 0h24v24H0z" /></React.Fragment>
, 'Directions');
| packages/material-ui-icons/src/Directions.js | 0 | https://github.com/mui/material-ui/commit/4feca34edb6e62d7131ed7a9edb78d66dc67424d | [
0.00017392398149240762,
0.00017392398149240762,
0.00017392398149240762,
0.00017392398149240762,
0
] |
{
"id": 0,
"code_window": [
"import { Theme } from '../styles/createMuiTheme';\n",
"import { TransitionProps } from '../transitions/transition';\n",
"\n",
"export interface FadeProps extends TransitionProps {\n",
" theme?: Theme;\n",
"}\n",
"\n",
"declare const Fade: React.ComponentType<FadeProps>;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ref?: React.Ref<unknown>;\n"
],
"file_path": "packages/material-ui/src/Fade/Fade.d.ts",
"type": "add",
"edit_start_line_idx": 5
} | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6-6-6z" /></React.Fragment>
, 'ChevronRightSharp');
| packages/material-ui-icons/src/ChevronRightSharp.js | 0 | https://github.com/mui/material-ui/commit/4feca34edb6e62d7131ed7a9edb78d66dc67424d | [
0.00017474898777436465,
0.00017474898777436465,
0.00017474898777436465,
0.00017474898777436465,
0
] |
{
"id": 0,
"code_window": [
"import { Theme } from '../styles/createMuiTheme';\n",
"import { TransitionProps } from '../transitions/transition';\n",
"\n",
"export interface FadeProps extends TransitionProps {\n",
" theme?: Theme;\n",
"}\n",
"\n",
"declare const Fade: React.ComponentType<FadeProps>;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ref?: React.Ref<unknown>;\n"
],
"file_path": "packages/material-ui/src/Fade/Fade.d.ts",
"type": "add",
"edit_start_line_idx": 5
} | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M13 15v-3h3v-2h-3V7h-2v3H8v2h3v3zM18 15l3 3-3 3 1.5 1.5L24 18l-4.5-4.5z" /><path d="M8 19v2h8v-2h2v-2H3V5h18v8h2V5c0-1.11-.9-2-2-2H3c-1.11 0-2 .89-2 2v12c0 1.1.89 2 2 2h5z" /></React.Fragment>
, 'QueuePlayNextTwoTone');
| packages/material-ui-icons/src/QueuePlayNextTwoTone.js | 0 | https://github.com/mui/material-ui/commit/4feca34edb6e62d7131ed7a9edb78d66dc67424d | [
0.00017243718320969492,
0.00017243718320969492,
0.00017243718320969492,
0.00017243718320969492,
0
] |
{
"id": 1,
"code_window": [
"import { Theme } from '../styles/createMuiTheme';\n",
"import { TransitionProps } from '../transitions/transition';\n",
"\n",
"export interface GrowProps extends Omit<TransitionProps, 'timeout'> {\n",
" theme?: Theme;\n",
" timeout?: TransitionProps['timeout'] | 'auto';\n",
"}\n",
"\n",
"declare const Grow: React.ComponentType<GrowProps>;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ref?: React.Ref<unknown>;\n"
],
"file_path": "packages/material-ui/src/Grow/Grow.d.ts",
"type": "add",
"edit_start_line_idx": 6
} | import * as React from 'react';
import { Theme } from '../styles/createMuiTheme';
import { TransitionProps } from '../transitions/transition';
export interface FadeProps extends TransitionProps {
theme?: Theme;
}
declare const Fade: React.ComponentType<FadeProps>;
export default Fade;
| packages/material-ui/src/Fade/Fade.d.ts | 1 | https://github.com/mui/material-ui/commit/4feca34edb6e62d7131ed7a9edb78d66dc67424d | [
0.004715451970696449,
0.002445631194859743,
0.00017581060819793493,
0.002445631194859743,
0.0022698205430060625
] |
{
"id": 1,
"code_window": [
"import { Theme } from '../styles/createMuiTheme';\n",
"import { TransitionProps } from '../transitions/transition';\n",
"\n",
"export interface GrowProps extends Omit<TransitionProps, 'timeout'> {\n",
" theme?: Theme;\n",
" timeout?: TransitionProps['timeout'] | 'auto';\n",
"}\n",
"\n",
"declare const Grow: React.ComponentType<GrowProps>;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ref?: React.Ref<unknown>;\n"
],
"file_path": "packages/material-ui/src/Grow/Grow.d.ts",
"type": "add",
"edit_start_line_idx": 6
} | import React from 'react';
import AppBar from '@material-ui/core/AppBar';
import Button from '@material-ui/core/Button';
import CameraIcon from '@material-ui/icons/PhotoCamera';
import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import CssBaseline from '@material-ui/core/CssBaseline';
import Grid from '@material-ui/core/Grid';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container';
import Link from '@material-ui/core/Link';
function MadeWithLove() {
return (
<Typography variant="body2" color="textSecondary" align="center">
{'Built with love by the '}
<Link color="inherit" href="https://material-ui.com/">
Material-UI
</Link>
{' team.'}
</Typography>
);
}
const useStyles = makeStyles(theme => ({
icon: {
marginRight: theme.spacing(2),
},
heroContent: {
backgroundColor: theme.palette.background.paper,
padding: theme.spacing(8, 0, 6),
},
heroButtons: {
marginTop: theme.spacing(4),
},
cardGrid: {
paddingTop: theme.spacing(8),
paddingBottom: theme.spacing(8),
},
card: {
height: '100%',
display: 'flex',
flexDirection: 'column',
},
cardMedia: {
paddingTop: '56.25%', // 16:9
},
cardContent: {
flexGrow: 1,
},
footer: {
backgroundColor: theme.palette.background.paper,
padding: theme.spacing(6),
},
}));
const cards = [1, 2, 3, 4, 5, 6, 7, 8, 9];
export default function Album() {
const classes = useStyles();
return (
<React.Fragment>
<CssBaseline />
<AppBar position="relative">
<Toolbar>
<CameraIcon className={classes.icon} />
<Typography variant="h6" color="inherit" noWrap>
Album layout
</Typography>
</Toolbar>
</AppBar>
<main>
{/* Hero unit */}
<div className={classes.heroContent}>
<Container maxWidth="sm">
<Typography component="h1" variant="h2" align="center" color="textPrimary" gutterBottom>
Album layout
</Typography>
<Typography variant="h5" align="center" color="textSecondary" paragraph>
Something short and leading about the collection below—its contents, the creator, etc.
Make it short and sweet, but not too short so folks don't simply skip over it
entirely.
</Typography>
<div className={classes.heroButtons}>
<Grid container spacing={2} justify="center">
<Grid item>
<Button variant="contained" color="primary">
Main call to action
</Button>
</Grid>
<Grid item>
<Button variant="outlined" color="primary">
Secondary action
</Button>
</Grid>
</Grid>
</div>
</Container>
</div>
<Container className={classes.cardGrid} maxWidth="md">
{/* End hero unit */}
<Grid container spacing={4}>
{cards.map(card => (
<Grid item key={card} xs={12} sm={6} md={4}>
<Card className={classes.card}>
<CardMedia
className={classes.cardMedia}
image="https://source.unsplash.com/random"
title="Image title"
/>
<CardContent className={classes.cardContent}>
<Typography gutterBottom variant="h5" component="h2">
Heading
</Typography>
<Typography>
This is a media card. You can use this section to describe the content.
</Typography>
</CardContent>
<CardActions>
<Button size="small" color="primary">
View
</Button>
<Button size="small" color="primary">
Edit
</Button>
</CardActions>
</Card>
</Grid>
))}
</Grid>
</Container>
</main>
{/* Footer */}
<footer className={classes.footer}>
<Typography variant="h6" align="center" gutterBottom>
Footer
</Typography>
<Typography variant="subtitle1" align="center" color="textSecondary" component="p">
Something here to give the footer a purpose!
</Typography>
<MadeWithLove />
</footer>
{/* End footer */}
</React.Fragment>
);
}
| docs/src/pages/getting-started/page-layout-examples/album/Album.js | 0 | https://github.com/mui/material-ui/commit/4feca34edb6e62d7131ed7a9edb78d66dc67424d | [
0.0004626676964107901,
0.00019110090215690434,
0.0001685046881902963,
0.00017372120055370033,
0.00007015713345026597
] |
{
"id": 1,
"code_window": [
"import { Theme } from '../styles/createMuiTheme';\n",
"import { TransitionProps } from '../transitions/transition';\n",
"\n",
"export interface GrowProps extends Omit<TransitionProps, 'timeout'> {\n",
" theme?: Theme;\n",
" timeout?: TransitionProps['timeout'] | 'auto';\n",
"}\n",
"\n",
"declare const Grow: React.ComponentType<GrowProps>;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ref?: React.Ref<unknown>;\n"
],
"file_path": "packages/material-ui/src/Grow/Grow.d.ts",
"type": "add",
"edit_start_line_idx": 6
} | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M5.95 5.98c-3.94 3.95-3.93 10.35.02 14.3l2.86-2.86C5.7 14.29 4.65 9.91 5.95 5.98zM17.42 8.83l2.86-2.86c-3.95-3.95-10.35-3.96-14.3-.02 3.93-1.3 8.31-.25 11.44 2.88z" /><path d="M5.97 5.96l-.01.01c-.38 3.01 1.17 6.88 4.3 10.02l5.73-5.73c-3.13-3.13-7.01-4.68-10.02-4.3zM13.1258 14.5608l1.4283-1.4284 6.4417 6.4417-1.4283 1.4283z" /></React.Fragment>
, 'BeachAccessSharp');
| packages/material-ui-icons/src/BeachAccessSharp.js | 0 | https://github.com/mui/material-ui/commit/4feca34edb6e62d7131ed7a9edb78d66dc67424d | [
0.00017191347433254123,
0.00017191347433254123,
0.00017191347433254123,
0.00017191347433254123,
0
] |
{
"id": 1,
"code_window": [
"import { Theme } from '../styles/createMuiTheme';\n",
"import { TransitionProps } from '../transitions/transition';\n",
"\n",
"export interface GrowProps extends Omit<TransitionProps, 'timeout'> {\n",
" theme?: Theme;\n",
" timeout?: TransitionProps['timeout'] | 'auto';\n",
"}\n",
"\n",
"declare const Grow: React.ComponentType<GrowProps>;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ref?: React.Ref<unknown>;\n"
],
"file_path": "packages/material-ui/src/Grow/Grow.d.ts",
"type": "add",
"edit_start_line_idx": 6
} | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M9.1 5h5.8L19 9.1v5.8l-.22.22 1.42 1.41.8-.8V8.27L15.73 3H8.27l-.8.8 1.41 1.42z" /><circle cx="12" cy="16" r="1" /><path d="M13 9.33V7h-2v.33zM2.41 1.58L1 2.99l3.64 3.64L3 8.27v7.46L8.27 21h7.46l1.64-1.64L21.01 23l1.41-1.41L2.41 1.58zM14.9 19H9.1L5 14.9V9.1l1.05-1.05 9.9 9.9L14.9 19z" /></React.Fragment>
, 'ReportOffOutlined');
| packages/material-ui-icons/src/ReportOffOutlined.js | 0 | https://github.com/mui/material-ui/commit/4feca34edb6e62d7131ed7a9edb78d66dc67424d | [
0.00017283619672525674,
0.00017283619672525674,
0.00017283619672525674,
0.00017283619672525674,
0
] |
{
"id": 2,
"code_window": [
"import { Theme } from '../styles/createMuiTheme';\n",
"import { TransitionProps } from '../transitions/transition';\n",
"\n",
"export interface SlideProps extends TransitionProps {\n",
" direction: 'left' | 'right' | 'up' | 'down';\n",
" theme?: Theme;\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" ref?: React.Ref<unknown>;\n"
],
"file_path": "packages/material-ui/src/Slide/Slide.d.ts",
"type": "add",
"edit_start_line_idx": 6
} | import * as React from 'react';
import { Theme } from '../styles/createMuiTheme';
import { TransitionProps } from '../transitions/transition';
export interface ZoomProps extends TransitionProps {
theme?: Theme;
}
declare const Zoom: React.ComponentType<ZoomProps>;
export default Zoom;
| packages/material-ui/src/Zoom/Zoom.d.ts | 1 | https://github.com/mui/material-ui/commit/4feca34edb6e62d7131ed7a9edb78d66dc67424d | [
0.007048310246318579,
0.0036131609231233597,
0.00017801141075324267,
0.0036131609231233597,
0.0034351495560258627
] |
{
"id": 2,
"code_window": [
"import { Theme } from '../styles/createMuiTheme';\n",
"import { TransitionProps } from '../transitions/transition';\n",
"\n",
"export interface SlideProps extends TransitionProps {\n",
" direction: 'left' | 'right' | 'up' | 'down';\n",
" theme?: Theme;\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" ref?: React.Ref<unknown>;\n"
],
"file_path": "packages/material-ui/src/Slide/Slide.d.ts",
"type": "add",
"edit_start_line_idx": 6
} | ---
title: Список, компонент React
components: Collapse, Divider, List, ListItem, ListItemAvatar, ListItemIcon, ListItemSecondaryAction, ListItemText, ListSubheader
---
# Списки
<p class="description">Списки представляют собой непрерывные вертикальные массивы данных из текста или изображений.</p>
[Списки](https://material.io/design/components/lists.html) представляют собой непрерывную группу из текста или изображений. Они состоят из элементов, содержащих основные и дополнительные действия, которые представлены значками и текстом.
## Простой список
{{"demo": "pages/demos/lists/SimpleList.js"}}
Последний элемент предыдущего примера показывает, как вы можете отрисовать ссылку:
```jsx
function ListItemLink(props) {
return <ListItem button component="a" {...props} />;
}
//...
<ListItemLink href="#simple-list">
<ListItemText primary="Spam" />
</ListItemLink>
```
Вы можете [посмотреть демо с React Router](/guides/composition/#react-router).
## Вложенный список
{{"demo": "pages/demos/lists/NestedList.js"}}
## Список папок
{{"demo": "pages/demos/lists/FolderList.js"}}
## Интерактивность
Ниже приведена интерактивная демонстрация, которая позволяет вам увидеть результаты различных настроек:
{{"demo": "pages/demos/lists/InteractiveList.js"}}
## Выбранный ListItem
{{"demo": "pages/demos/lists/SelectedListItem.js"}}
## Выравнивание элементов списка
Вы должны изменить выравнивание элементов списка при отображении 3 или более элементов. Для этого установите свойство `alignItems = "flex-start"`
{{"demo": "pages/demos/lists/AlignItemsList.js"}}
## Элементы управления списком
### Checkbox
Checkbox может быть основным или второстепенным действием.
В этом примере checkbox является основным действием и индикатором состояния для элемента списка. Кнопка комментария является второстепенным действием.
{{"demo": "pages/demos/lists/CheckboxList.js"}}
Тут checkbox является второстепенным действием для элемента списка.
{{"demo": "pages/demos/lists/CheckboxListSecondary.js"}}
### Switch (переключатель)
Switch является второстепенным действием.
{{"demo": "pages/demos/lists/SwitchListSecondary.js"}}
## Закрепленный подзаголовок
При прокрутке подзаголовки остаются закрепленными в верхней части экрана, пока следующий подзаголовок не оттеснит предыдущий.
Эта функция опирается на фиксированное позиционирование CSS. К сожалению эта функциональность, [не реализована](https://caniuse.com/#search=sticky) всеми браузерами, которые мы поддерживаем. Мы по умолчанию выключаем закрепление - `disableSticky` когда оно не поддерживается.
{{"demo": "pages/demos/lists/PinnedSubheaderList.js"}}
## Вставленный список
{{"demo": "pages/demos/lists/InsetList.js"}}
## Virtualized List
In the following example, we demonstrate how to use [react-window](https://github.com/bvaughn/react-window) with the `List` component. Он отображает 200 строк и c легкостью может еще больше. Virtualization helps with performance issues.
{{"demo": "pages/demos/lists/VirtualizedList.js"}} | docs/src/pages/demos/lists/lists-ru.md | 0 | https://github.com/mui/material-ui/commit/4feca34edb6e62d7131ed7a9edb78d66dc67424d | [
0.0006472545210272074,
0.00021854268561583012,
0.00016584194963797927,
0.00017024700355250388,
0.0001429653784725815
] |
{
"id": 2,
"code_window": [
"import { Theme } from '../styles/createMuiTheme';\n",
"import { TransitionProps } from '../transitions/transition';\n",
"\n",
"export interface SlideProps extends TransitionProps {\n",
" direction: 'left' | 'right' | 'up' | 'down';\n",
" theme?: Theme;\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" ref?: React.Ref<unknown>;\n"
],
"file_path": "packages/material-ui/src/Slide/Slide.d.ts",
"type": "add",
"edit_start_line_idx": 6
} | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M22 18v-2H8V4h2L7 1 4 4h2v2H2v2h4v10h10v2h-2l3 3 3-3h-2v-2h4zM10 8h6v6h2V6h-8v2z" /></g></React.Fragment>
, 'TransformSharp');
| packages/material-ui-icons/src/TransformSharp.js | 0 | https://github.com/mui/material-ui/commit/4feca34edb6e62d7131ed7a9edb78d66dc67424d | [
0.000177277805050835,
0.000177277805050835,
0.000177277805050835,
0.000177277805050835,
0
] |
{
"id": 2,
"code_window": [
"import { Theme } from '../styles/createMuiTheme';\n",
"import { TransitionProps } from '../transitions/transition';\n",
"\n",
"export interface SlideProps extends TransitionProps {\n",
" direction: 'left' | 'right' | 'up' | 'down';\n",
" theme?: Theme;\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" ref?: React.Ref<unknown>;\n"
],
"file_path": "packages/material-ui/src/Slide/Slide.d.ts",
"type": "add",
"edit_start_line_idx": 6
} | import React from 'react';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
import Slide from '@material-ui/core/Slide';
function Transition(props) {
return <Slide direction="up" {...props} />;
}
function AlertDialogSlide() {
const [open, setOpen] = React.useState(false);
function handleClickOpen() {
setOpen(true);
}
function handleClose() {
setOpen(false);
}
return (
<div>
<Button variant="outlined" color="primary" onClick={handleClickOpen}>
Slide in alert dialog
</Button>
<Dialog
open={open}
TransitionComponent={Transition}
keepMounted
onClose={handleClose}
aria-labelledby="alert-dialog-slide-title"
aria-describedby="alert-dialog-slide-description"
>
<DialogTitle id="alert-dialog-slide-title">{"Use Google's location service?"}</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-slide-description">
Let Google help apps determine location. This means sending anonymous location data to
Google, even when no apps are running.
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={handleClose} color="primary">
Disagree
</Button>
<Button onClick={handleClose} color="primary">
Agree
</Button>
</DialogActions>
</Dialog>
</div>
);
}
export default AlertDialogSlide;
| docs/src/pages/demos/dialogs/AlertDialogSlide.js | 0 | https://github.com/mui/material-ui/commit/4feca34edb6e62d7131ed7a9edb78d66dc67424d | [
0.9671364426612854,
0.16170640289783478,
0.0001741938613122329,
0.0007837439188733697,
0.360199511051178
] |
{
"id": 3,
"code_window": [
"import { TransitionProps } from '../transitions/transition';\n",
"\n",
"export interface ZoomProps extends TransitionProps {\n",
" theme?: Theme;\n",
"}\n",
"\n",
"declare const Zoom: React.ComponentType<ZoomProps>;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ref?: React.Ref<unknown>;\n"
],
"file_path": "packages/material-ui/src/Zoom/Zoom.d.ts",
"type": "add",
"edit_start_line_idx": 5
} | import * as React from 'react';
import { Theme } from '../styles/createMuiTheme';
import { TransitionProps } from '../transitions/transition';
export interface ZoomProps extends TransitionProps {
theme?: Theme;
}
declare const Zoom: React.ComponentType<ZoomProps>;
export default Zoom;
| packages/material-ui/src/Zoom/Zoom.d.ts | 1 | https://github.com/mui/material-ui/commit/4feca34edb6e62d7131ed7a9edb78d66dc67424d | [
0.9980291724205017,
0.9345943927764893,
0.871159553527832,
0.9345943927764893,
0.06343480944633484
] |
{
"id": 3,
"code_window": [
"import { TransitionProps } from '../transitions/transition';\n",
"\n",
"export interface ZoomProps extends TransitionProps {\n",
" theme?: Theme;\n",
"}\n",
"\n",
"declare const Zoom: React.ComponentType<ZoomProps>;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ref?: React.Ref<unknown>;\n"
],
"file_path": "packages/material-ui/src/Zoom/Zoom.d.ts",
"type": "add",
"edit_start_line_idx": 5
} | /* eslint-disable no-console */
import fse from 'fs-extra';
import path from 'path';
import yargs from 'yargs';
import Queue from 'modules/waterfall/Queue';
import sleep from 'modules/waterfall/sleep';
import retry from 'modules/waterfall/retry';
import 'isomorphic-fetch';
const themeMap = {
baseline: '', // filled
outline: '_outlined',
round: '_rounded',
twotone: '_two_tone',
sharp: '_sharp',
};
function downloadIcon(icon) {
console.log(`downloadIcon ${icon.index}: ${icon.id}`);
return Promise.all(
Object.keys(themeMap).map(async theme => {
let endUrl;
if (icon.imageUrls && icon.imageUrls[theme]) {
endUrl = icon.imageUrls[theme];
} else {
endUrl = `${theme}-${icon.id}-24px.svg`;
}
const size = endUrl.match(/^.*-([0-9]+)px.svg$/)[1];
const response = await fetch(`https://material.io/tools/icons/static/icons/${endUrl}`);
if (response.status !== 200) {
throw new Error(`status ${response.status}`);
}
const SVG = await response.text();
await fse.writeFile(
path.join(
__dirname,
`../material-io-tools-icons/ic_${icon.id}${themeMap[theme]}_${size}px.svg`,
),
SVG,
);
}),
);
}
async function run() {
try {
const argv = yargs
.usage('Download the SVG from material.io/tools/icons')
.describe('start-after', 'Resume at the following index').argv;
console.log('run', argv);
await fse.ensureDir(path.join(__dirname, '../material-io-tools-icons'));
const response = await fetch('https://material.io/tools/icons/static/data.json');
const data = await response.json();
let icons = data.categories.reduce((acc, item) => acc.concat(item.icons), []);
icons = icons.map((icon, index) => ({ index, ...icon }));
icons = icons.splice(argv.startAfter || 0);
console.log(`${icons.length} icons to download`);
const queue = new Queue(
async icon => {
await retry(async ({ tries }) => {
await sleep((tries - 1) * 100);
await downloadIcon(icon);
});
},
{ concurrency: 5 },
);
queue.push(icons);
await queue.wait({ empty: true });
} catch (err) {
console.log('err', err);
throw err;
}
}
run();
| packages/material-ui-icons/scripts/download.js | 0 | https://github.com/mui/material-ui/commit/4feca34edb6e62d7131ed7a9edb78d66dc67424d | [
0.00017841004591900855,
0.000173141757841222,
0.0001633835054235533,
0.0001751231902744621,
0.000005196181064093253
] |
{
"id": 3,
"code_window": [
"import { TransitionProps } from '../transitions/transition';\n",
"\n",
"export interface ZoomProps extends TransitionProps {\n",
" theme?: Theme;\n",
"}\n",
"\n",
"declare const Zoom: React.ComponentType<ZoomProps>;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ref?: React.Ref<unknown>;\n"
],
"file_path": "packages/material-ui/src/Zoom/Zoom.d.ts",
"type": "add",
"edit_start_line_idx": 5
} | import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';
import Slider from '@material-ui/lab/Slider';
const styles = {
root: {
width: 300,
},
slider: {
padding: '22px 0px',
},
};
class SimpleSlider extends React.Component {
state = {
value: 50,
};
handleChange = (event, value) => {
this.setState({ value });
};
render() {
const { classes } = this.props;
const { value } = this.state;
return (
<div className={classes.root}>
<Typography id="label">Slider label</Typography>
<Slider
className={classes.slider}
value={value}
aria-labelledby="label"
onChange={this.handleChange}
/>
</div>
);
}
}
SimpleSlider.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(SimpleSlider);
| docs/src/pages/lab/slider/SimpleSlider.js | 0 | https://github.com/mui/material-ui/commit/4feca34edb6e62d7131ed7a9edb78d66dc67424d | [
0.00017763585492502898,
0.0001737581187626347,
0.00016826771025080234,
0.00017298541206400841,
0.0000033908331715792883
] |
{
"id": 3,
"code_window": [
"import { TransitionProps } from '../transitions/transition';\n",
"\n",
"export interface ZoomProps extends TransitionProps {\n",
" theme?: Theme;\n",
"}\n",
"\n",
"declare const Zoom: React.ComponentType<ZoomProps>;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ref?: React.Ref<unknown>;\n"
],
"file_path": "packages/material-ui/src/Zoom/Zoom.d.ts",
"type": "add",
"edit_start_line_idx": 5
} | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M12 2C8.13 2 5 5.13 5 9c0 4.17 4.42 9.92 6.24 12.11.4.48 1.13.48 1.53 0C14.58 18.92 19 13.17 19 9c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z" /></React.Fragment>
, 'RoomRounded');
| packages/material-ui-icons/src/RoomRounded.js | 0 | https://github.com/mui/material-ui/commit/4feca34edb6e62d7131ed7a9edb78d66dc67424d | [
0.00017275710706599057,
0.00017275710706599057,
0.00017275710706599057,
0.00017275710706599057,
0
] |
{
"id": 0,
"code_window": [
"\tconst queryLower = query.toLowerCase();\n",
"\n",
"\tlet index = 0;\n",
"\tlet lastIndexOf = 0;\n",
"\tlet score = 0;\n",
"\twhile (index < queryLen) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\tlet lastIndexOf = -1;\n"
],
"file_path": "src/vs/base/common/scorer.ts",
"type": "replace",
"edit_start_line_idx": 50
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
// Based on material from:
/*!
* string_score.js: String Scoring Algorithm 0.1.22
*
* http://joshaven.com/string_score
* https://github.com/joshaven/string_score
*
* Copyright (C) 2009-2014 Joshaven Potter <[email protected]>
* Special thanks to all of the contributors listed here https://github.com/joshaven/string_score
* MIT License: http://opensource.org/licenses/MIT
*
* Date: Tue Mar 1 2011
* Updated: Tue Mar 10 2015
*/
/**
* Compute a score for the given string and the given query.
*
* Rules:
* Character score: 1
* Same case bonus: 1
* Upper case bonus: 1
* Start of word/path bonus: 7
* Start of string bonus: 8
*/
const wordPathBoundary = ['-', '_', ' ', '/', '\\', '.'];
export function score(target: string, query: string, cache?: {[id: string]: number}): number {
if (!target || !query) {
return 0; // return early if target or query are undefined
}
const hash = target + query;
const cached = cache && cache[hash];
if (typeof cached === 'number') {
return cached;
}
const queryLen = query.length;
const targetLower = target.toLowerCase();
const queryLower = query.toLowerCase();
let index = 0;
let lastIndexOf = 0;
let score = 0;
while (index < queryLen) {
var indexOf = targetLower.indexOf(queryLower[index], lastIndexOf);
if (indexOf < 0) {
score = 0; // This makes sure that the query is contained in the target
break;
}
lastIndexOf = indexOf;
// Character Match Bonus
score += 1;
// Same Case Bonous
if (target[indexOf] === query[indexOf]) {
score += 1;
}
// Prefix Bonus
if (indexOf === 0) {
score += 8;
}
// Start of Word/Path Bonous
else if (wordPathBoundary.some(w => w === target[indexOf - 1])) {
score += 7;
}
// Inside Word Upper Case Bonus
else if (isUpper(target.charCodeAt(indexOf))) {
score += 1;
}
index++;
}
if (cache) {
cache[hash] = score;
}
return score;
}
function isUpper(code: number): boolean {
return 65 <= code && code <= 90;
}
/**
* A fast method to check if a given string would produce a score > 0 for the given query.
*/
export function matches(target: string, queryLower: string): boolean {
if (!target || !queryLower) {
return false // return early if target or query are undefined
}
const queryLen = queryLower.length;
const targetLower = target.toLowerCase();
let index = 0;
let lastIndexOf = 0;
while (index < queryLen) {
var indexOf = targetLower.indexOf(queryLower[index], lastIndexOf);
if (indexOf < 0) {
return false;
}
lastIndexOf = indexOf;
index++;
}
return true;
} | src/vs/base/common/scorer.ts | 1 | https://github.com/microsoft/vscode/commit/29303185aa7199f8f26b6ce73bd2bb5722c8bf6e | [
0.9983056783676147,
0.6044231057167053,
0.00016823755868244916,
0.979310929775238,
0.47768691182136536
] |
{
"id": 0,
"code_window": [
"\tconst queryLower = query.toLowerCase();\n",
"\n",
"\tlet index = 0;\n",
"\tlet lastIndexOf = 0;\n",
"\tlet score = 0;\n",
"\twhile (index < queryLen) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\tlet lastIndexOf = -1;\n"
],
"file_path": "src/vs/base/common/scorer.ts",
"type": "replace",
"edit_start_line_idx": 50
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as assert from 'assert';
import { guessMimeTypes, registerTextMimeByFilename, registerTextMimeByFirstLine } from 'vs/base/common/mime';
suite('Mime', () => {
test('Dynamically Register Text Mime', () => {
var guess = guessMimeTypes('foo.monaco');
assert.deepEqual(guess, ['application/unknown']);
registerTextMimeByFilename('.monaco', 'text/monaco');
guess = guessMimeTypes('foo.monaco');
assert.deepEqual(guess, ['text/monaco', 'text/plain']);
guess = guessMimeTypes('.monaco');
assert.deepEqual(guess, ['text/monaco', 'text/plain']);
registerTextMimeByFilename('Codefile', 'text/code');
guess = guessMimeTypes('Codefile');
assert.deepEqual(guess, ['text/code', 'text/plain']);
guess = guessMimeTypes('foo.Codefile');
assert.deepEqual(guess, ['application/unknown']);
registerTextMimeByFirstLine(/RegexesAreNice/, 'text/nice-regex');
guess = guessMimeTypes('Randomfile.noregistration', 'RegexesAreNice');
assert.deepEqual(guess, ['text/nice-regex', 'text/plain']);
guess = guessMimeTypes('Randomfile.noregistration', 'RegexesAreNiceee');
assert.deepEqual(guess, ['application/unknown']);
guess = guessMimeTypes('Codefile', 'RegexesAreNice');
assert.deepEqual(guess, ['text/nice-regex', 'text/plain']);
});
test('Mimes Priority', () => {
registerTextMimeByFilename('.monaco', 'text/monaco');
registerTextMimeByFirstLine(/foobar/, 'text/foobar');
var guess = guessMimeTypes('foo.monaco');
assert.deepEqual(guess, ['text/monaco', 'text/plain']);
guess = guessMimeTypes('foo.monaco', 'foobar');
assert.deepEqual(guess, ['text/foobar', 'text/plain']);
});
test('Specificity priority 1', () => {
registerTextMimeByFilename('.monaco2', 'text/monaco2');
registerTextMimeByFilename('specific.monaco2', 'text/specific-monaco2');
assert.deepEqual(guessMimeTypes('specific.monaco2'), ['text/specific-monaco2', 'text/plain']);
assert.deepEqual(guessMimeTypes('foo.monaco2'), ['text/monaco2', 'text/plain']);
});
test('Specificity priority 2', () => {
registerTextMimeByFilename('specific.monaco3', 'text/specific-monaco3');
registerTextMimeByFilename('.monaco3', 'text/monaco3');
assert.deepEqual(guessMimeTypes('specific.monaco3'), ['text/specific-monaco3', 'text/plain']);
assert.deepEqual(guessMimeTypes('foo.monaco3'), ['text/monaco3', 'text/plain']);
});
test('Mimes Priority - Longest Extension wins', () => {
registerTextMimeByFilename('.monaco', 'text/monaco');
registerTextMimeByFilename('.monaco.xml', 'text/monaco-xml');
registerTextMimeByFilename('.monaco.xml.build', 'text/monaco-xml-build');
var guess = guessMimeTypes('foo.monaco');
assert.deepEqual(guess, ['text/monaco', 'text/plain']);
guess = guessMimeTypes('foo.monaco.xml');
assert.deepEqual(guess, ['text/monaco-xml', 'text/plain']);
guess = guessMimeTypes('foo.monaco.xml.build');
assert.deepEqual(guess, ['text/monaco-xml-build', 'text/plain']);
});
});
| src/vs/base/test/common/mime.test.ts | 0 | https://github.com/microsoft/vscode/commit/29303185aa7199f8f26b6ce73bd2bb5722c8bf6e | [
0.00017738771566655487,
0.00017500885587651283,
0.00017062545521184802,
0.00017574372759554535,
0.0000020703125755971996
] |
{
"id": 0,
"code_window": [
"\tconst queryLower = query.toLowerCase();\n",
"\n",
"\tlet index = 0;\n",
"\tlet lastIndexOf = 0;\n",
"\tlet score = 0;\n",
"\twhile (index < queryLen) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\tlet lastIndexOf = -1;\n"
],
"file_path": "src/vs/base/common/scorer.ts",
"type": "replace",
"edit_start_line_idx": 50
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/* ---------- IE10 remove auto clear button ---------- */
::-ms-clear {
display: none;
}
.monaco-editor {
position: relative;
overflow: visible;
-webkit-text-size-adjust: 100%;
}
.monaco-editor.enable-ligatures {
-webkit-font-feature-settings: "liga" on, "calt" on;
font-feature-settings: "liga" on, "calt" on;
}
.monaco-editor .overflow-guard {
position: relative;
overflow: hidden;
}
/* ---------- View overlays ---------- */
.monaco-editor .view-overlays {
position: absolute;
top: 0;
}
.monaco-editor .view-overlays > .static {
position: absolute;
top: 0;
}
/* ---------- Lines Content ---------- */
.monaco-editor .inputarea {
/*Chrome cannot handle typing in a 0x0 textarea*/
width: 1px;
height: 1px;
min-width: 0;
min-height: 0;
margin: 0;
padding: 0;
position: absolute;
outline: none;
resize: none;
border: none;
overflow: hidden;
}
.monaco-editor.ff .inputarea,
.monaco-editor.ie .inputarea {
width: 0;
height: 0;
}
.monaco-editor.ime-input .inputarea,
.monaco-editor.ie.ime-input .inputarea,
.monaco-editor.ff.ime-input .inputarea、 {
width: 500px;
z-index: 10;
background: rgba(255, 255, 255, 0.85);
}
.monaco-editor .accessibility-output {
position: absolute;
top: 0;
left: 0;
width: 0;
height: 0;
overflow: hidden;
}
.monaco-editor .lines-content {
position: absolute;
top: 0;
}
.monaco-editor .lines-content,
.monaco-editor .view-line,
.monaco-editor .view-line > span,
.monaco-editor .view-line > span > span,
.monaco-editor .view-lines {
-webkit-user-select: text;
-ms-user-select: text;
-khtml-user-select: text;
-moz-user-select: text;
-o-user-select: text;
user-select: text;
}
.monaco-editor.ie .lines-content,
.monaco-editor.ie .view-line,
.monaco-editor.ie .view-line > span,
.monaco-editor.ie .view-line > span > span,
.monaco-editor.ie .view-lines {
-ms-user-select: none;
user-select: none;
}
.monaco-editor .view-lines {
cursor: text;
white-space: nowrap;
}
.monaco-editor .view-line {
position: absolute;
width: 100%;
}
.margin-view-overlays > .view-line {
width: 100%;
}
.monaco-editor .view-layer-line {
position: relative;
overflow: visible;
width: 100%;
}
/* ---------- Squigglies ---------- */
.monaco-editor .redsquiggly {
background: url("red-squiggly.svg") repeat-x bottom left;
}
.monaco-editor .greensquiggly {
background: url("green-squiggly.svg") repeat-x bottom left;
}
.monaco-editor .linked-editing {
box-shadow: inset 0 0 0 1px #B9B9B9;
}
/* ----------- Bracket Match ------ */
.monaco-editor .bracket-match {
box-shadow: inset 0 0 0 1px #B9B9B9;
background-color: rgba(0, 100, 0, 0.1);
}
/* All widgets */
/* I am not a big fan of this rule */
.monaco-editor .editor-widget input {
color: inherit;
}
| src/vs/editor/browser/widget/media/editor.css | 0 | https://github.com/microsoft/vscode/commit/29303185aa7199f8f26b6ce73bd2bb5722c8bf6e | [
0.00017639192810747772,
0.00017155612295027822,
0.00016401318134739995,
0.00017230208322871476,
0.0000032768812161521055
] |
{
"id": 0,
"code_window": [
"\tconst queryLower = query.toLowerCase();\n",
"\n",
"\tlet index = 0;\n",
"\tlet lastIndexOf = 0;\n",
"\tlet score = 0;\n",
"\twhile (index < queryLen) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\tlet lastIndexOf = -1;\n"
],
"file_path": "src/vs/base/common/scorer.ts",
"type": "replace",
"edit_start_line_idx": 50
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as assert from 'assert';
import {isUndefinedOrNull, isArray} from 'vs/base/common/types';
import {isLinux, isWindows} from 'vs/base/common/platform';
import URI from 'vs/base/common/uri';
import {join} from 'vs/base/common/paths';
import {validateFileName} from 'vs/workbench/parts/files/browser/fileActions';
import {LocalFileChangeEvent} from 'vs/workbench/parts/files/common/files';
import {FileStat} from 'vs/workbench/parts/files/common/explorerViewModel';
function createStat(path, name, isFolder, hasChildren, size, mtime, mime) {
return new FileStat(toResource(path), isFolder, hasChildren, name, mtime);
}
function toResource(path) {
return URI.file(join('C:\\', path));
}
suite('Files - View Model', () => {
test("Properties", function() {
let d = new Date().getTime();
let s = createStat("/path/to/stat", "sName", true, true, 8096, d, "text/plain");
assert.strictEqual(s.isDirectoryResolved, false);
assert.strictEqual(s.resource.fsPath, toResource("/path/to/stat").fsPath);
assert.strictEqual(s.name, "sName");
assert.strictEqual(s.isDirectory, true);
assert.strictEqual(s.hasChildren, true);
assert.strictEqual(s.mtime, new Date(d).getTime());
assert.strictEqual(s.mime, undefined);
assert(isArray(s.children) && s.children.length === 0);
s = createStat("/path/to/stat", "sName", true, true, 8096, d, "text/plain; charset utf8");
assert.strictEqual(s.mime, undefined);
s = createStat("/path/to/stat", "sName", false, false, 8096, d, "text/plain; charset utf8");
assert(isUndefinedOrNull(s.children));
s = createStat("/path/to/stat/sName.js", "sName.js", false, false, 8096, d, "text/plain; charset utf8");
assert.strictEqual(s.mime, 'text/javascript, text/plain');
});
test("Add and Remove Child, check for hasChild", function() {
let d = new Date().getTime()
let s = createStat("/path/to/stat", "sName", true, false, 8096, d, "text/plain");
let s2 = createStat("/path/to/stat2", "sName2", false, false, 8096, d, "text/plain");
let child1 = createStat("/path/to/stat/foo", "foo", true, false, 8096, d, "text/plain");
let child2 = createStat("/path/to/stat/bar.html", "bar", false, false, 8096, d, "text/html");
let child3 = createStat("/path/to/stat/bar.html", "bar", false, false, 8096, d, "text/html");
let child4 = createStat("/otherpath/to/other/otherbar.html", "otherbar.html", false, false, 8096, d, "text/html");
assert.throws(function() {
s2.addChild(child1); // Can not add into non directory
});
assert.throws(function() {
s2.addChild(null);
});
assert.throws(function() {
s2.hasChild(child1.name);
});
assert.throws(function() {
s2.removeChild(child1);
});
assert.throws(function() {
s.hasChild(null);
});
assert(!s.hasChild(child1.name));
assert(!s.hasChild(child2.name));
s.addChild(child1);
assert(s.hasChild(child1.name));
assert(!s.hasChild(child1.name.toUpperCase()));
assert(s.hasChild(child1.name.toUpperCase(), true));
assert(s.children.length === 1);
assert(s.hasChildren);
s.addChild(child1);
assert(s.children.length === 1);
s.removeChild(child1);
assert(!s.hasChildren);
assert(s.children.length === 0);
// Assert that adding a child updates its path properly
s.addChild(child4);
assert.strictEqual(child4.resource.fsPath, toResource("/path/to/stat/" + child4.name).fsPath);
});
test("Move", function() {
let d = new Date().getTime();
let s1 = createStat("/", "/", true, false, 8096, d, "text/plain");
let s2 = createStat("/path", "path", true, false, 8096, d, "text/plain");
let s3 = createStat("/path/to", "to", true, false, 8096, d, "text/plain");
let s4 = createStat("/path/to/stat", "stat", false, false, 8096, d, "text/plain");
s1.addChild(s2);
s2.addChild(s3);
s3.addChild(s4);
assert.throws(function() {
s4.move(null);
});
assert.throws(function() {
s2.move(s4); // Can not move into a file
});
assert.throws(function() {
s1.move(s3); // Can not move root
});
s4.move(s1);
assert.strictEqual(s3.children.length, 0);
assert.strictEqual(s3.hasChildren, false);
assert.strictEqual(s1.children.length, 2);
// Assert the new path of the moved element
assert.strictEqual(s4.resource.fsPath, toResource("/" + s4.name).fsPath);
// Move a subtree with children
let leaf = createStat("/leaf", "leaf", true, false, 8096, d, "text/plain");
let leafC1 = createStat("/leaf/folder", "folder", true, false, 8096, d, "text/plain");
let leafCC2 = createStat("/leaf/folder/index.html", "index.html", true, false, 8096, d, "text/html");
leaf.addChild(leafC1);
leafC1.addChild(leafCC2);
s1.addChild(leaf);
leafC1.move(s3);
assert.strictEqual(leafC1.resource.fsPath, URI.file(s3.resource.fsPath + "/" + leafC1.name).fsPath);
assert.strictEqual(leafCC2.resource.fsPath, URI.file(leafC1.resource.fsPath + "/" + leafCC2.name).fsPath);
});
test("Rename", function() {
let d = new Date().getTime();
let s1 = createStat("/", "/", true, false, 8096, d, "text/plain");
let s2 = createStat("/path", "path", true, false, 8096, d, "text/plain");
let s3 = createStat("/path/to", "to", true, false, 8096, d, "text/plain");
let s4 = createStat("/path/to/stat", "stat", true, false, 8096, d, "text/plain");
let s5 = createStat("/path/to/stat", "stat", true, false, 8096, d, "text/plain");
assert.throws(function() {
s2.rename(null);
});
assert.throws(function() {
s1.rename(s2); // Can not rename root
});
assert.throws(function() {
s4.rename(s5); // Can not rename to stat from different workspace
});
s1.addChild(s2);
s2.addChild(s3);
s3.addChild(s4);
let s2renamed = createStat("/otherpath", "otherpath", true, true, 8096, d, "text/plain");
s2.rename(s2renamed);
// Verify the paths have changed including children
assert.strictEqual(s2.name, s2renamed.name);
assert.strictEqual(s2.resource.fsPath, s2renamed.resource.fsPath);
assert.strictEqual(s3.resource.fsPath, toResource("/otherpath/to").fsPath);
assert.strictEqual(s4.resource.fsPath, toResource("/otherpath/to/stat").fsPath);
let s4renamed = createStat("/otherpath/to/statother.js", "statother.js", true, false, 8096, d, "text/javascript");
s4.rename(s4renamed);
assert.strictEqual(s4.name, s4renamed.name);
assert.strictEqual(s4.resource.fsPath, s4renamed.resource.fsPath);
});
test("Find", function() {
let d = new Date().getTime();
let s1 = createStat("/", "/", true, false, 8096, d, "text/plain");
let s2 = createStat("/path", "path", true, false, 8096, d, "text/plain");
let s3 = createStat("/path/to", "to", true, false, 8096, d, "text/plain");
let s4 = createStat("/path/to/stat", "stat", true, false, 8096, d, "text/plain");
let child1 = createStat("/path/to/stat/foo", "foo", true, false, 8096, d, "text/plain");
let child2 = createStat("/path/to/stat/foo/bar.html", "bar.html", false, false, 8096, d, "text/html");
s1.addChild(s2);
s2.addChild(s3);
s3.addChild(s4);
s4.addChild(child1);
child1.addChild(child2);
assert.strictEqual(s1.find(child2.resource), child2);
assert.strictEqual(s1.find(child1.resource), child1);
assert.strictEqual(s1.find(s4.resource), s4);
assert.strictEqual(s1.find(s3.resource), s3);
assert.strictEqual(s1.find(s2.resource), s2);
assert.strictEqual(s1.find(toResource('foobar')), null);
assert.strictEqual(s1.find(toResource('/')), s1);
});
test("Find with mixed case", function() {
let d = new Date().getTime();
let s1 = createStat("/", "/", true, false, 8096, d, "text/plain");
let s2 = createStat("/path", "path", true, false, 8096, d, "text/plain");
let s3 = createStat("/path/to", "to", true, false, 8096, d, "text/plain");
let s4 = createStat("/path/to/stat", "stat", true, false, 8096, d, "text/plain");
let child1 = createStat("/path/to/stat/foo", "foo", true, false, 8096, d, "text/plain");
let child2 = createStat("/path/to/stat/foo/bar.html", "bar.html", false, false, 8096, d, "text/html");
s1.addChild(s2);
s2.addChild(s3);
s3.addChild(s4);
s4.addChild(child1);
child1.addChild(child2);
if (isLinux) { // linux is case sensitive
assert.ok(!s1.find(toResource('/path/to/stat/Foo')));
assert.ok(!s1.find(toResource('/Path/to/stat/foo/bar.html')));
} else {
assert.ok(s1.find(toResource('/path/to/stat/Foo')));
assert.ok(s1.find(toResource('/Path/to/stat/foo/bar.html')));
}
});
test("Validate File Name (For Create)", function() {
let d = new Date().getTime();
let s = createStat("/path/to/stat", "sName", true, true, 8096, d, "text/plain");
let sChild = createStat("/path/to/stat/alles.klar", "alles.klar", true, true, 8096, d, "text/plain");
s.addChild(sChild);
assert(validateFileName(s, null) !== null);
assert(validateFileName(s, "") !== null);
assert(validateFileName(s, " ") !== null);
assert(validateFileName(s, "Read Me") === null, "name containing space");
assert(validateFileName(s, "foo/bar") !== null);
assert(validateFileName(s, "foo\\bar") !== null);
if (isWindows) {
assert(validateFileName(s, "foo:bar") !== null);
assert(validateFileName(s, "foo*bar") !== null);
assert(validateFileName(s, "foo?bar") !== null);
assert(validateFileName(s, "foo<bar") !== null);
assert(validateFileName(s, "foo>bar") !== null);
assert(validateFileName(s, "foo|bar") !== null);
}
assert(validateFileName(s, "alles.klar") !== null);
assert(validateFileName(s, ".foo") === null);
assert(validateFileName(s, "foo.bar") === null);
assert(validateFileName(s, "foo") === null);
});
test("Validate File Name (For Rename)", function() {
let d = new Date().getTime();
let s = createStat("/path/to/stat", "sName", true, true, 8096, d, "text/plain");
let sChild = createStat("/path/to/stat/alles.klar", "alles.klar", true, true, 8096, d, "text/plain");
s.addChild(sChild);
assert(validateFileName(s, "alles.klar") !== null);
if (isLinux) {
assert(validateFileName(s, "Alles.klar") === null);
assert(validateFileName(s, "Alles.Klar") === null);
} else {
assert(validateFileName(s, "Alles.klar") !== null);
assert(validateFileName(s, "Alles.Klar") !== null);
}
assert(validateFileName(s, ".foo") === null);
assert(validateFileName(s, "foo.bar") === null);
assert(validateFileName(s, "foo") === null);
});
test("File Change Event (with stats)", function() {
let d = new Date().toUTCString();
let s1 = new FileStat(toResource("/path/to/sName"), false, false, "sName", 8096 /* Size */, d);
let s2 = new FileStat(toResource("/path/to/sName"), false, false, "sName", 16000 /* Size */, d);
let s3 = new FileStat(toResource("/path/to/sNameMoved"), false, false, "sNameMoved", 8096 /* Size */, d);
// Got Added
let event = new LocalFileChangeEvent(null, s1);
assert(event.gotAdded());
assert(!event.gotDeleted());
assert(!event.gotUpdated());
assert(!event.gotMoved());
// Got Removed
event = new LocalFileChangeEvent(s1, null);
assert(!event.gotAdded());
assert(event.gotDeleted());
assert(!event.gotUpdated());
assert(!event.gotMoved());
// Got Moved
event = new LocalFileChangeEvent(s3, s1);
assert(!event.gotAdded());
assert(!event.gotDeleted());
assert(!event.gotUpdated());
assert(event.gotMoved());
// Got Updated
event = new LocalFileChangeEvent(s2, s1);
assert(!event.gotAdded());
assert(!event.gotDeleted());
assert(event.gotUpdated());
assert(!event.gotMoved());
// No Change
event = new LocalFileChangeEvent(s1, s1);
assert(!event.gotAdded());
assert(!event.gotDeleted());
assert(!event.gotUpdated());
assert(!event.gotMoved());
});
test("Merge Local with Disk", function() {
let d = new Date().toUTCString();
let merge1 = new FileStat(URI.file(join('C:\\', '/path/to')), true, false, "to", 8096, d);
let merge2 = new FileStat(URI.file(join('C:\\', '/path/to')), true, false, "to", 16000, new Date(0).toUTCString());
// Merge Properties
FileStat.mergeLocalWithDisk(merge2, merge1);
assert.strictEqual(merge1.mtime, merge2.mtime);
// Merge Child when isDirectoryResolved=false is a no-op
merge2.addChild(new FileStat(URI.file(join('C:\\', '/path/to/foo.html')), true, false, "foo.html", 8096, d));
FileStat.mergeLocalWithDisk(merge2, merge1);
assert.strictEqual(merge1.children.length, 0);
// Merge Child with isDirectoryResolved=true
merge2.addChild(new FileStat(URI.file(join('C:\\', '/path/to/foo.html')), true, false, "foo.html", 8096, d));
merge2.isDirectoryResolved = true;
FileStat.mergeLocalWithDisk(merge2, merge1);
assert.strictEqual(merge1.children.length, 1);
assert.strictEqual(merge1.children[0].name, "foo.html");
assert.deepEqual(merge1.children[0].parent, merge1, "Check parent");
// Verify that merge does not replace existing children, but updates properties in that case
let existingChild = merge1.children[0];
FileStat.mergeLocalWithDisk(merge2, merge1);
assert.ok(existingChild === merge1.children[0]);
});
}); | src/vs/workbench/parts/files/test/browser/viewModel.test.ts | 0 | https://github.com/microsoft/vscode/commit/29303185aa7199f8f26b6ce73bd2bb5722c8bf6e | [
0.00017666156054474413,
0.00017311076226178557,
0.000168411381309852,
0.00017307762755081058,
0.0000019352946765138768
] |
{
"id": 1,
"code_window": [
"\tlet score = 0;\n",
"\twhile (index < queryLen) {\n",
"\t\tvar indexOf = targetLower.indexOf(queryLower[index], lastIndexOf);\n",
"\t\tif (indexOf < 0) {\n",
"\t\t\tscore = 0; // This makes sure that the query is contained in the target\n",
"\t\t\tbreak;\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tvar indexOf = targetLower.indexOf(queryLower[index], lastIndexOf + 1);\n"
],
"file_path": "src/vs/base/common/scorer.ts",
"type": "replace",
"edit_start_line_idx": 53
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
// Based on material from:
/*!
* string_score.js: String Scoring Algorithm 0.1.22
*
* http://joshaven.com/string_score
* https://github.com/joshaven/string_score
*
* Copyright (C) 2009-2014 Joshaven Potter <[email protected]>
* Special thanks to all of the contributors listed here https://github.com/joshaven/string_score
* MIT License: http://opensource.org/licenses/MIT
*
* Date: Tue Mar 1 2011
* Updated: Tue Mar 10 2015
*/
/**
* Compute a score for the given string and the given query.
*
* Rules:
* Character score: 1
* Same case bonus: 1
* Upper case bonus: 1
* Start of word/path bonus: 7
* Start of string bonus: 8
*/
const wordPathBoundary = ['-', '_', ' ', '/', '\\', '.'];
export function score(target: string, query: string, cache?: {[id: string]: number}): number {
if (!target || !query) {
return 0; // return early if target or query are undefined
}
const hash = target + query;
const cached = cache && cache[hash];
if (typeof cached === 'number') {
return cached;
}
const queryLen = query.length;
const targetLower = target.toLowerCase();
const queryLower = query.toLowerCase();
let index = 0;
let lastIndexOf = 0;
let score = 0;
while (index < queryLen) {
var indexOf = targetLower.indexOf(queryLower[index], lastIndexOf);
if (indexOf < 0) {
score = 0; // This makes sure that the query is contained in the target
break;
}
lastIndexOf = indexOf;
// Character Match Bonus
score += 1;
// Same Case Bonous
if (target[indexOf] === query[indexOf]) {
score += 1;
}
// Prefix Bonus
if (indexOf === 0) {
score += 8;
}
// Start of Word/Path Bonous
else if (wordPathBoundary.some(w => w === target[indexOf - 1])) {
score += 7;
}
// Inside Word Upper Case Bonus
else if (isUpper(target.charCodeAt(indexOf))) {
score += 1;
}
index++;
}
if (cache) {
cache[hash] = score;
}
return score;
}
function isUpper(code: number): boolean {
return 65 <= code && code <= 90;
}
/**
* A fast method to check if a given string would produce a score > 0 for the given query.
*/
export function matches(target: string, queryLower: string): boolean {
if (!target || !queryLower) {
return false // return early if target or query are undefined
}
const queryLen = queryLower.length;
const targetLower = target.toLowerCase();
let index = 0;
let lastIndexOf = 0;
while (index < queryLen) {
var indexOf = targetLower.indexOf(queryLower[index], lastIndexOf);
if (indexOf < 0) {
return false;
}
lastIndexOf = indexOf;
index++;
}
return true;
} | src/vs/base/common/scorer.ts | 1 | https://github.com/microsoft/vscode/commit/29303185aa7199f8f26b6ce73bd2bb5722c8bf6e | [
0.9984922409057617,
0.36557987332344055,
0.00016608991427347064,
0.0026556572411209345,
0.46363064646720886
] |
{
"id": 1,
"code_window": [
"\tlet score = 0;\n",
"\twhile (index < queryLen) {\n",
"\t\tvar indexOf = targetLower.indexOf(queryLower[index], lastIndexOf);\n",
"\t\tif (indexOf < 0) {\n",
"\t\t\tscore = 0; // This makes sure that the query is contained in the target\n",
"\t\t\tbreak;\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tvar indexOf = targetLower.indexOf(queryLower[index], lastIndexOf + 1);\n"
],
"file_path": "src/vs/base/common/scorer.ts",
"type": "replace",
"edit_start_line_idx": 53
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { IStringDictionary, INumberDictionary } from 'vs/base/common/collections';
import URI from 'vs/base/common/uri';
import { EventEmitter } from 'vs/base/common/eventEmitter';
import { IDisposable } from 'vs/base/common/lifecycle';
import { IModelService } from 'vs/editor/common/services/modelService';
import { ILineMatcher, createLineMatcher, ProblemMatcher, FileLocationKind, ProblemMatch, ApplyToKind, WatchingPattern, getResource } from 'vs/platform/markers/common/problemMatcher';
import { IMarkerService, IMarkerData, MarkerType, IResourceMarker, IMarker, MarkerStatistics } from 'vs/platform/markers/common/markers';
export namespace ProblemCollectorEvents {
export let WatchingBeginDetected: string = 'watchingBeginDetected';
export let WatchingEndDetected: string = 'watchingEndDetected';
}
export interface IProblemMatcher {
processLine(line:string):void;
}
export class AbstractProblemCollector extends EventEmitter implements IDisposable {
private matchers: INumberDictionary<ILineMatcher[]>;
private activeMatcher : ILineMatcher;
private _numberOfMatches: number;
private buffer: string[];
private bufferLength: number;
private openModels: IStringDictionary<boolean>;
private modelListeners: IDisposable[];
constructor(problemMatchers: ProblemMatcher[], private modelService: IModelService) {
super();
this.matchers = Object.create(null);
this.bufferLength = 1;
problemMatchers.map(elem => createLineMatcher(elem)).forEach((matcher) => {
let length = matcher.matchLength;
if (length > this.bufferLength) {
this.bufferLength = length;
}
let value = this.matchers[length];
if (!value) {
value = [];
this.matchers[length] = value;
}
value.push(matcher);
});
this.buffer = [];
this.activeMatcher = null;
this.openModels = Object.create(null);
this.modelListeners = [];
this.modelService.onModelAdded((model) => {
this.openModels[model.getAssociatedResource().toString()] = true;
}, this, this.modelListeners);
this.modelService.onModelRemoved((model) => {
delete this.openModels[model.getAssociatedResource().toString()];
}, this, this.modelListeners);
this.modelService.getModels().forEach(model => this.openModels[model.getAssociatedResource().toString()] = true);
}
public dispose() {
this.modelListeners.forEach(disposable => disposable.dispose());
}
public get numberOfMatches(): number {
return this._numberOfMatches;
}
protected tryFindMarker(line: string): ProblemMatch {
let result: ProblemMatch = null;
if (this.activeMatcher) {
result = this.activeMatcher.next(line);
if (result) {
this._numberOfMatches++;
return result;
}
this.clearBuffer();
this.activeMatcher = null;
}
if (this.buffer.length < this.bufferLength) {
this.buffer.push(line);
} else {
let end = this.buffer.length - 1;
for (let i = 0; i < end; i++) {
this.buffer[i] = this.buffer[i + 1];
}
this.buffer[end] = line;
}
result = this.tryMatchers();
if (result) {
this.clearBuffer();
}
return result;
}
protected isOpen(resource: URI): boolean {
return !!this.openModels[resource.toString()];
}
protected shouldApplyMatch(result: ProblemMatch): boolean {
switch(result.description.applyTo) {
case ApplyToKind.allDocuments:
return true;
case ApplyToKind.openDocuments:
return this.openModels[result.resource.toString()]
case ApplyToKind.closedDocuments:
return !this.openModels[result.resource.toString()]
default:
return true;
}
}
private tryMatchers(): ProblemMatch {
this.activeMatcher = null;
let length = this.buffer.length;
for (let startIndex = 0; startIndex < length; startIndex++) {
let candidates = this.matchers[length - startIndex];
if (!candidates) {
continue;
}
for (let i = 0; i < candidates.length; i++) {
let matcher = candidates[i];
let result = matcher.handle(this.buffer, startIndex);
if (result.match) {
this._numberOfMatches++;
if (result.continue) {
this.activeMatcher = matcher;
}
return result.match;
}
}
}
return null;
}
private clearBuffer(): void {
if (this.buffer.length > 0) {
this.buffer = [];
}
}
}
export enum ProblemHandlingStrategy {
Clean
}
export class StartStopProblemCollector extends AbstractProblemCollector implements IProblemMatcher {
private owners: string[];
private markerService: IMarkerService;
private strategy: ProblemHandlingStrategy;
// Global state
private currentResourcesWithMarkers: IStringDictionary<URI[]>;
private reportedResourcesWithMarkers: IStringDictionary<IStringDictionary<URI>>;
// Current State
private currentResource: URI = null;
private currentResourceAsString: string = null;
private markers: IStringDictionary<IMarkerData[]> = Object.create(null);
constructor(problemMatchers: ProblemMatcher[], markerService:IMarkerService, modelService: IModelService, strategy: ProblemHandlingStrategy = ProblemHandlingStrategy.Clean) {
super(problemMatchers, modelService);
let ownerSet:{ [key:string]:boolean; } = Object.create(null);
problemMatchers.forEach(description => ownerSet[description.owner] = true);
this.owners = Object.keys(ownerSet);
this.markerService = markerService;
this.strategy = strategy;
this.currentResourcesWithMarkers = Object.create(null);
this.reportedResourcesWithMarkers = Object.create(null);
this.owners.forEach((owner) => {
this.currentResourcesWithMarkers[owner] = this.markerService.read({owner: owner}).map(m => m.resource);
this.reportedResourcesWithMarkers[owner] = Object.create(null);
});
this.currentResource = null;
this.currentResourceAsString = null;
this.markers = Object.create(null);
}
public processLine(line:string):void {
let markerMatch = this.tryFindMarker(line);
if (!markerMatch) {
return;
}
let owner = markerMatch.description.owner;
let resource = markerMatch.resource;
let resourceAsString = resource.toString();
let shouldApplyMatch = this.shouldApplyMatch(markerMatch);
if (shouldApplyMatch) {
if (this.currentResourceAsString !== resourceAsString) {
if (this.currentResource) {
Object.keys(this.markers).forEach((owner) => {
this.markerService.changeOne(owner, this.currentResource, this.markers[owner]);
});
this.markers = Object.create(null);
}
this.reportedResourcesWithMarkers[owner][resourceAsString] = resource;
this.currentResource = resource;
this.currentResourceAsString = resourceAsString;
}
let markerData = this.markers[owner];
if (!markerData) {
markerData = [];
this.markers[owner] = markerData;
}
markerData.push(markerMatch.marker);
} else {
this.reportedResourcesWithMarkers[owner][resourceAsString] = resource;
}
}
public done(): void {
if (this.currentResource) {
Object.keys(this.markers).forEach((owner) => {
this.markerService.changeOne(owner, this.currentResource, this.markers[owner]);
});
}
if (this.strategy === ProblemHandlingStrategy.Clean) {
Object.keys(this.currentResourcesWithMarkers).forEach((owner) => {
let toRemove:URI[] = [];
let withMarkers = this.reportedResourcesWithMarkers[owner];
this.currentResourcesWithMarkers[owner].forEach((resource) => {
if (!withMarkers[resource.toString()]) {
toRemove.push(resource);
}
});
this.markerService.remove(owner, toRemove);
});
}
this.currentResource = null;
this.currentResourceAsString = null;
this.markers = Object.create(null);
}
}
interface OwnedWatchingPattern {
problemMatcher: ProblemMatcher;
pattern: WatchingPattern;
}
export class WatchingProblemCollector extends AbstractProblemCollector implements IProblemMatcher {
private problemMatchers: ProblemMatcher[];
private watchingBeginsPatterns: OwnedWatchingPattern[];
private watchingEndsPatterns: OwnedWatchingPattern[];
private markerService: IMarkerService;
// Current State
private currentResource: URI;
private currentResourceAsString: string;
private markers: IStringDictionary<IMarkerData[]>;
// Cleaning state
private ignoreOpenResourcesByOwner: IStringDictionary<boolean>;
private resourcesToClean: IStringDictionary<IStringDictionary<URI>>;
constructor(problemMatchers: ProblemMatcher[], markerService: IMarkerService, modelService: IModelService) {
super(problemMatchers, modelService);
this.problemMatchers = problemMatchers;
this.markerService = markerService;
this.resetCurrentResource();
this.resourcesToClean = Object.create(null);
this.ignoreOpenResourcesByOwner = Object.create(null);
this.watchingBeginsPatterns = [];
this.watchingEndsPatterns = [];
this.problemMatchers.forEach(matcher => {
if (matcher.watching) {
this.watchingBeginsPatterns.push({ problemMatcher: matcher, pattern: matcher.watching.beginsPattern });
this.watchingEndsPatterns.push({ problemMatcher: matcher, pattern: matcher.watching.endsPattern });
}
})
}
public aboutToStart(): void {
this.problemMatchers.forEach(matcher => {
if (matcher.watching && matcher.watching.activeOnStart) {
this.emit(ProblemCollectorEvents.WatchingBeginDetected, {});
this.recordResourcesToClean(matcher.owner);
}
let value: boolean = this.ignoreOpenResourcesByOwner[matcher.owner];
if (!value) {
this.ignoreOpenResourcesByOwner[matcher.owner] = (matcher.applyTo === ApplyToKind.closedDocuments);
} else {
let newValue = value && (matcher.applyTo === ApplyToKind.closedDocuments);
if (newValue != value) {
this.ignoreOpenResourcesByOwner[matcher.owner] = newValue;
}
}
})
}
public processLine(line: string): void {
if (this.tryBegin(line) || this.tryFinish(line)) {
return;
}
let markerMatch = this.tryFindMarker(line);
if (!markerMatch) {
return;
}
let resource = markerMatch.resource;
let owner = markerMatch.description.owner;
let resourceAsString = resource.toString();
let shouldApplyMatch = this.shouldApplyMatch(markerMatch);
if (shouldApplyMatch) {
if (this.currentResourceAsString !== resourceAsString) {
this.removeResourceToClean(owner, resourceAsString);
if (this.currentResource) {
this.deliverMarkersForCurrentResource();
}
this.currentResource = resource;
this.currentResourceAsString = resourceAsString;
}
let markerData = this.markers[owner];
if (!markerData) {
markerData = [];
this.markers[owner] = markerData;
}
markerData.push(markerMatch.marker);
} else {
this.removeResourceToClean(owner, resourceAsString);
}
}
public forceDelivery(): void {
this.deliverMarkersForCurrentResource(false);
Object.keys(this.resourcesToClean).forEach((owner) => {
this.cleanMarkers(owner, false);
});
this.resourcesToClean = Object.create(null);
}
private tryBegin(line: string): boolean {
let result = false;
for (let i = 0; i < this.watchingBeginsPatterns.length; i++) {
let beginMatcher = this.watchingBeginsPatterns[i];
let matches = beginMatcher.pattern.regexp.exec(line);
if (matches) {
this.emit(ProblemCollectorEvents.WatchingBeginDetected, {});
result = true;
let owner = beginMatcher.problemMatcher.owner;
if (matches[1]) {
let resource = getResource(matches[1], beginMatcher.problemMatcher);
if (this.currentResourceAsString && this.currentResourceAsString === resource.toString()) {
this.resetCurrentResource();
}
this.recordResourceToClean(owner, resource);
} else {
this.recordResourcesToClean(owner);
this.resetCurrentResource();
}
}
}
return result;
}
private tryFinish(line: string): boolean {
let result = false;
for (let i = 0; i < this.watchingEndsPatterns.length; i++) {
let endMatcher = this.watchingEndsPatterns[i];
let matches = endMatcher.pattern.regexp.exec(line);
if (matches) {
this.emit(ProblemCollectorEvents.WatchingEndDetected, {});
result = true;
let owner = endMatcher.problemMatcher.owner;
this.cleanMarkers(owner);
this.deliverMarkersForCurrentResource();
}
}
return result;
}
private recordResourcesToClean(owner: string): void {
let resourceSetToClean = this.getResourceSetToClean(owner);
this.markerService.read({ owner: owner }).forEach(marker => resourceSetToClean[marker.resource.toString()] = marker.resource);
}
private recordResourceToClean(owner: string, resource: URI): void {
this.getResourceSetToClean(owner)[resource.toString()] = resource;
}
private removeResourceToClean(owner: string, resource: string): void {
let resourceSet = this.resourcesToClean[owner];
if (resourceSet) {
delete resourceSet[resource];
}
}
private cleanMarkers(owner: string, remove: boolean = true): void {
let resourceSet = this.resourcesToClean[owner];
if (resourceSet) {
let toClean = Object.keys(resourceSet).map(key => resourceSet[key]).filter(resource => {
// Check whether we need to ignore open documents for this owner.
return this.ignoreOpenResourcesByOwner[owner] ? !this.isOpen(resource) : true;
});
this.markerService.remove(owner, toClean);
if (remove) {
delete this.resourcesToClean[owner];
}
}
}
private deliverMarkersForCurrentResource(resetCurrentResource: boolean = true): void {
if (this.currentResource) {
Object.keys(this.markers).forEach((owner) => {
this.markerService.changeOne(owner, this.currentResource, this.markers[owner]);
});
}
if (resetCurrentResource) {
this.resetCurrentResource();
}
}
private getResourceSetToClean(owner: string): IStringDictionary<URI> {
let result = this.resourcesToClean[owner];
if (!result) {
result = Object.create(null);
this.resourcesToClean[owner] = result;
}
return result;
}
private resetCurrentResource(): void {
this.currentResource = null;
this.currentResourceAsString = null;
this.markers = Object.create(null);
}
} | src/vs/workbench/parts/tasks/common/problemCollectors.ts | 0 | https://github.com/microsoft/vscode/commit/29303185aa7199f8f26b6ce73bd2bb5722c8bf6e | [
0.0001782412000466138,
0.00017414432659279555,
0.00016736731049604714,
0.00017395119357388467,
0.0000022669637473882176
] |
{
"id": 1,
"code_window": [
"\tlet score = 0;\n",
"\twhile (index < queryLen) {\n",
"\t\tvar indexOf = targetLower.indexOf(queryLower[index], lastIndexOf);\n",
"\t\tif (indexOf < 0) {\n",
"\t\t\tscore = 0; // This makes sure that the query is contained in the target\n",
"\t\t\tbreak;\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tvar indexOf = targetLower.indexOf(queryLower[index], lastIndexOf + 1);\n"
],
"file_path": "src/vs/base/common/scorer.ts",
"type": "replace",
"edit_start_line_idx": 53
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import assert = require('assert');
import EditorCommon = require('vs/editor/common/editorCommon');
import Modes = require('vs/editor/common/modes');
import URI from 'vs/base/common/uri';
import quickfix = require('vs/languages/typescript/common/features/quickFix');
import diagnostics = require('vs/languages/typescript/common/features/diagnostics');
import ts = require('vs/languages/typescript/common/lib/typescriptServices');
import utils = require('vs/languages/typescript/test/common/features/utils');
import Options = require('vs/languages/typescript/common/options');
suite('TS - quick fix', () => {
function assertQuickFix(code: string, fileName: string, callback: (outline: Modes.IQuickFix[]) => any): void {
var filePath = 'file://test/' + fileName;
var fileURL = URI.parse(filePath);
var host = new utils.LanguageServiceHost().add(filePath, code);
var service = ts.createLanguageService(host, ts.createDocumentRegistry());
var markers = diagnostics.getSemanticDiagnostics(service, fileURL, Options.typeScriptOptions).markers;
assert.equal(markers.length, 1);
var marker = markers[0];
var elements = quickfix.compute(service, fileURL, marker);
callback(elements);
}
test('quickfix', function() {
assertQuickFix('class C { private hello = 0; private world = this.hell0; }', 'a.ts', (elements) => {
assert.equal(elements.length, 1);
assert.equal(elements[0].command.title, "Rename to 'hello'");
});
assertQuickFix('_.foo();', 'a.ts', (elements) => {
assert.equal(elements.length, 2);
assert.equal(elements[0].command.title, "Download type definition underscore.d.ts");
assert.equal(elements[1].command.title, "Download type definition lodash.d.ts");
});
assertQuickFix('describe("x");', 'a.js', (elements) => {
assert.equal(elements.length, 3);
assert.equal(elements[0].command.title, "Download type definition mocha.d.ts");
assert.equal(elements[1].command.title, "Download type definition jasmine.d.ts");
assert.equal(elements[2].command.title, "Mark 'describe' as global");
});
assertQuickFix('angular.foo = 1;', 'a.ts', (elements) => {
assert.equal(elements.length, 1);
assert.equal(elements[0].command.title, "Download type definition angular.d.ts");
});
assertQuickFix('var x = __dirname;', 'a.ts', (elements) => {
assert.equal(elements.length, 1);
assert.equal(elements[0].command.title, "Download type definition node.d.ts");
});
assertQuickFix('ko.observable(null);', 'a.ts', (elements) => {
assert.equal(elements.length, 1);
assert.equal(elements[0].command.title, "Download type definition knockout.d.ts");
});
for (var id in quickfix.typingsMap) {
assertQuickFix(id + '.foo();', 'a.ts', (elements) => {
var value = quickfix.typingsMap[id];
var length = Array.isArray(value) ? value.length : 1;
assert.equal(elements.length, length);
});
}
assertQuickFix('foo.observable(null);', 'a.js', (elements) => {
assert.equal(elements.length, 1);
assert.equal(elements[0].command.title, "Mark 'foo' as global");
});
assertQuickFix('toString();', 'a.js', (elements) => {
assert.equal(elements.length, 1);
assert.equal(elements[0].command.title, "Mark 'toString' as global");
});
});
}); | src/vs/languages/typescript/test/common/features/quickfix.test.ts | 0 | https://github.com/microsoft/vscode/commit/29303185aa7199f8f26b6ce73bd2bb5722c8bf6e | [
0.00017929804744198918,
0.00017618804122321308,
0.000172402651514858,
0.00017673923866823316,
0.000002335765202587936
] |
{
"id": 1,
"code_window": [
"\tlet score = 0;\n",
"\twhile (index < queryLen) {\n",
"\t\tvar indexOf = targetLower.indexOf(queryLower[index], lastIndexOf);\n",
"\t\tif (indexOf < 0) {\n",
"\t\t\tscore = 0; // This makes sure that the query is contained in the target\n",
"\t\t\tbreak;\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tvar indexOf = targetLower.indexOf(queryLower[index], lastIndexOf + 1);\n"
],
"file_path": "src/vs/base/common/scorer.ts",
"type": "replace",
"edit_start_line_idx": 53
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as Types from 'vs/base/common/types';
/**
* Equalable objects can compute a
* hash-code and can also tell if they
* are equal to other objects.
*/
export interface IEqualable {
hashCode(): number;
equals(other: any): boolean;
}
export function clone<T>(obj: T): T {
if (!obj || typeof obj !== 'object') {
return obj;
}
if (obj instanceof RegExp) {
return obj;
}
var result = (Array.isArray(obj)) ? <any>[] : <any>{};
Object.keys(obj).forEach((key) => {
if (obj[key] && typeof obj[key] === 'object') {
result[key] = clone(obj[key]);
} else {
result[key] = obj[key];
}
});
return result;
}
export function deepClone<T>(obj: T): T {
if (!obj || typeof obj !== 'object') {
return obj;
}
var result = (Array.isArray(obj)) ? <any>[] : <any>{};
Object.getOwnPropertyNames(obj).forEach((key) => {
if (obj[key] && typeof obj[key] === 'object') {
result[key] = deepClone(obj[key]);
} else {
result[key] = obj[key];
}
});
return result;
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
export function cloneAndChange(obj: any, changer: (orig: any) => any): any {
return _cloneAndChange(obj, changer, []);
}
function _cloneAndChange(obj: any, changer: (orig: any) => any, encounteredObjects: any[]): any {
if (Types.isUndefinedOrNull(obj)) {
return obj;
}
var changed = changer(obj);
if (typeof changed !== 'undefined') {
return changed;
}
if (Types.isArray(obj)) {
var r1: any[] = [];
for (var i1 = 0; i1 < obj.length; i1++) {
r1.push(_cloneAndChange(obj[i1], changer, encounteredObjects));
}
return r1;
}
if (Types.isObject(obj)) {
if (encounteredObjects.indexOf(obj) >= 0) {
throw new Error('Cannot clone recursive data-structure');
}
encounteredObjects.push(obj);
var r2 = {};
for (var i2 in obj) {
if (hasOwnProperty.call(obj, i2)) {
r2[i2] = _cloneAndChange(obj[i2], changer, encounteredObjects);
}
}
encounteredObjects.pop();
return r2;
}
return obj;
}
// DON'T USE THESE FUNCTION UNLESS YOU KNOW HOW CHROME
// WORKS... WE HAVE SEEN VERY WEIRD BEHAVIOUR WITH CHROME >= 37
///**
// * Recursively call Object.freeze on object and any properties that are objects.
// */
//export function deepFreeze(obj:any):void {
// Object.freeze(obj);
// Object.keys(obj).forEach((key) => {
// if(!(typeof obj[key] === 'object') || Object.isFrozen(obj[key])) {
// return;
// }
//
// deepFreeze(obj[key]);
// });
// if(!Object.isFrozen(obj)) {
// console.log('too warm');
// }
//}
//
//export function deepSeal(obj:any):void {
// Object.seal(obj);
// Object.keys(obj).forEach((key) => {
// if(!(typeof obj[key] === 'object') || Object.isSealed(obj[key])) {
// return;
// }
//
// deepSeal(obj[key]);
// });
// if(!Object.isSealed(obj)) {
// console.log('NOT sealed');
// }
//}
/**
* Copies all properties of source into destination. The optional parameter "overwrite" allows to control
* if existing properties on the destination should be overwritten or not. Defaults to true (overwrite).
*/
export function mixin(destination: any, source: any, overwrite: boolean = true): any {
if (!Types.isObject(destination)) {
return source;
}
if (Types.isObject(source)) {
Object.keys(source).forEach((key) => {
if (key in destination) {
if (overwrite) {
if (Types.isObject(destination[key]) && Types.isObject(source[key])) {
mixin(destination[key], source[key], overwrite);
} else {
destination[key] = source[key];
}
}
} else {
destination[key] = source[key];
}
});
}
return destination;
}
export function assign(destination: any, ...sources: any[]): any {
sources.forEach(source => Object.keys(source).forEach((key) => destination[key] = source[key]));
return destination;
}
/**
* Returns a new object that has all values of {{obj}}
* plus those from {{defaults}}.
*/
export function withDefaults<T>(obj: T, defaults: T): T {
return mixin(clone(defaults), obj || {});
}
export function equals(one: any, other: any): boolean {
if (one === other) {
return true;
}
if (one === null || one === undefined || other === null || other === undefined) {
return false;
}
if (typeof one !== typeof other) {
return false;
}
if (typeof one !== 'object') {
return false;
}
if ((Array.isArray(one)) !== (Array.isArray(other))) {
return false;
}
var i: number,
key: string;
if (Array.isArray(one)) {
if (one.length !== other.length) {
return false;
}
for (i = 0; i < one.length; i++) {
if (!equals(one[i], other[i])) {
return false;
}
}
} else {
var oneKeys:string[] = [];
for (key in one) {
oneKeys.push(key);
}
oneKeys.sort();
var otherKeys:string[] = [];
for (key in other) {
otherKeys.push(key);
}
otherKeys.sort();
if (!equals(oneKeys, otherKeys)) {
return false;
}
for (i = 0; i < oneKeys.length; i++) {
if (!equals(one[oneKeys[i]], other[oneKeys[i]])) {
return false;
}
}
}
return true;
}
export function ensureProperty(obj: any, property: string, defaultValue: any) {
if (typeof obj[property] === 'undefined') {
obj[property] = defaultValue;
}
}
export function arrayToHash(array: any[]) {
var result: any = {};
for (var i = 0; i < array.length; ++i) {
result[array[i]] = true;
}
return result;
}
/**
* Given an array of strings, returns a function which, given a string
* returns true or false whether the string is in that array.
*/
export function createKeywordMatcher(arr: string[], caseInsensitive: boolean = false): (str: string) => boolean {
if (caseInsensitive) {
arr = arr.map(function (x) { return x.toLowerCase(); });
}
var hash = arrayToHash(arr);
if (caseInsensitive) {
return function (word) {
return hash[word.toLowerCase()] !== undefined && hash.hasOwnProperty(word.toLowerCase());
};
} else {
return function (word) {
return hash[word] !== undefined && hash.hasOwnProperty(word);
};
}
}
/**
* Started from TypeScript's __extends function to make a type a subclass of a specific class.
* Modified to work with properties already defined on the derivedClass, since we can't get TS
* to call this method before the constructor definition.
*/
export function derive(baseClass: any, derivedClass: any): void {
for (var prop in baseClass) {
if (baseClass.hasOwnProperty(prop)) {
derivedClass[prop] = baseClass[prop];
}
}
derivedClass = derivedClass || function () { };
var basePrototype = baseClass.prototype;
var derivedPrototype = derivedClass.prototype;
derivedClass.prototype = Object.create(basePrototype);
for (var prop in derivedPrototype) {
if (derivedPrototype.hasOwnProperty(prop)) {
// handle getters and setters properly
Object.defineProperty(derivedClass.prototype, prop, Object.getOwnPropertyDescriptor(derivedPrototype, prop));
}
}
// Cast to any due to Bug 16188:PropertyDescriptor set and get function should be optional.
Object.defineProperty(derivedClass.prototype, 'constructor', <any>{ value: derivedClass, writable: true, configurable: true, enumerable: true });
}
/**
* Calls JSON.Stringify with a replacer to break apart any circular references.
* This prevents JSON.stringify from throwing the exception
* "Uncaught TypeError: Converting circular structure to JSON"
*/
export function safeStringify(obj: any): string {
var seen: any[] = [];
return JSON.stringify(obj, (key, value) => {
if (Types.isObject(value) || Array.isArray(value)) {
if (seen.indexOf(value) !== -1) {
return '[Circular]';
} else {
seen.push(value);
}
}
return value;
});
} | src/vs/base/common/objects.ts | 0 | https://github.com/microsoft/vscode/commit/29303185aa7199f8f26b6ce73bd2bb5722c8bf6e | [
0.00017979384574573487,
0.00017310459224972874,
0.00016125140246003866,
0.0001746683701639995,
0.000004531297690846259
] |
{
"id": 2,
"code_window": [
"\tconst queryLen = queryLower.length;\n",
"\tconst targetLower = target.toLowerCase();\n",
"\n",
"\tlet index = 0;\n",
"\tlet lastIndexOf = 0;\n",
"\twhile (index < queryLen) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\tlet lastIndexOf = -1;\n"
],
"file_path": "src/vs/base/common/scorer.ts",
"type": "replace",
"edit_start_line_idx": 110
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
// Based on material from:
/*!
* string_score.js: String Scoring Algorithm 0.1.22
*
* http://joshaven.com/string_score
* https://github.com/joshaven/string_score
*
* Copyright (C) 2009-2014 Joshaven Potter <[email protected]>
* Special thanks to all of the contributors listed here https://github.com/joshaven/string_score
* MIT License: http://opensource.org/licenses/MIT
*
* Date: Tue Mar 1 2011
* Updated: Tue Mar 10 2015
*/
/**
* Compute a score for the given string and the given query.
*
* Rules:
* Character score: 1
* Same case bonus: 1
* Upper case bonus: 1
* Start of word/path bonus: 7
* Start of string bonus: 8
*/
const wordPathBoundary = ['-', '_', ' ', '/', '\\', '.'];
export function score(target: string, query: string, cache?: {[id: string]: number}): number {
if (!target || !query) {
return 0; // return early if target or query are undefined
}
const hash = target + query;
const cached = cache && cache[hash];
if (typeof cached === 'number') {
return cached;
}
const queryLen = query.length;
const targetLower = target.toLowerCase();
const queryLower = query.toLowerCase();
let index = 0;
let lastIndexOf = 0;
let score = 0;
while (index < queryLen) {
var indexOf = targetLower.indexOf(queryLower[index], lastIndexOf);
if (indexOf < 0) {
score = 0; // This makes sure that the query is contained in the target
break;
}
lastIndexOf = indexOf;
// Character Match Bonus
score += 1;
// Same Case Bonous
if (target[indexOf] === query[indexOf]) {
score += 1;
}
// Prefix Bonus
if (indexOf === 0) {
score += 8;
}
// Start of Word/Path Bonous
else if (wordPathBoundary.some(w => w === target[indexOf - 1])) {
score += 7;
}
// Inside Word Upper Case Bonus
else if (isUpper(target.charCodeAt(indexOf))) {
score += 1;
}
index++;
}
if (cache) {
cache[hash] = score;
}
return score;
}
function isUpper(code: number): boolean {
return 65 <= code && code <= 90;
}
/**
* A fast method to check if a given string would produce a score > 0 for the given query.
*/
export function matches(target: string, queryLower: string): boolean {
if (!target || !queryLower) {
return false // return early if target or query are undefined
}
const queryLen = queryLower.length;
const targetLower = target.toLowerCase();
let index = 0;
let lastIndexOf = 0;
while (index < queryLen) {
var indexOf = targetLower.indexOf(queryLower[index], lastIndexOf);
if (indexOf < 0) {
return false;
}
lastIndexOf = indexOf;
index++;
}
return true;
} | src/vs/base/common/scorer.ts | 1 | https://github.com/microsoft/vscode/commit/29303185aa7199f8f26b6ce73bd2bb5722c8bf6e | [
0.9988160133361816,
0.38632938265800476,
0.0001666386378929019,
0.01326891127973795,
0.48268991708755493
] |
{
"id": 2,
"code_window": [
"\tconst queryLen = queryLower.length;\n",
"\tconst targetLower = target.toLowerCase();\n",
"\n",
"\tlet index = 0;\n",
"\tlet lastIndexOf = 0;\n",
"\twhile (index < queryLen) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\tlet lastIndexOf = -1;\n"
],
"file_path": "src/vs/base/common/scorer.ts",
"type": "replace",
"edit_start_line_idx": 110
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import rewriter = require('vs/languages/typescript/common/js/rewriting');
import ts = require('vs/languages/typescript/common/lib/typescriptServices');
class DefineRewriter implements rewriter.ISyntaxRewriter {
public get name() {
return 'rewriter.modules.define';
}
private static _pattern = /\bdefine\b/g;
public computeEdits(context: rewriter.AnalyzerContext): void {
var sourceText = context.sourceFile.getFullText();
DefineRewriter._pattern.lastIndex = 0;
while (DefineRewriter._pattern.test(sourceText)) {
var offset = DefineRewriter._pattern.lastIndex - 1,
node = ts.getTokenAtPosition(context.sourceFile, offset);
if (node && node.kind === ts.SyntaxKind.Identifier && node.parent
&& node.parent.kind === ts.SyntaxKind.CallExpression) {
DefineRewriter._checkArguments(<ts.CallExpression> node.parent, context);
}
}
}
private static _checkArguments(call: ts.CallExpression, context: rewriter.AnalyzerContext): void {
var dependencies: ts.StringLiteral[],
parameters: ts.ParameterDeclaration[];
var idx = call.arguments[0] && call.arguments[0].kind === ts.SyntaxKind.StringLiteral
? 1 : 0;
// define(id?, [dep], function(){ ... });
// ^^^
if (call.arguments[idx] && call.arguments[idx].kind === ts.SyntaxKind.ArrayLiteralExpression) {
(<ts.ArrayLiteralExpression> call.arguments[idx]).elements.forEach(element => {
if (element.kind === ts.SyntaxKind.StringLiteral) {
if (!dependencies) {
dependencies = [<ts.StringLiteral> element];
} else {
dependencies.push(<ts.StringLiteral> element);
}
}
});
}
// define(id?, [dep], function(dep1, dep2){ ... });
// ^^^^^^^^^^
idx += 1;
if (dependencies && call.arguments[idx] && call.arguments[idx].kind === ts.SyntaxKind.FunctionExpression) {
parameters = (<ts.FunctionExpression> call.arguments[idx]).parameters;
}
if (!dependencies || !parameters || !parameters.length) {
return;
}
for (var i = 0; i < parameters.length; i++) {
var parameter = parameters[i];
if (DefineRewriter._specialModules[parameter.name.getText()]) {
// ignore magic dependencies: require, exports, and module
continue;
}
var dependency = dependencies[i];
if (!dependency) {
// no more dependencies to fill in
break;
}
var variableName = rewriter.encodeVariableName(parameter);
context.newDerive(dependency, DefineRewriter._importPattern, variableName, dependency.getText());
context.newInsert(parameter.name.getEnd(), DefineRewriter._typeOfPattern, variableName);
}
}
static _specialModules: { [n: string]: boolean } = { 'require': true, 'exports': true, 'module': true };
static _importPattern = 'import * as {0} from {1};\n';
static _typeOfPattern = ': typeof {0}';
}
export = DefineRewriter; | src/vs/languages/typescript/common/js/defineRewriter.ts | 0 | https://github.com/microsoft/vscode/commit/29303185aa7199f8f26b6ce73bd2bb5722c8bf6e | [
0.00018885380995925516,
0.00017325530643574893,
0.00016501318896189332,
0.00017196789849549532,
0.00000589834007769241
] |
{
"id": 2,
"code_window": [
"\tconst queryLen = queryLower.length;\n",
"\tconst targetLower = target.toLowerCase();\n",
"\n",
"\tlet index = 0;\n",
"\tlet lastIndexOf = 0;\n",
"\twhile (index < queryLen) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\tlet lastIndexOf = -1;\n"
],
"file_path": "src/vs/base/common/scorer.ts",
"type": "replace",
"edit_start_line_idx": 110
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
/**
* Represents a window in a possible chain of iframes
*/
export interface IWindowChainElement {
/**
* The window object for it
*/
window: Window;
/**
* The iframe element inside the window.parent corresponding to window
*/
iframeElement: HTMLIFrameElement;
}
var hasDifferentOriginAncestorFlag:boolean = false;
var sameOriginWindowChainCache:IWindowChainElement[] = null;
function getParentWindowIfSameOrigin(w:Window): Window {
if (!w.parent || w.parent === w) {
return null;
}
// Cannot really tell if we have access to the parent window unless we try to access something in it
try {
var location = w.location;
var parentLocation = w.parent.location;
if (location.protocol !== parentLocation.protocol || location.hostname !== parentLocation.hostname || location.port !== parentLocation.port) {
hasDifferentOriginAncestorFlag = true;
return null;
}
} catch (e) {
hasDifferentOriginAncestorFlag = true;
return null;
}
return w.parent;
}
function findIframeElementInParentWindow(parentWindow:Window, childWindow:Window): HTMLIFrameElement {
var parentWindowIframes = parentWindow.document.getElementsByTagName('iframe');
var iframe:HTMLIFrameElement;
for (var i = 0, len = parentWindowIframes.length; i < len; i++) {
iframe = parentWindowIframes[i];
if (iframe.contentWindow === childWindow) {
return iframe;
}
}
return null;
}
/**
* Returns a chain of embedded windows with the same origin (which can be accessed programmatically).
* Having a chain of length 1 might mean that the current execution environment is running outside of an iframe or inside an iframe embedded in a window with a different origin.
* To distinguish if at one point the current execution environment is running inside a window with a different origin, see hasDifferentOriginAncestor()
*/
export function getSameOriginWindowChain(): IWindowChainElement[] {
if (!sameOriginWindowChainCache) {
sameOriginWindowChainCache = [];
var w = window, parent:Window;
do {
parent = getParentWindowIfSameOrigin(w);
if (parent) {
sameOriginWindowChainCache.push({
window: w,
iframeElement: findIframeElementInParentWindow(parent, w)
});
} else {
sameOriginWindowChainCache.push({
window: w,
iframeElement: null
});
}
w = parent;
} while (w);
}
return sameOriginWindowChainCache.slice(0);
}
/**
* Returns true if the current execution environment is chained in a list of iframes which at one point ends in a window with a different origin.
* Returns false if the current execution environment is not running inside an iframe or if the entire chain of iframes have the same origin.
*/
export function hasDifferentOriginAncestor(): boolean {
if (!sameOriginWindowChainCache) {
getSameOriginWindowChain();
}
return hasDifferentOriginAncestorFlag;
}
/**
* Returns the position of `childWindow` relative to `ancestorWindow`
*/
export function getPositionOfChildWindowRelativeToAncestorWindow(childWindow:Window, ancestorWindow:any) {
if (!ancestorWindow || childWindow === ancestorWindow) {
return {
top: 0,
left: 0
};
}
var top = 0, left = 0;
var windowChain = getSameOriginWindowChain();
for (var i = 0; i < windowChain.length; i++) {
var windowChainEl = windowChain[i];
if (windowChainEl.window === ancestorWindow) {
break;
}
if (!windowChainEl.iframeElement) {
break;
}
var boundingRect = windowChainEl.iframeElement.getBoundingClientRect();
top += boundingRect.top;
left += boundingRect.left;
}
return {
top: top,
left: left
};
} | src/vs/base/browser/iframe.ts | 0 | https://github.com/microsoft/vscode/commit/29303185aa7199f8f26b6ce73bd2bb5722c8bf6e | [
0.00025300143170170486,
0.00017536236555315554,
0.00016526860417798162,
0.00016924188821576536,
0.0000217112301470479
] |
{
"id": 2,
"code_window": [
"\tconst queryLen = queryLower.length;\n",
"\tconst targetLower = target.toLowerCase();\n",
"\n",
"\tlet index = 0;\n",
"\tlet lastIndexOf = 0;\n",
"\twhile (index < queryLen) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\tlet lastIndexOf = -1;\n"
],
"file_path": "src/vs/base/common/scorer.ts",
"type": "replace",
"edit_start_line_idx": 110
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import Strings = require('vs/base/common/strings');
import Modes = require('vs/editor/common/modes');
import EditorCommon = require('vs/editor/common/editorCommon');
export interface ILineEdit {
startColumn: number;
endColumn: number;
text: string;
forceMoveMarkers: boolean;
}
export interface ILineMarker extends EditorCommon.IReadOnlyLineMarker {
id:string;
column:number;
stickToPreviousCharacter:boolean;
oldLineNumber:number;
oldColumn:number;
line:ModelLine;
}
export interface IChangedMarkers {
[markerId:string]: boolean;
}
export interface IModeTransitions {
toArray(topLevelMode: Modes.IMode): Modes.IModeTransition[];
}
export interface ITextWithMarkers {
text: string;
markers: ILineMarker[];
}
interface ITokensAdjuster {
adjust(toColumn:number, delta:number, minimumAllowedColumn:number): void;
finish(delta:number, lineTextLength:number): void;
}
interface IMarkersAdjuster {
adjust(toColumn:number, delta:number, minimumAllowedColumn:number, isReplace:boolean, forceMoveMarkers:boolean): void;
finish(delta:number, lineTextLength:number): void;
}
var NO_OP_TOKENS_ADJUSTER: ITokensAdjuster = {
adjust: () => {},
finish: () => {}
};
var NO_OP_MARKERS_ADJUSTER: IMarkersAdjuster = {
adjust: () => {},
finish: () => {}
};
export class ModelLine {
public lineNumber:number;
public text:string;
public isInvalid:boolean;
private _state:Modes.IState;
private _modeTransitions:IModeTransitions;
private _lineTokens:EditorCommon.ILineTokens;
private _markers:ILineMarker[];
constructor(lineNumber:number, text:string) {
this.lineNumber = lineNumber;
this.text = text;
this.isInvalid = false;
}
// --- BEGIN STATE
public setState(state: Modes.IState): void {
this._state = state;
}
public getState(): Modes.IState {
return this._state || null;
}
// --- END STATE
// --- BEGIN MODE TRANSITIONS
private _setModeTransitions(topLevelMode:Modes.IMode, modeTransitions:Modes.IModeTransition[]): void {
let desired = toModeTransitions(topLevelMode, modeTransitions);
if (desired === null) {
// saving memory
if (typeof this._modeTransitions === 'undefined') {
return;
}
this._modeTransitions = null;
return;
}
this._modeTransitions = desired;
}
public getModeTransitions(): IModeTransitions {
if (this._modeTransitions) {
return this._modeTransitions;
}
return DefaultModeTransitions.INSTANCE;
}
// --- END MODE TRANSITIONS
// --- BEGIN TOKENS
public setTokens(map: EditorCommon.ITokensInflatorMap, tokens: Modes.IToken[], topLevelMode:Modes.IMode, modeTransitions:Modes.IModeTransition[]): void {
this._setLineTokens(map, tokens);
this._setModeTransitions(topLevelMode, modeTransitions);
}
private _setLineTokens(map:EditorCommon.ITokensInflatorMap, tokens:Modes.IToken[]|number[]): void {
let desired = toLineTokens(map, tokens, this.text.length);
if (desired === null) {
// saving memory
if (typeof this._lineTokens === 'undefined') {
return;
}
this._lineTokens = null;
return;
}
this._lineTokens = desired;
}
public getTokens(): EditorCommon.ILineTokens {
if (this._lineTokens) {
return this._lineTokens;
}
if (this.text.length === 0) {
return EmptyLineTokens.INSTANCE;
}
return DefaultLineTokens.INSTANCE;
}
// --- END TOKENS
private _createTokensAdjuster(): ITokensAdjuster {
if (!this._lineTokens) {
// This line does not have real tokens, so there is nothing to adjust
return NO_OP_TOKENS_ADJUSTER;
}
var lineTokens = this._lineTokens;
let BIN = EditorCommon.LineTokensBinaryEncoding;
let tokens = lineTokens.getBinaryEncodedTokens();
let tokensLength = tokens.length;
let tokensIndex = 0;
let currentTokenStartIndex = 0;
let adjust = (toColumn:number, delta:number, minimumAllowedColumn:number) => {
// console.log('before call: tokensIndex: ' + tokensIndex + ': ' + String(this.getTokens()));
// console.log('adjustTokens: ' + toColumn + ' with delta: ' + delta + ' and [' + minimumAllowedColumn + ']');
// console.log('currentTokenStartIndex: ' + currentTokenStartIndex);
let minimumAllowedIndex = minimumAllowedColumn - 1;
while (currentTokenStartIndex < toColumn && tokensIndex < tokensLength) {
if (currentTokenStartIndex > 0 && delta !== 0) {
// adjust token's `startIndex` by `delta`
let deflatedType = (tokens[tokensIndex] / BIN.TYPE_OFFSET) & BIN.TYPE_MASK;
let deflatedBracket = (tokens[tokensIndex] / BIN.BRACKET_OFFSET) & BIN.BRACKET_MASK;
let newStartIndex = Math.max(minimumAllowedIndex, currentTokenStartIndex + delta);
let newToken = deflatedBracket * BIN.BRACKET_OFFSET + deflatedType * BIN.TYPE_OFFSET + newStartIndex * BIN.START_INDEX_OFFSET;
if (delta < 0) {
// pop all previous tokens that have become `collapsed`
while (tokensIndex > 0) {
let prevTokenStartIndex = (tokens[tokensIndex - 1] / BIN.START_INDEX_OFFSET) & BIN.START_INDEX_MASK;
if (prevTokenStartIndex >= newStartIndex) {
// Token at `tokensIndex` - 1 is now `collapsed` => pop it
tokens.splice(tokensIndex - 1, 1);
tokensLength--;
tokensIndex--;
} else {
break;
}
}
}
tokens[tokensIndex] = newToken;
}
tokensIndex++;
if (tokensIndex < tokensLength) {
currentTokenStartIndex = (tokens[tokensIndex] / BIN.START_INDEX_OFFSET) & BIN.START_INDEX_MASK;
}
}
// console.log('after call: tokensIndex: ' + tokensIndex + ': ' + String(this.getTokens()));
};
let finish = (delta:number, lineTextLength:number) => {
adjust(Number.MAX_VALUE, delta, 1);
};
return {
adjust: adjust,
finish: finish
};
}
private _setText(text:string): void {
this.text = text;
if (this._lineTokens) {
let BIN = EditorCommon.LineTokensBinaryEncoding,
map = this._lineTokens.getBinaryEncodedTokensMap(),
tokens = this._lineTokens.getBinaryEncodedTokens(),
lineTextLength = this.text.length;
// Remove overflowing tokens
while (tokens.length > 0) {
let lastTokenStartIndex = (tokens[tokens.length - 1] / BIN.START_INDEX_OFFSET) & BIN.START_INDEX_MASK;
if (lastTokenStartIndex < lineTextLength) {
// Valid token
break;
}
// This token now overflows the text => remove it
tokens.pop();
}
this._setLineTokens(map, tokens);
}
}
// private _printMarkers(): string {
// if (!this._markers) {
// return '[]';
// }
// if (this._markers.length === 0) {
// return '[]';
// }
// var markers = this._markers;
// var printMarker = (m:ILineMarker) => {
// if (m.stickToPreviousCharacter) {
// return '|' + m.column;
// }
// return m.column + '|';
// }
// return '[' + markers.map(printMarker).join(', ') + ']';
// }
private _createMarkersAdjuster(changedMarkers:IChangedMarkers): IMarkersAdjuster {
if (!this._markers) {
return NO_OP_MARKERS_ADJUSTER;
}
if (this._markers.length === 0) {
return NO_OP_MARKERS_ADJUSTER;
}
this._markers.sort(ModelLine._compareMarkers);
var markers = this._markers;
var markersLength = markers.length;
var markersIndex = 0;
var marker = markers[markersIndex];
// console.log('------------- INITIAL MARKERS: ' + this._printMarkers());
let adjust = (toColumn:number, delta:number, minimumAllowedColumn:number, forceStickToPrevious:boolean, forceMoveMarkers:boolean) => {
// console.log('------------------------------');
// console.log('adjust called: toColumn: ' + toColumn + ', delta: ' + delta + ', minimumAllowedColumn: ' + minimumAllowedColumn + ', forceStickToPrevious: ' + forceStickToPrevious + ', forceMoveMarkers:' + forceMoveMarkers);
// console.log('BEFORE::: markersIndex: ' + markersIndex + ' : ' + this._printMarkers());
while (
markersIndex < markersLength
&& (
marker.column < toColumn
|| (
!forceMoveMarkers
&& marker.column === toColumn
&& (forceStickToPrevious || marker.stickToPreviousCharacter)
)
)
) {
if (delta !== 0) {
let newColumn = Math.max(minimumAllowedColumn, marker.column + delta);
if (marker.column !== newColumn) {
changedMarkers[marker.id] = true;
marker.oldLineNumber = marker.oldLineNumber || this.lineNumber;
marker.oldColumn = marker.oldColumn || marker.column;
marker.column = Math.max(minimumAllowedColumn, marker.column + delta);
}
}
markersIndex++;
if (markersIndex < markersLength) {
marker = markers[markersIndex];
}
}
// console.log('AFTER::: markersIndex: ' + markersIndex + ' : ' + this._printMarkers());
};
let finish = (delta:number, lineTextLength:number) => {
adjust(Number.MAX_VALUE, delta, 1, false, false);
// console.log('------------- FINAL MARKERS: ' + this._printMarkers());
};
return {
adjust: adjust,
finish: finish
};
}
public applyEdits(changedMarkers: IChangedMarkers, edits:ILineEdit[]): number {
let deltaColumn = 0;
let resultText = this.text;
let tokensAdjuster = this._createTokensAdjuster();
let markersAdjuster = this._createMarkersAdjuster(changedMarkers);
for (let i = 0, len = edits.length; i < len; i++) {
let edit = edits[i];
// console.log();
// console.log('=============================');
// console.log('EDIT #' + i + ' [ ' + edit.startColumn + ' -> ' + edit.endColumn + ' ] : <<<' + edit.text + '>>>, forceMoveMarkers: ' + edit.forceMoveMarkers);
// console.log('deltaColumn: ' + deltaColumn);
let startColumn = deltaColumn + edit.startColumn;
let endColumn = deltaColumn + edit.endColumn;
let deletingCnt = endColumn - startColumn;
let insertingCnt = edit.text.length;
// Adjust tokens & markers before this edit
// console.log('Adjust tokens & markers before this edit');
tokensAdjuster.adjust(edit.startColumn - 1, deltaColumn, 1);
markersAdjuster.adjust(edit.startColumn, deltaColumn, 1, deletingCnt > 0, edit.forceMoveMarkers);
// Adjust tokens & markers for the common part of this edit
let commonLength = Math.min(deletingCnt, insertingCnt);
if (commonLength > 0) {
// console.log('Adjust tokens & markers for the common part of this edit');
tokensAdjuster.adjust(edit.startColumn - 1 + commonLength, deltaColumn, startColumn);
markersAdjuster.adjust(edit.startColumn + commonLength, deltaColumn, startColumn, deletingCnt > insertingCnt, edit.forceMoveMarkers);
}
// Perform the edit & update `deltaColumn`
resultText = resultText.substring(0, startColumn - 1) + edit.text + resultText.substring(endColumn - 1);
deltaColumn += insertingCnt - deletingCnt;
// Adjust tokens & markers inside this edit
// console.log('Adjust tokens & markers inside this edit');
tokensAdjuster.adjust(edit.endColumn, deltaColumn, startColumn);
markersAdjuster.adjust(edit.endColumn, deltaColumn, startColumn, false, edit.forceMoveMarkers);
}
// Wrap up tokens & markers; adjust remaining if needed
tokensAdjuster.finish(deltaColumn, resultText.length);
markersAdjuster.finish(deltaColumn, resultText.length);
// Save the resulting text
this._setText(resultText);
return deltaColumn;
}
public split(changedMarkers: IChangedMarkers, splitColumn:number, forceMoveMarkers:boolean): ModelLine {
// console.log('--> split @ ' + splitColumn + '::: ' + this._printMarkers());
var myText = this.text.substring(0, splitColumn - 1);
var otherText = this.text.substring(splitColumn - 1);
var otherMarkers: ILineMarker[] = null;
if (this._markers) {
this._markers.sort(ModelLine._compareMarkers);
for (let i = 0, len = this._markers.length; i < len; i++) {
let marker = this._markers[i];
if (
marker.column > splitColumn
|| (
marker.column === splitColumn
&& (
forceMoveMarkers
|| !marker.stickToPreviousCharacter
)
)
) {
let myMarkers = this._markers.slice(0, i);
otherMarkers = this._markers.slice(i);
this._markers = myMarkers;
break;
}
}
if (otherMarkers) {
for (let i = 0, len = otherMarkers.length; i < len; i++) {
let marker = otherMarkers[i];
changedMarkers[marker.id] = true;
marker.oldLineNumber = marker.oldLineNumber || this.lineNumber;
marker.oldColumn = marker.oldColumn || marker.column;
marker.column -= splitColumn - 1;
}
}
}
this._setText(myText);
var otherLine = new ModelLine(this.lineNumber + 1, otherText);
if (otherMarkers) {
otherLine.addMarkers(otherMarkers);
}
return otherLine;
}
public append(changedMarkers: IChangedMarkers, other:ModelLine): void {
// console.log('--> append: THIS :: ' + this._printMarkers());
// console.log('--> append: OTHER :: ' + this._printMarkers());
var thisTextLength = this.text.length;
this._setText(this.text + other.text);
let otherLineTokens = other._lineTokens;
if (otherLineTokens) {
// Other has real tokens
let otherTokens = otherLineTokens.getBinaryEncodedTokens();
// Adjust other tokens
if (thisTextLength > 0) {
let BIN = EditorCommon.LineTokensBinaryEncoding;
for (let i = 0, len = otherTokens.length; i < len; i++) {
let token = otherTokens[i];
let deflatedStartIndex = (token / BIN.START_INDEX_OFFSET) & BIN.START_INDEX_MASK;
let deflatedType = (token / BIN.TYPE_OFFSET) & BIN.TYPE_MASK;
let deflatedBracket = (token / BIN.BRACKET_OFFSET) & BIN.BRACKET_MASK;
let newStartIndex = deflatedStartIndex + thisTextLength;
let newToken = deflatedBracket * BIN.BRACKET_OFFSET + deflatedType * BIN.TYPE_OFFSET + newStartIndex * BIN.START_INDEX_OFFSET;
otherTokens[i] = newToken;
}
}
// Append other tokens
let myLineTokens = this._lineTokens;
if (myLineTokens) {
// I have real tokens
this._setLineTokens(myLineTokens.getBinaryEncodedTokensMap(), myLineTokens.getBinaryEncodedTokens().concat(otherTokens));
} else {
// I don't have real tokens
this._setLineTokens(otherLineTokens.getBinaryEncodedTokensMap(), otherTokens);
}
}
if (other._markers) {
// Other has markers
let otherMarkers = other._markers;
// Adjust other markers
for (let i = 0, len = otherMarkers.length; i < len; i++) {
let marker = otherMarkers[i];
changedMarkers[marker.id] = true;
marker.oldLineNumber = marker.oldLineNumber || other.lineNumber;
marker.oldColumn = marker.oldColumn || marker.column;
marker.column += thisTextLength;
}
this.addMarkers(otherMarkers);
}
}
public addMarker(marker:ILineMarker): void {
marker.line = this;
if (!this._markers) {
this._markers = [marker];
} else {
this._markers.push(marker);
}
}
public addMarkers(markers:ILineMarker[]): void {
if (markers.length === 0) {
return;
}
var i:number,
len:number;
for (i = 0, len = markers.length; i < len; i++) {
markers[i].line = this;
}
if (!this._markers) {
this._markers = markers.slice(0);
} else {
this._markers = this._markers.concat(markers);
}
}
private static _compareMarkers(a:ILineMarker, b:ILineMarker): number {
if (a.column === b.column) {
return (a.stickToPreviousCharacter ? 0 : 1) - (b.stickToPreviousCharacter ? 0 : 1);
}
return a.column - b.column;
}
public removeMarker(marker:ILineMarker): void {
var index = this._indexOfMarkerId(marker.id);
if (index >= 0) {
this._markers.splice(index, 1);
}
marker.line = null;
}
public removeMarkers(deleteMarkers: {[markerId:string]:boolean;}): void {
if (!this._markers) {
return;
}
for (let i = 0, len = this._markers.length; i < len; i++) {
let marker = this._markers[i];
if (deleteMarkers[marker.id]) {
marker.line = null;
this._markers.splice(i, 1);
len--;
i--;
}
}
}
public getMarkers(): ILineMarker[] {
if (!this._markers) {
return [];
}
return this._markers.slice(0);
}
public updateLineNumber(changedMarkers: IChangedMarkers, newLineNumber: number): void {
if (this._markers) {
var markers = this._markers,
i: number,
len: number,
marker: ILineMarker;
for (i = 0, len = markers.length; i < len; i++) {
marker = markers[i];
changedMarkers[marker.id] = true;
marker.oldLineNumber = marker.oldLineNumber || this.lineNumber;
}
}
this.lineNumber = newLineNumber;
}
public deleteLine(changedMarkers: IChangedMarkers, setMarkersColumn:number, setMarkersOldLineNumber:number): ILineMarker[] {
// console.log('--> deleteLine: ');
if (this._markers) {
var markers = this._markers,
i: number,
len: number,
marker: ILineMarker;
// Mark all these markers as changed
for (i = 0, len = markers.length; i < len; i++) {
marker = markers[i];
changedMarkers[marker.id] = true;
marker.oldColumn = marker.oldColumn || marker.column;
marker.oldLineNumber = marker.oldLineNumber || setMarkersOldLineNumber;
marker.column = setMarkersColumn;
}
return markers;
}
return [];
}
private _indexOfMarkerId(markerId:string): number {
if (this._markers) {
var markers = this._markers,
i: number,
len: number;
for (i = 0, len = markers.length; i < len; i++) {
if (markers[i].id === markerId) {
return i;
}
}
}
return -1;
}
}
function areDeflatedTokens(tokens:Modes.IToken[]|number[]): tokens is number[] {
return (typeof tokens[0] === 'number');
}
function toLineTokens(map:EditorCommon.ITokensInflatorMap, tokens:Modes.IToken[]|number[], textLength:number): EditorCommon.ILineTokens {
if (textLength === 0) {
return null;
}
if (!tokens || tokens.length === 0) {
return null;
}
if (tokens.length === 1) {
if (areDeflatedTokens(tokens)) {
if (tokens[0] === 0) {
return null;
}
} else {
if (tokens[0].startIndex === 0 && tokens[0].type === '' && !tokens[0].bracket) {
return null;
}
}
}
return new LineTokens(map, tokens);
}
var getStartIndex = EditorCommon.LineTokensBinaryEncoding.getStartIndex;
var getType = EditorCommon.LineTokensBinaryEncoding.getType;
var getBracket = EditorCommon.LineTokensBinaryEncoding.getBracket;
var findIndexOfOffset = EditorCommon.LineTokensBinaryEncoding.findIndexOfOffset;
export class LineTokens implements EditorCommon.ILineTokens {
private map:EditorCommon.ITokensInflatorMap;
private _tokens:number[];
constructor(map:EditorCommon.ITokensInflatorMap, tokens:Modes.IToken[]|number[]) {
this.map = map;
if (areDeflatedTokens(tokens)) {
this._tokens = tokens;
} else {
this._tokens = EditorCommon.LineTokensBinaryEncoding.deflateArr(map, tokens);
}
}
public toString(): string {
return EditorCommon.LineTokensBinaryEncoding.inflateArr(this.map, this._tokens).toString();
}
public getBinaryEncodedTokensMap(): EditorCommon.ITokensInflatorMap {
return this.map;
}
public getBinaryEncodedTokens(): number[] {
return this._tokens;
}
public getTokenCount(): number {
return this._tokens.length;
}
public getTokenStartIndex(tokenIndex:number): number {
return getStartIndex(this._tokens[tokenIndex]);
}
public getTokenType(tokenIndex:number): string {
return getType(this.map, this._tokens[tokenIndex]);
}
public getTokenBracket(tokenIndex:number): Modes.Bracket {
return getBracket(this._tokens[tokenIndex]);
}
public getTokenEndIndex(tokenIndex:number, textLength:number): number {
if (tokenIndex + 1 < this._tokens.length) {
return getStartIndex(this._tokens[tokenIndex + 1]);
}
return textLength;
}
public equals(other:EditorCommon.ILineTokens): boolean {
return this === other;
}
public findIndexOfOffset(offset:number): number {
return findIndexOfOffset(this._tokens, offset);
}
}
class EmptyLineTokens implements EditorCommon.ILineTokens {
public static INSTANCE = new EmptyLineTokens();
private static TOKENS = <number[]>[];
public getBinaryEncodedTokens(): number[] {
return EmptyLineTokens.TOKENS;
}
public getBinaryEncodedTokensMap(): EditorCommon.ITokensInflatorMap {
return null;
}
public getTokenCount(): number {
return 0;
}
public getTokenStartIndex(tokenIndex:number): number {
return 0;
}
public getTokenType(tokenIndex:number): string {
return Strings.empty;
}
public getTokenBracket(tokenIndex:number): Modes.Bracket {
return 0;
}
public getTokenEndIndex(tokenIndex:number, textLength:number): number {
return 0;
}
public equals(other:EditorCommon.ILineTokens): boolean {
return other === this;
}
public findIndexOfOffset(offset:number): number {
return 0;
}
}
export class DefaultLineTokens implements EditorCommon.ILineTokens {
public static INSTANCE = new DefaultLineTokens();
private static TOKENS = <number[]> [0];
public getBinaryEncodedTokensMap(): EditorCommon.ITokensInflatorMap {
return null;
}
public getBinaryEncodedTokens(): number[] {
return DefaultLineTokens.TOKENS;
}
public getTokenCount(): number {
return 1;
}
public getTokenStartIndex(tokenIndex:number): number {
return 0;
}
public getTokenType(tokenIndex:number): string {
return Strings.empty;
}
public getTokenBracket(tokenIndex:number): Modes.Bracket {
return 0;
}
public getTokenEndIndex(tokenIndex:number, textLength:number): number {
return textLength;
}
public equals(other:EditorCommon.ILineTokens): boolean {
return this === other;
}
public findIndexOfOffset(offset:number): number {
return 0;
}
}
function toModeTransitions(topLevelMode:Modes.IMode, modeTransitions:Modes.IModeTransition[]): IModeTransitions {
if (!modeTransitions || modeTransitions.length === 0) {
return null;
} else if (modeTransitions.length === 1 && modeTransitions[0].startIndex === 0) {
if (modeTransitions[0].mode === topLevelMode) {
return null;
} else {
return new SingleModeTransition(modeTransitions[0].mode);
}
}
return new ModeTransitions(modeTransitions);
}
class DefaultModeTransitions implements IModeTransitions {
public static INSTANCE = new DefaultModeTransitions();
public toArray(topLevelMode:Modes.IMode): Modes.IModeTransition[] {
return [{
startIndex: 0,
mode: topLevelMode
}];
}
}
class SingleModeTransition implements IModeTransitions {
private _mode: Modes.IMode;
constructor(mode:Modes.IMode) {
this._mode = mode;
}
public toArray(topLevelMode:Modes.IMode): Modes.IModeTransition[] {
return [{
startIndex: 0,
mode: this._mode
}];
}
}
class ModeTransitions implements IModeTransitions {
private _modeTransitions: Modes.IModeTransition[];
constructor(modeTransitions:Modes.IModeTransition[]) {
this._modeTransitions = modeTransitions;
}
public toArray(topLevelMode:Modes.IMode): Modes.IModeTransition[] {
return this._modeTransitions.slice(0);
}
} | src/vs/editor/common/model/modelLine.ts | 0 | https://github.com/microsoft/vscode/commit/29303185aa7199f8f26b6ce73bd2bb5722c8bf6e | [
0.04780128598213196,
0.0007497900514863431,
0.0001645865704631433,
0.00017014870536513627,
0.00516522815451026
] |
{
"id": 3,
"code_window": [
"\twhile (index < queryLen) {\n",
"\t\tvar indexOf = targetLower.indexOf(queryLower[index], lastIndexOf);\n",
"\t\tif (indexOf < 0) {\n",
"\t\t\treturn false;\n",
"\t\t}\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tvar indexOf = targetLower.indexOf(queryLower[index], lastIndexOf + 1);\n"
],
"file_path": "src/vs/base/common/scorer.ts",
"type": "replace",
"edit_start_line_idx": 112
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
// Based on material from:
/*!
* string_score.js: String Scoring Algorithm 0.1.22
*
* http://joshaven.com/string_score
* https://github.com/joshaven/string_score
*
* Copyright (C) 2009-2014 Joshaven Potter <[email protected]>
* Special thanks to all of the contributors listed here https://github.com/joshaven/string_score
* MIT License: http://opensource.org/licenses/MIT
*
* Date: Tue Mar 1 2011
* Updated: Tue Mar 10 2015
*/
/**
* Compute a score for the given string and the given query.
*
* Rules:
* Character score: 1
* Same case bonus: 1
* Upper case bonus: 1
* Start of word/path bonus: 7
* Start of string bonus: 8
*/
const wordPathBoundary = ['-', '_', ' ', '/', '\\', '.'];
export function score(target: string, query: string, cache?: {[id: string]: number}): number {
if (!target || !query) {
return 0; // return early if target or query are undefined
}
const hash = target + query;
const cached = cache && cache[hash];
if (typeof cached === 'number') {
return cached;
}
const queryLen = query.length;
const targetLower = target.toLowerCase();
const queryLower = query.toLowerCase();
let index = 0;
let lastIndexOf = 0;
let score = 0;
while (index < queryLen) {
var indexOf = targetLower.indexOf(queryLower[index], lastIndexOf);
if (indexOf < 0) {
score = 0; // This makes sure that the query is contained in the target
break;
}
lastIndexOf = indexOf;
// Character Match Bonus
score += 1;
// Same Case Bonous
if (target[indexOf] === query[indexOf]) {
score += 1;
}
// Prefix Bonus
if (indexOf === 0) {
score += 8;
}
// Start of Word/Path Bonous
else if (wordPathBoundary.some(w => w === target[indexOf - 1])) {
score += 7;
}
// Inside Word Upper Case Bonus
else if (isUpper(target.charCodeAt(indexOf))) {
score += 1;
}
index++;
}
if (cache) {
cache[hash] = score;
}
return score;
}
function isUpper(code: number): boolean {
return 65 <= code && code <= 90;
}
/**
* A fast method to check if a given string would produce a score > 0 for the given query.
*/
export function matches(target: string, queryLower: string): boolean {
if (!target || !queryLower) {
return false // return early if target or query are undefined
}
const queryLen = queryLower.length;
const targetLower = target.toLowerCase();
let index = 0;
let lastIndexOf = 0;
while (index < queryLen) {
var indexOf = targetLower.indexOf(queryLower[index], lastIndexOf);
if (indexOf < 0) {
return false;
}
lastIndexOf = indexOf;
index++;
}
return true;
} | src/vs/base/common/scorer.ts | 1 | https://github.com/microsoft/vscode/commit/29303185aa7199f8f26b6ce73bd2bb5722c8bf6e | [
0.9972516894340515,
0.3818609416484833,
0.00016412940749432892,
0.0017698337323963642,
0.4822838008403778
] |
{
"id": 3,
"code_window": [
"\twhile (index < queryLen) {\n",
"\t\tvar indexOf = targetLower.indexOf(queryLower[index], lastIndexOf);\n",
"\t\tif (indexOf < 0) {\n",
"\t\t\treturn false;\n",
"\t\t}\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tvar indexOf = targetLower.indexOf(queryLower[index], lastIndexOf + 1);\n"
],
"file_path": "src/vs/base/common/scorer.ts",
"type": "replace",
"edit_start_line_idx": 112
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import {IEditor, ITextModel} from 'vs/editor/common/editorCommon';
import {StringEditorInput} from 'vs/workbench/common/editor/stringEditorInput';
import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
/**
* A read-only text editor input whos contents are made of the provided value and mime type. As a subclass of StringEditorInput
* it adds additional functionality suitable for using it to show output or logs.
*/
export class LogEditorInput extends StringEditorInput {
public static ID = 'workbench.editors.logEditorInput';
constructor(
name: string,
description: string,
value: string,
mime: string,
singleton: boolean,
@IInstantiationService instantiationService: IInstantiationService,
@IWorkbenchEditorService private editorService: IWorkbenchEditorService
) {
super(name, description, value, mime, singleton, instantiationService);
}
public getId(): string {
return LogEditorInput.ID;
}
/**
* Appends text to the end of this input and automatically reveals the last line if an editor is visible with this input.
*/
public append(value: string): void {
super.append(value);
this.revealLastLine();
}
/**
* Removes all lines from the top if the line number exceeds the given line count. Returns the new value if lines got trimmed.
* Automatically reveals the last line if an editor is visible with this input.
*
* Note: This method is a no-op if the input has not yet been resolved.
*/
public trim(linecount: number): string {
let newValue = super.trim(linecount);
if (newValue !== null) {
this.revealLastLine();
}
return newValue;
}
/**
* Reveals the last line on any editor that has this output set.
*/
public revealLastLine(): void {
let editors = this.editorService.getVisibleEditors();
for (let i = 0; i < editors.length; i++) {
let editor = editors[i];
if (editor.input === this) {
let editorControl = <IEditor>editor.getControl();
if (editorControl) {
let model = <ITextModel>editorControl.getModel();
if (model) {
let lastLine = model.getLineCount();
editorControl.revealLine(lastLine);
}
}
}
}
}
} | src/vs/workbench/common/editor/logEditorInput.ts | 0 | https://github.com/microsoft/vscode/commit/29303185aa7199f8f26b6ce73bd2bb5722c8bf6e | [
0.00022738090774510056,
0.0001789967209333554,
0.00016442766354884952,
0.0001724555331747979,
0.000018768922018352896
] |
{
"id": 3,
"code_window": [
"\twhile (index < queryLen) {\n",
"\t\tvar indexOf = targetLower.indexOf(queryLower[index], lastIndexOf);\n",
"\t\tif (indexOf < 0) {\n",
"\t\t\treturn false;\n",
"\t\t}\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tvar indexOf = targetLower.indexOf(queryLower[index], lastIndexOf + 1);\n"
],
"file_path": "src/vs/base/common/scorer.ts",
"type": "replace",
"edit_start_line_idx": 112
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-menu .monaco-action-bar.vertical .action-label.hover {
background-color: #EEE;
} | src/vs/editor/contrib/clipboard/browser/clipboard.css | 0 | https://github.com/microsoft/vscode/commit/29303185aa7199f8f26b6ce73bd2bb5722c8bf6e | [
0.00017661525635048747,
0.00017661525635048747,
0.00017661525635048747,
0.00017661525635048747,
0
] |
{
"id": 3,
"code_window": [
"\twhile (index < queryLen) {\n",
"\t\tvar indexOf = targetLower.indexOf(queryLower[index], lastIndexOf);\n",
"\t\tif (indexOf < 0) {\n",
"\t\t\treturn false;\n",
"\t\t}\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tvar indexOf = targetLower.indexOf(queryLower[index], lastIndexOf + 1);\n"
],
"file_path": "src/vs/base/common/scorer.ts",
"type": "replace",
"edit_start_line_idx": 112
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/* ---------- DiffEditor ---------- */
.monaco-diff-editor .diffOverview {
z-index: 9;
}
.monaco-diff-editor .diffViewport {
box-shadow: inset 0px 0px 1px 0px #B9B9B9;
background: rgba(148, 148, 148, 0.19);
}
.monaco-diff-editor.vs-dark {
background: #1E1E1E;
}
.monaco-scrollable-element.modified-in-monaco-diff-editor .scrollbar {
background: rgba(0,0,0,0);
}
.monaco-scrollable-element.modified-in-monaco-diff-editor .slider {
z-index: 10;
}
.modified-in-monaco-diff-editor .slider.active {
background: rgba(171, 171, 171, .4);
}
.monaco-diff-editor.side-by-side .editor.modified {
box-shadow: -6px 0 5px -5px #DDD;
}
.monaco-diff-editor.side-by-side.vs-dark .editor.modified {
box-shadow: -6px 0 5px -5px black;
}
/* ---------- Diff ---------- */
.monaco-editor .line-delete, .monaco-editor .char-delete {
background: rgba(255, 0, 0, 0.2);
}
.monaco-editor .line-insert, .monaco-editor .char-insert {
background: rgba(155, 185, 85, 0.2);
}
.monaco-editor .diagonal-fill {
background: url('diagonal-fill.png');
}
.monaco-editor.vs-dark .diagonal-fill {
opacity: 0.2;
}
/* ---------- Inline Diff ---------- */
.monaco-editor .view-zones .view-lines .view-line span {
display: inline-block;
}
/* High Contrast Theming */
.monaco-diff-editor.hc-black {
background: #000;
} | src/vs/editor/browser/widget/media/diffEditor.css | 0 | https://github.com/microsoft/vscode/commit/29303185aa7199f8f26b6ce73bd2bb5722c8bf6e | [
0.00017722017946653068,
0.00017029247828759253,
0.00016595884517300874,
0.0001687519979896024,
0.000004031765911349794
] |
{
"id": 4,
"code_window": [
"\t\tif (indexOf < 0) {\n",
"\t\t\treturn false;\n",
"\t\t}\n",
"\n",
"\t\tlastIndexOf = indexOf;\n",
"\t\t\n",
"\t\tindex++;\n",
"\t}\n",
"\n",
"\treturn true;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "src/vs/base/common/scorer.ts",
"type": "replace",
"edit_start_line_idx": 118
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
// Based on material from:
/*!
* string_score.js: String Scoring Algorithm 0.1.22
*
* http://joshaven.com/string_score
* https://github.com/joshaven/string_score
*
* Copyright (C) 2009-2014 Joshaven Potter <[email protected]>
* Special thanks to all of the contributors listed here https://github.com/joshaven/string_score
* MIT License: http://opensource.org/licenses/MIT
*
* Date: Tue Mar 1 2011
* Updated: Tue Mar 10 2015
*/
/**
* Compute a score for the given string and the given query.
*
* Rules:
* Character score: 1
* Same case bonus: 1
* Upper case bonus: 1
* Start of word/path bonus: 7
* Start of string bonus: 8
*/
const wordPathBoundary = ['-', '_', ' ', '/', '\\', '.'];
export function score(target: string, query: string, cache?: {[id: string]: number}): number {
if (!target || !query) {
return 0; // return early if target or query are undefined
}
const hash = target + query;
const cached = cache && cache[hash];
if (typeof cached === 'number') {
return cached;
}
const queryLen = query.length;
const targetLower = target.toLowerCase();
const queryLower = query.toLowerCase();
let index = 0;
let lastIndexOf = 0;
let score = 0;
while (index < queryLen) {
var indexOf = targetLower.indexOf(queryLower[index], lastIndexOf);
if (indexOf < 0) {
score = 0; // This makes sure that the query is contained in the target
break;
}
lastIndexOf = indexOf;
// Character Match Bonus
score += 1;
// Same Case Bonous
if (target[indexOf] === query[indexOf]) {
score += 1;
}
// Prefix Bonus
if (indexOf === 0) {
score += 8;
}
// Start of Word/Path Bonous
else if (wordPathBoundary.some(w => w === target[indexOf - 1])) {
score += 7;
}
// Inside Word Upper Case Bonus
else if (isUpper(target.charCodeAt(indexOf))) {
score += 1;
}
index++;
}
if (cache) {
cache[hash] = score;
}
return score;
}
function isUpper(code: number): boolean {
return 65 <= code && code <= 90;
}
/**
* A fast method to check if a given string would produce a score > 0 for the given query.
*/
export function matches(target: string, queryLower: string): boolean {
if (!target || !queryLower) {
return false // return early if target or query are undefined
}
const queryLen = queryLower.length;
const targetLower = target.toLowerCase();
let index = 0;
let lastIndexOf = 0;
while (index < queryLen) {
var indexOf = targetLower.indexOf(queryLower[index], lastIndexOf);
if (indexOf < 0) {
return false;
}
lastIndexOf = indexOf;
index++;
}
return true;
} | src/vs/base/common/scorer.ts | 1 | https://github.com/microsoft/vscode/commit/29303185aa7199f8f26b6ce73bd2bb5722c8bf6e | [
0.996118426322937,
0.07908648997545242,
0.0001644803414819762,
0.0003855876566376537,
0.26476120948791504
] |
{
"id": 4,
"code_window": [
"\t\tif (indexOf < 0) {\n",
"\t\t\treturn false;\n",
"\t\t}\n",
"\n",
"\t\tlastIndexOf = indexOf;\n",
"\t\t\n",
"\t\tindex++;\n",
"\t}\n",
"\n",
"\treturn true;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "src/vs/base/common/scorer.ts",
"type": "replace",
"edit_start_line_idx": 118
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import winjs = require('vs/base/common/winjs.base');
import nls = require('vs/nls');
import platform = require('vs/base/common/platform');
import errors = require('vs/base/common/errors');
import paths = require('vs/base/common/paths');
import severity from 'vs/base/common/severity';
import lifecycle = require('vs/base/common/lifecycle');
import dom = require('vs/base/browser/dom');
import keyboard = require('vs/base/browser/keyboardEvent');
import mouse = require('vs/base/browser/mouseEvent');
import comparers = require('vs/base/common/comparers');
import actions = require('vs/base/common/actions');
import actionbar = require('vs/base/browser/ui/actionbar/actionbar');
import countbadge = require('vs/base/browser/ui/countBadge/countBadge');
import tree = require('vs/base/parts/tree/browser/tree');
import treednd = require('vs/base/parts/tree/browser/treeDnd');
import treedefaults = require('vs/base/parts/tree/browser/treeDefaults');
import actionsrenderer = require('vs/base/parts/tree/browser/actionsRenderer');
import git = require('vs/workbench/parts/git/common/git');
import gitmodel = require('vs/workbench/parts/git/common/gitModel');
import gitactions = require('vs/workbench/parts/git/browser/gitActions');
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IMessageService } from 'vs/platform/message/common/message';
import { CommonKeybindings } from 'vs/base/common/keyCodes';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import URI from 'vs/base/common/uri';
import IGitService = git.IGitService
function toReadablePath(path: string): string {
if (!platform.isWindows) {
return path;
}
return path.replace(/\//g, '\\');
}
var $ = dom.emmet;
export class ActionContainer implements lifecycle.IDisposable {
private cache: { [actionId:string]:actions.IAction; };
private instantiationService: IInstantiationService;
constructor(instantiationService: IInstantiationService) {
this.cache = <any> {};
this.instantiationService = instantiationService;
}
protected getAction(ctor: any, ...args: any[]): any {
var action = this.cache[ctor.ID];
if (!action) {
args.unshift(ctor);
action = this.cache[ctor.ID] = this.instantiationService.createInstance.apply(this.instantiationService, args);
}
return action;
}
public dispose(): void {
Object.keys(this.cache).forEach(k => {
this.cache[k].dispose();
});
this.cache = null;
}
}
export class DataSource implements tree.IDataSource {
public getId(tree: tree.ITree, element: any): string {
if (element instanceof gitmodel.StatusModel) {
return 'root';
} else if (element instanceof gitmodel.StatusGroup) {
var statusGroup = <git.IStatusGroup> element;
switch (statusGroup.getType()) {
case git.StatusType.INDEX: return 'index';
case git.StatusType.WORKING_TREE: return 'workingTree';
case git.StatusType.MERGE: return 'merge';
default: throw new Error('Invalid group type');
}
}
var status = <git.IFileStatus> element;
return status.getId();
}
public hasChildren(tree: tree.ITree, element: any): boolean {
if (element instanceof gitmodel.StatusModel) {
return true;
} else if (element instanceof gitmodel.StatusGroup) {
var statusGroup = <git.IStatusGroup> element;
return statusGroup.all().length > 0;
}
}
public getChildren(tree: tree.ITree, element: any): winjs.Promise {
if (element instanceof gitmodel.StatusModel) {
var model = <git.IStatusModel> element;
return winjs.Promise.as(model.getGroups());
} else if (element instanceof gitmodel.StatusGroup) {
var statusGroup = <git.IStatusGroup> element;
return winjs.Promise.as(statusGroup.all());
}
return winjs.Promise.as([]);
}
public getParent(tree: tree.ITree, element: any): winjs.Promise {
return winjs.Promise.as(null);
}
}
export class ActionProvider extends ActionContainer implements actionsrenderer.IActionProvider {
private gitService: git.IGitService;
constructor(@IInstantiationService instantiationService: IInstantiationService, @IGitService gitService: IGitService) {
super(instantiationService);
this.gitService = gitService;
}
public hasActions(tree: tree.ITree, element: any): boolean {
if (element instanceof gitmodel.FileStatus) {
return true;
} else if (element instanceof gitmodel.StatusGroup && (<git.IStatusGroup> element).all().length > 0) {
return true;
}
return false;
}
public getActions(tree: tree.ITree, element: any): winjs.TPromise<actions.IAction[]> {
if (element instanceof gitmodel.StatusGroup) {
return winjs.Promise.as(this.getActionsForGroupStatusType(element.getType()));
} else {
return winjs.Promise.as(this.getActionsForFileStatusType(element.getType()));
}
}
public getActionsForFileStatusType(statusType: git.StatusType): actions.IAction[] {
switch (statusType) {
case git.StatusType.INDEX:
return [this.getAction(gitactions.UnstageAction)];
case git.StatusType.WORKING_TREE:
return [this.getAction(gitactions.UndoAction), this.getAction(gitactions.StageAction)];
case git.StatusType.MERGE:
return [this.getAction(gitactions.StageAction)];
default:
return [];
}
}
public getActionsForGroupStatusType(statusType: git.StatusType): actions.IAction[] {
switch (statusType) {
case git.StatusType.INDEX:
return [this.getAction(gitactions.GlobalUnstageAction)];
case git.StatusType.WORKING_TREE:
return [this.getAction(gitactions.GlobalUndoAction), this.getAction(gitactions.GlobalStageAction)];
case git.StatusType.MERGE:
return [this.getAction(gitactions.StageAction)];
default:
return [];
}
}
public hasSecondaryActions(tree: tree.ITree, element: any): boolean {
return this.hasActions(tree, element);
}
public getSecondaryActions(tree: tree.ITree, element: any): winjs.TPromise<actions.IAction[]> {
return this.getActions(tree, element).then((actions: actions.IAction[]) => {
if (element instanceof gitmodel.FileStatus) {
var fileStatus = <gitmodel.FileStatus> element;
var status = fileStatus.getStatus();
actions.push(new actionbar.Separator());
if (status !== git.Status.DELETED && status !== git.Status.INDEX_DELETED) {
actions.push(this.getAction(gitactions.OpenFileAction));
}
actions.push(this.getAction(gitactions.OpenChangeAction));
}
actions.reverse();
return actions;
});
}
public getActionItem(tree: tree.ITree, element: any, action: actions.IAction): actionbar.IActionItem {
return null;
}
}
interface IFileStatusTemplateData {
root: HTMLElement;
status: HTMLElement;
name: HTMLElement;
folder: HTMLElement;
renameName: HTMLElement;
renameFolder: HTMLElement;
actionBar: actionbar.ActionBar;
}
interface IStatusGroupTemplateData {
root: HTMLElement;
count: countbadge.CountBadge;
actionBar: actionbar.ActionBar;
}
export class Renderer implements tree.IRenderer {
constructor(
private actionProvider:ActionProvider,
private actionRunner: actions.IActionRunner,
@IMessageService private messageService: IMessageService,
@IGitService private gitService: IGitService,
@IWorkspaceContextService private contextService: IWorkspaceContextService
) {
// noop
}
public getHeight(tree:tree.ITree, element:any): number {
return 22;
}
public getTemplateId(tree: tree.ITree, element: any): string {
if (element instanceof gitmodel.StatusGroup) {
switch (element.getType()) {
case git.StatusType.INDEX: return 'index';
case git.StatusType.WORKING_TREE: return 'workingTree';
case git.StatusType.MERGE: return 'merge';
}
}
if (element instanceof gitmodel.FileStatus) {
switch (element.getType()) {
case git.StatusType.INDEX: return 'file:index';
case git.StatusType.WORKING_TREE: return 'file:workingTree';
case git.StatusType.MERGE: return 'file:merge';
}
}
return null;
}
public renderTemplate(tree: tree.ITree, templateId: string, container: HTMLElement): any {
if (/^file:/.test(templateId)) {
return this.renderFileStatusTemplate(Renderer.templateIdToStatusType(templateId), container);
} else {
return this.renderStatusGroupTemplate(Renderer.templateIdToStatusType(templateId), container);
}
}
private renderStatusGroupTemplate(statusType: git.StatusType, container: HTMLElement): IStatusGroupTemplateData {
var data: IStatusGroupTemplateData = Object.create(null);
data.actionBar = new actionbar.ActionBar(container, { actionRunner: this.actionRunner });
data.actionBar.push(this.actionProvider.getActionsForGroupStatusType(statusType), { icon: true, label: false });
data.actionBar.addListener2('run', e => e.error && this.onError(e.error));
const wrapper = dom.append(container, $('.count-badge-wrapper'));
data.count = new countbadge.CountBadge(wrapper);
data.root = dom.append(container, $('.status-group'));
switch (statusType) {
case git.StatusType.INDEX: data.root.textContent = nls.localize('stagedChanges', "Staged Changes"); break;
case git.StatusType.WORKING_TREE: data.root.textContent = nls.localize('allChanges', "Changes"); break;
case git.StatusType.MERGE: data.root.textContent = nls.localize('mergeChanges', "Merge Changes"); break;
}
return data;
}
private renderFileStatusTemplate(statusType: git.StatusType, container: HTMLElement): IFileStatusTemplateData {
var data: IFileStatusTemplateData = Object.create(null);
data.actionBar = new actionbar.ActionBar(container, { actionRunner: this.actionRunner });
data.actionBar.push(this.actionProvider.getActionsForFileStatusType(statusType), { icon: true, label: false });
data.actionBar.addListener2('run', e => e.error && this.onError(e.error));
data.root = dom.append(container, $('.file-status'));
data.status = dom.append(data.root, $('span.status'));
data.name = dom.append(data.root, $('a.name.plain'));
data.folder = dom.append(data.root, $('span.folder'));
var rename = dom.append(data.root, $('span.rename'));
var arrow = dom.append(rename, $('span.rename-arrow'));
arrow.textContent = '←';
data.renameName = dom.append(rename, $('span.rename-name'));
data.renameFolder = dom.append(rename, $('span.rename-folder'));
return data;
}
public renderElement(tree: tree.ITree, element: any, templateId: string, templateData: any): void {
if (/^file:/.test(templateId)) {
this.renderFileStatus(tree, <git.IFileStatus> element, templateData);
} else {
Renderer.renderStatusGroup(<git.IStatusGroup> element, templateData);
}
}
private static renderStatusGroup(statusGroup: git.IStatusGroup, data: IStatusGroupTemplateData): void {
data.actionBar.context = statusGroup;
data.count.setCount(statusGroup.all().length);
}
private renderFileStatus(tree: tree.ITree, fileStatus: git.IFileStatus, data: IFileStatusTemplateData): void {
data.actionBar.context = {
tree: tree,
fileStatus: fileStatus
};
const repositoryRoot = this.gitService.getModel().getRepositoryRoot();
const workspaceRoot = this.contextService.getWorkspace().resource.fsPath;
const status = fileStatus.getStatus();
const renamePath = fileStatus.getRename();
const path = fileStatus.getPath();
const lastSlashIndex = path.lastIndexOf('/');
const name = lastSlashIndex === -1 ? path : path.substr(lastSlashIndex + 1, path.length);
const folder = (lastSlashIndex === -1 ? '' : path.substr(0, lastSlashIndex));
data.root.className = 'file-status ' + Renderer.statusToClass(status);
data.status.textContent = Renderer.statusToChar(status);
data.status.title = Renderer.statusToTitle(status);
const resource = URI.file(paths.normalize(paths.join(repositoryRoot, path)));
let isInWorkspace = paths.isEqualOrParent(resource.fsPath, workspaceRoot);
let rename = '';
let renameFolder = '';
if (renamePath) {
const renameLastSlashIndex = renamePath.lastIndexOf('/');
rename = renameLastSlashIndex === -1 ? renamePath : renamePath.substr(renameLastSlashIndex + 1, renamePath.length);
renameFolder = (renameLastSlashIndex === -1 ? '' : renamePath.substr(0, renameLastSlashIndex));
data.renameName.textContent = name;
data.renameFolder.textContent = folder;
const resource = URI.file(paths.normalize(paths.join(repositoryRoot, renamePath)));
isInWorkspace = paths.isEqualOrParent(resource.fsPath, workspaceRoot)
}
if (isInWorkspace) {
data.root.title = '';
} else {
data.root.title = nls.localize('outsideOfWorkspace', "This file is located outside the current workspace.");
data.root.className += ' out-of-workspace';
}
data.name.textContent = rename || name;
data.folder.textContent = toReadablePath(renameFolder || folder);
}
public disposeTemplate(tree: tree.ITree, templateId: string, templateData: any): void {
if (/^file:/.test(templateId)) {
Renderer.disposeFileStatusTemplate(<IFileStatusTemplateData> templateData);
}
}
private static disposeFileStatusTemplate(templateData: IFileStatusTemplateData): void {
templateData.actionBar.dispose();
}
private static statusToChar(status: git.Status): string {
switch (status) {
case git.Status.INDEX_MODIFIED: return nls.localize('modified-char', "M");
case git.Status.MODIFIED: return nls.localize('modified-char', "M");
case git.Status.INDEX_ADDED: return nls.localize('added-char', "A");
case git.Status.INDEX_DELETED: return nls.localize('deleted-char', "D");
case git.Status.DELETED: return nls.localize('deleted-char', "D");
case git.Status.INDEX_RENAMED: return nls.localize('renamed-char', "R");
case git.Status.INDEX_COPIED: return nls.localize('copied-char', "C");
case git.Status.UNTRACKED: return nls.localize('untracked-char', "U");
case git.Status.IGNORED: return nls.localize('ignored-char', "!");
case git.Status.BOTH_DELETED: return nls.localize('deleted-char', "D");
case git.Status.ADDED_BY_US: return nls.localize('added-char', "A");
case git.Status.DELETED_BY_THEM: return nls.localize('deleted-char', "D");
case git.Status.ADDED_BY_THEM: return nls.localize('added-char', "A");
case git.Status.DELETED_BY_US: return nls.localize('deleted-char', "D");
case git.Status.BOTH_ADDED: return nls.localize('added-char', "A");
case git.Status.BOTH_MODIFIED: return nls.localize('modified-char', "M");
default: return '';
}
}
private static statusToTitle(status: git.Status): string {
switch (status) {
case git.Status.INDEX_MODIFIED: return nls.localize('title-index-modified', "Modified in index");
case git.Status.MODIFIED: return nls.localize('title-modified', "Modified");
case git.Status.INDEX_ADDED: return nls.localize('title-index-added', "Added to index");
case git.Status.INDEX_DELETED: return nls.localize('title-index-deleted', "Deleted in index");
case git.Status.DELETED: return nls.localize('title-deleted', "Deleted");
case git.Status.INDEX_RENAMED: return nls.localize('title-index-renamed', "Renamed in index");
case git.Status.INDEX_COPIED: return nls.localize('title-index-copied', "Copied in index");
case git.Status.UNTRACKED: return nls.localize('title-untracked', "Untracked");
case git.Status.IGNORED: return nls.localize('title-ignored', "Ignored");
case git.Status.BOTH_DELETED: return nls.localize('title-conflict-both-deleted', "Conflict: both deleted");
case git.Status.ADDED_BY_US: return nls.localize('title-conflict-added-by-us', "Conflict: added by us");
case git.Status.DELETED_BY_THEM: return nls.localize('title-conflict-deleted-by-them', "Conflict: deleted by them");
case git.Status.ADDED_BY_THEM: return nls.localize('title-conflict-added-by-them', "Conflict: added by them");
case git.Status.DELETED_BY_US: return nls.localize('title-conflict-deleted-by-us', "Conflict: deleted by us");
case git.Status.BOTH_ADDED: return nls.localize('title-conflict-both-added', "Conflict: both added");
case git.Status.BOTH_MODIFIED: return nls.localize('title-conflict-both-modified', "Conflict: both modified");
default: return '';
}
}
private static statusToClass(status: git.Status): string {
switch (status) {
case git.Status.INDEX_MODIFIED: return 'modified';
case git.Status.MODIFIED: return 'modified';
case git.Status.INDEX_ADDED: return 'added';
case git.Status.INDEX_DELETED: return 'deleted';
case git.Status.DELETED: return 'deleted';
case git.Status.INDEX_RENAMED: return 'renamed';
case git.Status.INDEX_COPIED: return 'copied';
case git.Status.UNTRACKED: return 'untracked';
case git.Status.IGNORED: return 'ignored';
case git.Status.BOTH_DELETED: return 'conflict both-deleted';
case git.Status.ADDED_BY_US: return 'conflict added-by-us';
case git.Status.DELETED_BY_THEM: return 'conflict deleted-by-them';
case git.Status.ADDED_BY_THEM: return 'conflict added-by-them';
case git.Status.DELETED_BY_US: return 'conflict deleted-by-us';
case git.Status.BOTH_ADDED: return 'conflict both-added';
case git.Status.BOTH_MODIFIED: return 'conflict both-modified';
default: return '';
}
}
private static templateIdToStatusType(templateId: string): git.StatusType {
if (/index$/.test(templateId)) {
return git.StatusType.INDEX;
} else if (/workingTree$/.test(templateId)) {
return git.StatusType.WORKING_TREE;
} else {
return git.StatusType.MERGE;
}
}
private onError(error: any): void {
this.messageService.show(severity.Error, error);
}
}
export class Filter implements tree.IFilter {
public isVisible(tree: tree.ITree, element: any): boolean {
if (element instanceof gitmodel.StatusGroup) {
var statusGroup = <git.IStatusGroup> element;
switch (statusGroup.getType()) {
case git.StatusType.INDEX:
case git.StatusType.MERGE:
return statusGroup.all().length > 0;
case git.StatusType.WORKING_TREE:
return true;
}
}
return true;
}
}
export class Sorter implements tree.ISorter {
public compare(tree: tree.ITree, element: any, otherElement: any): number {
if (!(element instanceof gitmodel.FileStatus && otherElement instanceof gitmodel.FileStatus)) {
return 0;
}
return Sorter.compareStatus(element, otherElement);
}
private static compareStatus(element: git.IFileStatus, otherElement: git.IFileStatus): number {
var one = element.getPathComponents();
var other = otherElement.getPathComponents();
var lastOne = one.length - 1;
var lastOther = other.length - 1;
var endOne: boolean, endOther: boolean, onePart: string, otherPart: string;
for (var i = 0; ; i++) {
endOne = lastOne === i;
endOther = lastOther === i;
if (endOne && endOther) {
return comparers.compareFileNames(one[i], other[i]);
} else if (endOne) {
return -1;
} else if (endOther) {
return 1;
} else if ((onePart = one[i].toLowerCase()) !== (otherPart = other[i].toLowerCase())) {
return onePart < otherPart ? -1 : 1;
}
}
}
}
export class DragAndDrop extends ActionContainer implements tree.IDragAndDrop {
private gitService: git.IGitService;
private messageService: IMessageService;
constructor(@IInstantiationService instantiationService: IInstantiationService, @IGitService gitService: IGitService, @IMessageService messageService: IMessageService) {
super(instantiationService);
this.gitService = gitService;
this.messageService = messageService;
}
public getDragURI(tree: tree.ITree, element: any): string {
if (element instanceof gitmodel.StatusGroup) {
var statusGroup = <git.IStatusGroup> element;
return 'git:' + statusGroup.getType();
} else if (element instanceof gitmodel.FileStatus) {
var status = <git.IFileStatus> element;
return 'git:' + status.getType() + ':' + status.getPath();
}
return null;
}
public onDragStart(tree: tree.ITree, data: tree.IDragAndDropData, originalEvent:mouse.DragMouseEvent):void {
// no-op
}
public onDragOver(_tree: tree.ITree, data: tree.IDragAndDropData, targetElement: any, originalEvent:mouse.DragMouseEvent): tree.IDragOverReaction {
if (!this.gitService.isIdle()) {
return tree.DRAG_OVER_REJECT;
}
if (!(data instanceof treednd.ElementsDragAndDropData)) {
return tree.DRAG_OVER_REJECT;
}
var elements: any[] = data.getData();
var element = elements[0];
if (element instanceof gitmodel.StatusGroup) {
var statusGroup = <git.IStatusGroup> element;
return this.onDrag(targetElement, statusGroup.getType());
} else if (element instanceof gitmodel.FileStatus) {
var status = <git.IFileStatus> element;
return this.onDrag(targetElement, status.getType());
} else {
return tree.DRAG_OVER_REJECT;
}
}
private onDrag(targetElement: any, type: git.StatusType): tree.IDragOverReaction {
if (type === git.StatusType.WORKING_TREE) {
return this.onDragWorkingTree(targetElement);
} else if (type === git.StatusType.INDEX) {
return this.onDragIndex(targetElement);
} else if (type === git.StatusType.MERGE) {
return this.onDragMerge(targetElement);
} else {
return tree.DRAG_OVER_REJECT;
}
}
private onDragWorkingTree(targetElement: any): tree.IDragOverReaction {
if (targetElement instanceof gitmodel.StatusGroup) {
var targetStatusGroup = <git.IStatusGroup> targetElement;
return targetStatusGroup.getType() === git.StatusType.INDEX ? tree.DRAG_OVER_ACCEPT_BUBBLE_DOWN : tree.DRAG_OVER_REJECT;
} else if (targetElement instanceof gitmodel.FileStatus) {
var targetStatus = <git.IFileStatus> targetElement;
return targetStatus.getType() === git.StatusType.INDEX ? tree.DRAG_OVER_ACCEPT_BUBBLE_UP : tree.DRAG_OVER_REJECT;
} else {
return tree.DRAG_OVER_REJECT;
}
}
private onDragIndex(targetElement: any): tree.IDragOverReaction {
if (targetElement instanceof gitmodel.StatusGroup) {
var targetStatusGroup = <git.IStatusGroup> targetElement;
return targetStatusGroup.getType() === git.StatusType.WORKING_TREE ? tree.DRAG_OVER_ACCEPT_BUBBLE_DOWN : tree.DRAG_OVER_REJECT;
} else if (targetElement instanceof gitmodel.FileStatus) {
var targetStatus = <git.IFileStatus> targetElement;
return targetStatus.getType() === git.StatusType.WORKING_TREE ? tree.DRAG_OVER_ACCEPT_BUBBLE_UP : tree.DRAG_OVER_REJECT;
} else {
return tree.DRAG_OVER_REJECT;
}
}
private onDragMerge(targetElement: any): tree.IDragOverReaction {
if (targetElement instanceof gitmodel.StatusGroup) {
var targetStatusGroup = <git.IStatusGroup> targetElement;
return targetStatusGroup.getType() === git.StatusType.INDEX ? tree.DRAG_OVER_ACCEPT_BUBBLE_DOWN : tree.DRAG_OVER_REJECT;
} else if (targetElement instanceof gitmodel.FileStatus) {
var targetStatus = <git.IFileStatus> targetElement;
return targetStatus.getType() === git.StatusType.INDEX ? tree.DRAG_OVER_ACCEPT_BUBBLE_UP : tree.DRAG_OVER_REJECT;
} else {
return tree.DRAG_OVER_REJECT;
}
}
public drop(tree: tree.ITree, data: tree.IDragAndDropData, targetElement: any, originalEvent:mouse.DragMouseEvent): void {
var elements: any[] = data.getData();
var element = elements[0];
var files: git.IFileStatus[];
if (element instanceof gitmodel.StatusGroup) {
files = (<git.IStatusGroup> element).all();
// } else if (element instanceof gitmodel.FileStatus) {
// files = [ element ];
} else {
files = elements;
// throw new Error('Invalid drag and drop data.');
}
var targetGroup = <git.IStatusGroup> targetElement;
// Add files to index
if (targetGroup.getType() === git.StatusType.INDEX) {
this.getAction(gitactions.StageAction).run(files).done(null, (e:Error) => this.onError(e));
}
// Remove files from index
if (targetGroup.getType() === git.StatusType.WORKING_TREE) {
this.getAction(gitactions.UnstageAction).run(files).done(null, (e:Error) => this.onError(e));
}
}
private onError(error: any): void {
this.messageService.show(severity.Error, error);
}
}
export class Controller extends treedefaults.DefaultController {
private contextMenuService:IContextMenuService;
private actionProvider:actionsrenderer.IActionProvider;
constructor(actionProvider:actionsrenderer.IActionProvider, @IContextMenuService contextMenuService: IContextMenuService) {
super({ clickBehavior: treedefaults.ClickBehavior.ON_MOUSE_UP });
this.actionProvider = actionProvider;
this.contextMenuService = contextMenuService;
this.downKeyBindingDispatcher.set(CommonKeybindings.SHIFT_UP_ARROW, this.onUp.bind(this));
this.downKeyBindingDispatcher.set(CommonKeybindings.SHIFT_DOWN_ARROW, this.onDown.bind(this));
this.downKeyBindingDispatcher.set(CommonKeybindings.SHIFT_PAGE_UP, this.onPageUp.bind(this));
this.downKeyBindingDispatcher.set(CommonKeybindings.SHIFT_PAGE_DOWN, this.onPageDown.bind(this));
}
protected onLeftClick(tree: tree.ITree, element: any, event: mouse.StandardMouseEvent): boolean {
// Status group should never get selected nor expanded/collapsed
if (element instanceof gitmodel.StatusGroup) {
event.preventDefault();
event.stopPropagation();
return true;
}
if (event.shiftKey) {
var focus = tree.getFocus();
if (!(focus instanceof gitmodel.FileStatus) || !(element instanceof gitmodel.FileStatus)) {
return;
}
var focusStatus = <gitmodel.FileStatus> focus;
var elementStatus = <gitmodel.FileStatus> element;
if (focusStatus.getType() !== elementStatus.getType()) {
return;
}
if (this.canSelect(tree, element)) {
tree.setFocus(element);
if (tree.isSelected(element)) {
tree.deselectRange(focusStatus, elementStatus);
} else {
tree.selectRange(focusStatus, elementStatus);
}
}
return;
}
tree.setFocus(element);
if (platform.isMacintosh ? event.metaKey : event.ctrlKey) {
if (this.canSelect(tree, element)) {
tree.toggleSelection(element, { origin: 'mouse', originalEvent: event });
}
return;
}
return super.onLeftClick(tree, element, event);
}
protected onEnter(tree: tree.ITree, event: keyboard.StandardKeyboardEvent): boolean {
var element = tree.getFocus();
// Status group should never get selected nor expanded/collapsed
if (element instanceof gitmodel.StatusGroup) {
event.preventDefault();
event.stopPropagation();
return true;
}
return super.onEnter(tree, event);
}
protected onSpace(tree: tree.ITree, event: keyboard.StandardKeyboardEvent):boolean {
var focus = tree.getFocus();
if (!focus) {
event.preventDefault();
event.stopPropagation();
return true;
}
if (!this.canSelect(tree, focus)) {
return false;
}
tree.toggleSelection(focus, { origin: 'keyboard', originalEvent: event });
event.preventDefault();
event.stopPropagation();
return true;
}
public onContextMenu(tree:tree.ITree, element:any, event:tree.ContextMenuEvent):boolean {
if (event.target && event.target.tagName && event.target.tagName.toLowerCase() === 'input') {
return false;
}
event.preventDefault();
event.stopPropagation();
tree.setFocus(element);
if (this.actionProvider.hasSecondaryActions(tree, element)) {
var anchor = { x: event.posx + 1, y: event.posy };
var context = {
selection: tree.getSelection(),
focus: element
};
this.contextMenuService.showContextMenu({
getAnchor: () => anchor,
getActions: () => this.actionProvider.getSecondaryActions(tree, element),
getActionItem: this.actionProvider.getActionItem.bind(this.actionProvider, tree, element),
getActionsContext: () => context,
onHide: (wasCancelled?:boolean) => {
if (wasCancelled) {
tree.DOMFocus();
}
}
});
return true;
}
return false;
}
protected onLeft(tree: tree.ITree, event:keyboard.StandardKeyboardEvent):boolean {
return true;
}
protected onRight(tree: tree.ITree, event:keyboard.StandardKeyboardEvent):boolean {
return true;
}
protected onUp(tree:tree.ITree, event:keyboard.StandardKeyboardEvent):boolean {
var oldFocus = tree.getFocus();
var base = super.onUp(tree, event);
if (!base || !event.shiftKey) {
return false;
}
return this.shiftSelect(tree, oldFocus, event);
}
protected onPageUp(tree:tree.ITree, event:keyboard.StandardKeyboardEvent):boolean {
var oldFocus = tree.getFocus();
var base = super.onPageUp(tree, event);
if (!base || !event.shiftKey) {
return false;
}
return this.shiftSelect(tree, oldFocus, event);
}
protected onDown(tree:tree.ITree, event:keyboard.StandardKeyboardEvent):boolean {
var oldFocus = tree.getFocus();
var base = super.onDown(tree, event);
if (!base || !event.shiftKey) {
return false;
}
return this.shiftSelect(tree, oldFocus, event);
}
protected onPageDown(tree:tree.ITree, event:keyboard.StandardKeyboardEvent):boolean {
var oldFocus = tree.getFocus();
var base = super.onPageDown(tree, event);
if (!base || !event.shiftKey) {
return false;
}
return this.shiftSelect(tree, oldFocus, event);
}
private canSelect(tree: tree.ITree, ...elements: any[]): boolean {
if (elements.some(e => e instanceof gitmodel.StatusGroup || e instanceof gitmodel.StatusModel)) {
return false;
}
return elements.every(e => {
var first = <gitmodel.FileStatus> tree.getSelection()[0];
var clicked = <gitmodel.FileStatus> e;
return !first || (first.getType() === clicked.getType());
});
}
private shiftSelect(tree: tree.ITree, oldFocus: any, event:keyboard.StandardKeyboardEvent): boolean {
var payload = { origin: 'keyboard', originalEvent: event };
var focus = tree.getFocus();
if (focus === oldFocus) {
return false;
}
var oldFocusIsSelected = tree.isSelected(oldFocus);
var focusIsSelected = tree.isSelected(focus);
if (oldFocusIsSelected && focusIsSelected) {
tree.deselectRange(focus, oldFocus, payload);
} else if (!oldFocusIsSelected && !focusIsSelected) {
if (this.canSelect(tree, oldFocus, focus)) {
tree.selectRange(focus, oldFocus, payload);
}
} else if (oldFocusIsSelected) {
if (this.canSelect(tree, focus)) {
tree.selectRange(focus, oldFocus, payload);
}
} else {
tree.deselectRange(focus, oldFocus, payload);
}
return true;
}
}
| src/vs/workbench/parts/git/browser/views/changes/changesViewer.ts | 0 | https://github.com/microsoft/vscode/commit/29303185aa7199f8f26b6ce73bd2bb5722c8bf6e | [
0.011404777877032757,
0.000349558045854792,
0.00016305544704664499,
0.00016943624359555542,
0.0012523201294243336
] |
{
"id": 4,
"code_window": [
"\t\tif (indexOf < 0) {\n",
"\t\t\treturn false;\n",
"\t\t}\n",
"\n",
"\t\tlastIndexOf = indexOf;\n",
"\t\t\n",
"\t\tindex++;\n",
"\t}\n",
"\n",
"\treturn true;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "src/vs/base/common/scorer.ts",
"type": "replace",
"edit_start_line_idx": 118
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import nls = require('vs/nls');
import 'vs/base/common/async';
import 'vs/base/node/stdFork';
import 'vs/languages/lib/common/wireProtocol';
import pfs = require('vs/base/node/pfs');
import URI from 'vs/base/common/uri';
import {TPromise} from 'vs/base/common/winjs.base';
import paths = require('vs/base/common/paths');
import {IPluginService, IPluginDescription} from 'vs/platform/plugins/common/plugins';
import {PluginsRegistry, PluginsMessageCollector, IPluginsMessageCollector} from 'vs/platform/plugins/common/pluginsRegistry';
import {ExtHostAPIImplementation} from 'vs/workbench/api/node/extHost.api.impl';
import { create as createIPC, IPluginsIPC } from 'vs/platform/plugins/common/ipcRemoteCom';
import {ExtHostModelService} from 'vs/workbench/api/node/extHostDocuments';
import {IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import InstantiationService = require('vs/platform/instantiation/common/instantiationService');
import {PluginHostPluginService} from 'vs/platform/plugins/common/nativePluginService';
import {PluginHostThreadService} from 'vs/platform/thread/common/pluginHostThreadService';
import marshalling = require('vs/base/common/marshalling');
import {ExtHostTelemetryService} from 'vs/workbench/api/node/extHostTelemetry';
import {BaseRequestService} from 'vs/platform/request/common/baseRequestService';
import {BaseWorkspaceContextService} from 'vs/platform/workspace/common/baseWorkspaceContextService';
import {ModeServiceImpl} from 'vs/editor/common/services/modeServiceImpl';
import {PluginScanner} from 'vs/workbench/node/extensionPoints';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { Client } from 'vs/base/node/service.net';
import { IExtensionsService } from 'vs/workbench/parts/extensions/common/extensions';
import { ExtensionsService } from 'vs/workbench/parts/extensions/node/extensionsService';
const DIRNAME = URI.parse(require.toUrl('./')).fsPath;
const BASE_PATH = paths.normalize(paths.join(DIRNAME, '../../../..'));
const BUILTIN_PLUGINS_PATH = paths.join(BASE_PATH, 'extensions');
export interface IInitData {
threadService: any;
contextService: {
workspace: any;
configuration: any;
options: any;
};
}
const nativeExit = process.exit.bind(process);
process.exit = function() {
const err = new Error('An extension called process.exit() and this was prevented.');
console.warn((<any>err).stack);
};
export function exit(code?: number) {
nativeExit(code);
}
export function createServices(remoteCom: IPluginsIPC, initData: IInitData, sharedProcessClient: Client): IInstantiationService {
// the init data is not demarshalled
initData = marshalling.deserialize(initData);
let contextService = new BaseWorkspaceContextService(initData.contextService.workspace, initData.contextService.configuration, initData.contextService.options);
let threadService = new PluginHostThreadService(remoteCom);
threadService.setInstantiationService(InstantiationService.create({ threadService: threadService }));
let telemetryServiceInstance = new ExtHostTelemetryService(threadService);
let requestService = new BaseRequestService(contextService, telemetryServiceInstance);
let modelService = threadService.getRemotable(ExtHostModelService);
let pluginService = new PluginHostPluginService(threadService);
let modeService = new ModeServiceImpl(threadService, pluginService);
let _services: any = {
contextService: contextService,
requestService: requestService,
modelService: modelService,
threadService: threadService,
modeService: modeService,
pluginService: pluginService,
telemetryService: ExtHostTelemetryService
};
let instantiationService = InstantiationService.create(_services);
threadService.setInstantiationService(instantiationService);
// Create the monaco API
instantiationService.createInstance(ExtHostAPIImplementation);
// Connect to shared process services
instantiationService.addSingleton(IExtensionsService, sharedProcessClient.getService<IExtensionsService>('ExtensionService', ExtensionsService));
return instantiationService;
}
interface ITestRunner {
run(testsRoot: string, clb: (error: Error, failures?: number) => void): void;
}
export class PluginHostMain {
private _isTerminating: boolean;
constructor(
@IWorkspaceContextService private contextService: IWorkspaceContextService,
@IPluginService private pluginService: IPluginService,
@IInstantiationService instantiationService: IInstantiationService
) {
this._isTerminating = false;
}
public start(): TPromise<void> {
return this.readPlugins();
}
public terminate(): void {
if (this._isTerminating) {
// we are already shutting down...
return;
}
this._isTerminating = true;
try {
let allExtensions = PluginsRegistry.getAllPluginDescriptions();
let allExtensionsIds = allExtensions.map(ext => ext.id);
let activatedExtensions = allExtensionsIds.filter(id => this.pluginService.isActivated(id));
activatedExtensions.forEach((extensionId) => {
this.pluginService.deactivate(extensionId);
});
} catch (err) {
// TODO: write to log once we have one
}
// Give extensions 1 second to wrap up any async dispose, then exit
setTimeout(() => {
exit();
}, 1000);
}
private readPlugins(): TPromise<void> {
let collector = new PluginsMessageCollector();
let env = this.contextService.getConfiguration().env;
return PluginHostMain.scanPlugins(collector, BUILTIN_PLUGINS_PATH, !env.disablePlugins ? env.userPluginsHome : void 0, !env.disablePlugins ? env.pluginDevelopmentPath : void 0, env.version)
.then(null, err => {
collector.error('', err);
return [];
})
.then(extensions => {
// Register & Signal done
PluginsRegistry.registerPlugins(extensions);
this.pluginService.registrationDone(collector.getMessages());
})
.then(() => this.handleEagerPlugins())
.then(() => this.handlePluginTests());
}
private static scanPlugins(collector: IPluginsMessageCollector, builtinPluginsPath: string, userInstallPath: string, pluginDevelopmentPath: string, version: string): TPromise<IPluginDescription[]> {
const builtinPlugins = PluginScanner.scanPlugins(version, collector, builtinPluginsPath, true);
const userPlugins = !userInstallPath ? TPromise.as([]) : PluginScanner.scanPlugins(version, collector, userInstallPath, false);
const developedPlugins = !pluginDevelopmentPath ? TPromise.as([]) : PluginScanner.scanOneOrMultiplePlugins(version, collector, pluginDevelopmentPath, false);
return TPromise.join([builtinPlugins, userPlugins, developedPlugins]).then((_: IPluginDescription[][]) => {
let builtinPlugins = _[0];
let userPlugins = _[1];
let extensionDevPlugins = _[2];
let resultingPluginsMap: { [pluginName: string]: IPluginDescription; } = {};
builtinPlugins.forEach((builtinPlugin) => {
resultingPluginsMap[builtinPlugin.id] = builtinPlugin;
});
userPlugins.forEach((userPlugin) => {
if (resultingPluginsMap.hasOwnProperty(userPlugin.id)) {
collector.warn(userPlugin.extensionFolderPath, 'Overwriting extension ' + resultingPluginsMap[userPlugin.id].extensionFolderPath + ' with ' + userPlugin.extensionFolderPath);
}
resultingPluginsMap[userPlugin.id] = userPlugin;
});
extensionDevPlugins.forEach(extensionDevPlugin => {
collector.info('', 'Loading development extension at ' + extensionDevPlugin.extensionFolderPath);
if (resultingPluginsMap.hasOwnProperty(extensionDevPlugin.id)) {
collector.warn(extensionDevPlugin.extensionFolderPath, 'Overwriting extension ' + resultingPluginsMap[extensionDevPlugin.id].extensionFolderPath + ' with ' + extensionDevPlugin.extensionFolderPath);
}
resultingPluginsMap[extensionDevPlugin.id] = extensionDevPlugin;
});
return Object.keys(resultingPluginsMap).map(name => resultingPluginsMap[name]);
});
}
// Handle "eager" activation plugins
private handleEagerPlugins(): TPromise<void> {
this.pluginService.activateByEvent('*').then(null, (err) => {
console.error(err);
});
return this.handleWorkspaceContainsEagerPlugins();
}
private handleWorkspaceContainsEagerPlugins(): TPromise<void> {
let workspace = this.contextService.getWorkspace();
if (!workspace || !workspace.resource) {
return TPromise.as(null);
}
let folderPath = workspace.resource.fsPath;
let desiredFilesMap: {
[filename: string]: boolean;
} = {};
PluginsRegistry.getAllPluginDescriptions().forEach((desc) => {
let activationEvents = desc.activationEvents;
if (!activationEvents) {
return;
}
for (let i = 0; i < activationEvents.length; i++) {
if (/^workspaceContains:/.test(activationEvents[i])) {
let fileName = activationEvents[i].substr('workspaceContains:'.length);
desiredFilesMap[fileName] = true;
}
}
});
return TPromise.join(
Object.keys(desiredFilesMap).map(
(fileName) => pfs.fileExistsWithResult(paths.join(folderPath, fileName), fileName)
)
).then((fileNames: string[]) => {
fileNames.forEach((existingFileName) => {
if (!existingFileName) {
return;
}
let activationEvent = 'workspaceContains:' + existingFileName;
this.pluginService.activateByEvent(activationEvent).then(null, (err) => {
console.error(err);
});
});
});
}
private handlePluginTests(): TPromise<void> {
let env = this.contextService.getConfiguration().env;
if (!env.pluginTestsPath || !env.pluginDevelopmentPath) {
return TPromise.as(null);
}
// Require the test runner via node require from the provided path
let testRunner: ITestRunner;
let requireError: Error;
try {
testRunner = <any>require.__$__nodeRequire(env.pluginTestsPath);
} catch (error) {
requireError = error;
}
// Execute the runner if it follows our spec
if (testRunner && typeof testRunner.run === 'function') {
return new TPromise<void>((c, e) => {
testRunner.run(env.pluginTestsPath, (error, failures) => {
if (error) {
e(error.toString());
} else {
c(null);
}
// after tests have run, we shutdown the host
this.gracefulExit(failures && failures > 0 ? 1 /* ERROR */ : 0 /* OK */);
});
});
}
// Otherwise make sure to shutdown anyway even in case of an error
else {
this.gracefulExit(1 /* ERROR */);
}
return TPromise.wrapError<void>(requireError ? requireError.toString() : nls.localize('pluginTestError', "Path {0} does not point to a valid extension test runner.", env.pluginTestsPath));
}
private gracefulExit(code: number): void {
// to give the PH process a chance to flush any outstanding console
// messages to the main process, we delay the exit() by some time
setTimeout(() => exit(code), 500);
}
} | src/vs/workbench/node/pluginHostMain.ts | 0 | https://github.com/microsoft/vscode/commit/29303185aa7199f8f26b6ce73bd2bb5722c8bf6e | [
0.0006998325698077679,
0.00018660836212802678,
0.0001637945242691785,
0.00016815272101666778,
0.00009702699026092887
] |
{
"id": 4,
"code_window": [
"\t\tif (indexOf < 0) {\n",
"\t\t\treturn false;\n",
"\t\t}\n",
"\n",
"\t\tlastIndexOf = indexOf;\n",
"\t\t\n",
"\t\tindex++;\n",
"\t}\n",
"\n",
"\treturn true;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "src/vs/base/common/scorer.ts",
"type": "replace",
"edit_start_line_idx": 118
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import {EventEmitter} from 'vs/base/common/eventEmitter';
import types = require('vs/base/common/types');
import errors = require('vs/base/common/errors');
import strings = require('vs/base/common/strings');
import {IStorageService, StorageScope, StorageEvent, StorageEventType} from 'vs/platform/storage/common/storage';
import {IWorkspaceContextService, IWorkspace} from 'vs/platform/workspace/common/workspace';
// Browser localStorage interface
export interface IStorage {
length: number;
key(index: number): string;
clear(): void;
setItem(key: string, value: any): void;
getItem(key: string): string;
removeItem(key: string): void;
}
export class Storage extends EventEmitter implements IStorageService {
public serviceId = IStorageService;
private static COMMON_PREFIX = 'storage://';
private static GLOBAL_PREFIX = Storage.COMMON_PREFIX + 'global/';
private static WORKSPACE_PREFIX = Storage.COMMON_PREFIX + 'workspace/';
private static WORKSPACE_IDENTIFIER = 'workspaceIdentifier';
private static NO_WORKSPACE_IDENTIFIER = '__$noWorkspace__';
private workspaceStorage: IStorage;
private globalStorage: IStorage;
private toUnbind: { (): void; }[];
private workspaceKey: string;
constructor(contextService: IWorkspaceContextService, globalStorage: IStorage, workspaceStorage = globalStorage) {
super();
let workspace = contextService.getWorkspace();
this.globalStorage = globalStorage;
this.workspaceStorage = workspaceStorage;
this.toUnbind = [];
// Calculate workspace storage key
this.workspaceKey = this.getWorkspaceKey(workspace);
// Make sure to delete all workspace storage if the workspace has been recreated meanwhile
let workspaceUniqueId: number = workspace ? workspace.uid : null;
if (types.isNumber(workspaceUniqueId)) {
this.cleanupWorkspaceScope(workspaceUniqueId, workspace.name);
}
}
private getWorkspaceKey(workspace?: IWorkspace): string {
let workspaceUri: string = null;
if (workspace && workspace.resource) {
workspaceUri = workspace.resource.toString();
}
return workspaceUri ? this.calculateWorkspaceKey(workspaceUri) : Storage.NO_WORKSPACE_IDENTIFIER;
}
private calculateWorkspaceKey(workspaceUrl: string): string {
let root = 'file:///';
let index = workspaceUrl.indexOf(root);
if (index === 0) {
return strings.rtrim(workspaceUrl.substr(root.length), '/') + '/';
}
return workspaceUrl;
}
private cleanupWorkspaceScope(workspaceId: number, workspaceName: string): void {
// Get stored identifier from storage
let id = this.getInteger(Storage.WORKSPACE_IDENTIFIER, StorageScope.WORKSPACE);
// If identifier differs, assume the workspace got recreated and thus clean all storage for this workspace
if (types.isNumber(id) && workspaceId !== id) {
let keyPrefix = this.toStorageKey('', StorageScope.WORKSPACE);
let toDelete: string[] = [];
let length = this.workspaceStorage.length;
for (let i = 0; i < length; i++) {
let key = this.workspaceStorage.key(i);
if (key.indexOf(Storage.WORKSPACE_PREFIX) < 0) {
continue; // ignore stored things that don't belong to storage service or are defined globally
}
// Check for match on prefix
if (key.indexOf(keyPrefix) === 0) {
toDelete.push(key);
}
}
if (toDelete.length > 0) {
console.warn('Clearing previous version of local storage for workspace ', workspaceName);
}
// Run the delete
toDelete.forEach((keyToDelete) => {
this.workspaceStorage.removeItem(keyToDelete);
});
}
// Store workspace identifier now
if (workspaceId !== id) {
this.store(Storage.WORKSPACE_IDENTIFIER, workspaceId, StorageScope.WORKSPACE);
}
}
public clear(): void {
this.globalStorage.clear();
this.workspaceStorage.clear();
}
public store(key: string, value: any, scope = StorageScope.GLOBAL): void {
let storage = (scope === StorageScope.GLOBAL) ? this.globalStorage : this.workspaceStorage;
if (types.isUndefinedOrNull(value)) {
this.remove(key, scope); // we cannot store null or undefined, in that case we remove the key
return;
}
let storageKey = this.toStorageKey(key, scope);
let before = storage.getItem(storageKey);
let after = value.toString();
// Store
try {
storage.setItem(storageKey, value);
} catch (error) {
errors.onUnexpectedError(error);
}
// Emit Event
if (before !== after) {
this.emit(StorageEventType.STORAGE, new StorageEvent(key, before, after));
}
}
public get(key: string, scope = StorageScope.GLOBAL, defaultValue?: any): string {
let storage = (scope === StorageScope.GLOBAL) ? this.globalStorage : this.workspaceStorage;
let value = storage.getItem(this.toStorageKey(key, scope));
if (types.isUndefinedOrNull(value)) {
return defaultValue;
}
return value;
}
public remove(key: string, scope = StorageScope.GLOBAL): void {
let storage = (scope === StorageScope.GLOBAL) ? this.globalStorage : this.workspaceStorage;
let storageKey = this.toStorageKey(key, scope);
let before = storage.getItem(storageKey);
let after: any = null;
// Remove
storage.removeItem(storageKey);
// Emit Event
if (before !== after) {
this.emit(StorageEventType.STORAGE, new StorageEvent(key, before, after));
}
}
public swap(key: string, valueA: any, valueB: any, scope = StorageScope.GLOBAL, defaultValue?: any): void {
let value = this.get(key, scope);
if (types.isUndefinedOrNull(value) && defaultValue) {
this.store(key, defaultValue, scope);
} else if (value === valueA.toString()) { // Convert to string because store is string based
this.store(key, valueB, scope);
} else {
this.store(key, valueA, scope);
}
}
public getInteger(key: string, scope = StorageScope.GLOBAL, defaultValue?: number): number {
let value = this.get(key, scope, defaultValue);
if (types.isUndefinedOrNull(value)) {
return defaultValue;
}
return parseInt(value, 10);
}
public getBoolean(key: string, scope = StorageScope.GLOBAL, defaultValue?: boolean): boolean {
let value = this.get(key, scope, defaultValue);
if (types.isUndefinedOrNull(value)) {
return defaultValue;
}
if (types.isString(value)) {
return value.toLowerCase() === 'true' ? true : false;
}
return value ? true : false;
}
public dispose(): void {
super.dispose();
while (this.toUnbind.length) {
this.toUnbind.pop()();
}
}
private toStorageKey(key: string, scope: StorageScope): string {
if (scope === StorageScope.GLOBAL) {
return Storage.GLOBAL_PREFIX + key.toLowerCase();
}
return Storage.WORKSPACE_PREFIX + this.workspaceKey + key.toLowerCase();
}
}
// In-Memory Local Storage Implementation
export class InMemoryLocalStorage implements IStorage {
private store: { [key: string]: string; };
constructor() {
this.store = {};
}
public get length() {
return Object.keys(this.store).length;
}
public key(index: number): string {
let keys = Object.keys(this.store);
if (keys.length > index) {
return keys[index];
}
return null;
}
public clear(): void {
this.store = {};
}
public setItem(key: string, value: any): void {
this.store[key] = value.toString();
}
public getItem(key: string): string {
let item = this.store[key];
if (!types.isUndefinedOrNull(item)) {
return item;
}
return null;
}
public removeItem(key: string): void {
delete this.store[key];
}
}
export const inMemoryLocalStorageInstance = new InMemoryLocalStorage(); | src/vs/workbench/common/storage.ts | 0 | https://github.com/microsoft/vscode/commit/29303185aa7199f8f26b6ce73bd2bb5722c8bf6e | [
0.0033626453951001167,
0.0003329715982545167,
0.0001626149460207671,
0.00016998105274979025,
0.0006253056926652789
] |
{
"id": 5,
"code_window": [
"\t\tassert.ok(scorer.matches('hello world', 'horl'));\n",
"\t\tassert.ok(scorer.matches('hello world', 'd'));\n",
"\t\tassert.ok(!scorer.matches('hello world', 'wh'));\n",
"\t});\n",
"});\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.ok(!scorer.matches('d', 'dd'));\n"
],
"file_path": "src/vs/base/test/common/scorer.test.ts",
"type": "add",
"edit_start_line_idx": 51
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
// Based on material from:
/*!
* string_score.js: String Scoring Algorithm 0.1.22
*
* http://joshaven.com/string_score
* https://github.com/joshaven/string_score
*
* Copyright (C) 2009-2014 Joshaven Potter <[email protected]>
* Special thanks to all of the contributors listed here https://github.com/joshaven/string_score
* MIT License: http://opensource.org/licenses/MIT
*
* Date: Tue Mar 1 2011
* Updated: Tue Mar 10 2015
*/
/**
* Compute a score for the given string and the given query.
*
* Rules:
* Character score: 1
* Same case bonus: 1
* Upper case bonus: 1
* Start of word/path bonus: 7
* Start of string bonus: 8
*/
const wordPathBoundary = ['-', '_', ' ', '/', '\\', '.'];
export function score(target: string, query: string, cache?: {[id: string]: number}): number {
if (!target || !query) {
return 0; // return early if target or query are undefined
}
const hash = target + query;
const cached = cache && cache[hash];
if (typeof cached === 'number') {
return cached;
}
const queryLen = query.length;
const targetLower = target.toLowerCase();
const queryLower = query.toLowerCase();
let index = 0;
let lastIndexOf = 0;
let score = 0;
while (index < queryLen) {
var indexOf = targetLower.indexOf(queryLower[index], lastIndexOf);
if (indexOf < 0) {
score = 0; // This makes sure that the query is contained in the target
break;
}
lastIndexOf = indexOf;
// Character Match Bonus
score += 1;
// Same Case Bonous
if (target[indexOf] === query[indexOf]) {
score += 1;
}
// Prefix Bonus
if (indexOf === 0) {
score += 8;
}
// Start of Word/Path Bonous
else if (wordPathBoundary.some(w => w === target[indexOf - 1])) {
score += 7;
}
// Inside Word Upper Case Bonus
else if (isUpper(target.charCodeAt(indexOf))) {
score += 1;
}
index++;
}
if (cache) {
cache[hash] = score;
}
return score;
}
function isUpper(code: number): boolean {
return 65 <= code && code <= 90;
}
/**
* A fast method to check if a given string would produce a score > 0 for the given query.
*/
export function matches(target: string, queryLower: string): boolean {
if (!target || !queryLower) {
return false // return early if target or query are undefined
}
const queryLen = queryLower.length;
const targetLower = target.toLowerCase();
let index = 0;
let lastIndexOf = 0;
while (index < queryLen) {
var indexOf = targetLower.indexOf(queryLower[index], lastIndexOf);
if (indexOf < 0) {
return false;
}
lastIndexOf = indexOf;
index++;
}
return true;
} | src/vs/base/common/scorer.ts | 1 | https://github.com/microsoft/vscode/commit/29303185aa7199f8f26b6ce73bd2bb5722c8bf6e | [
0.0007435894221998751,
0.00022074967273510993,
0.00017178581038024276,
0.00017760858463589102,
0.00015095064009074122
] |
{
"id": 5,
"code_window": [
"\t\tassert.ok(scorer.matches('hello world', 'horl'));\n",
"\t\tassert.ok(scorer.matches('hello world', 'd'));\n",
"\t\tassert.ok(!scorer.matches('hello world', 'wh'));\n",
"\t});\n",
"});\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.ok(!scorer.matches('d', 'dd'));\n"
],
"file_path": "src/vs/base/test/common/scorer.test.ts",
"type": "add",
"edit_start_line_idx": 51
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as nls from 'vs/nls';
import {TPromise} from 'vs/base/common/winjs.base';
import {CommonEditorRegistry, ContextKey, EditorActionDescriptor} from 'vs/editor/common/editorCommonExtensions';
import {EditorAction, Behaviour} from 'vs/editor/common/editorAction';
import {FindModelBoundToEditorModel, FIND_IDS} from 'vs/editor/contrib/find/common/findModel';
import {Disposable} from 'vs/base/common/lifecycle';
import * as EditorCommon from 'vs/editor/common/editorCommon';
import {Selection} from 'vs/editor/common/core/selection';
import {IKeybindingService, IKeybindingContextKey, IKeybindings} from 'vs/platform/keybinding/common/keybindingService';
import {INullService} from 'vs/platform/instantiation/common/instantiation';
import {KeyMod, KeyCode} from 'vs/base/common/keyCodes';
import {Range} from 'vs/editor/common/core/range';
import {OccurrencesRegistry} from 'vs/editor/contrib/wordHighlighter/common/wordHighlighter';
import {INewFindReplaceState, FindReplaceStateChangedEvent, FindReplaceState} from 'vs/editor/contrib/find/common/findState';
export enum FindStartFocusAction {
NoFocusChange,
FocusFindInput,
FocusReplaceInput
}
export interface IFindStartOptions {
forceRevealReplace:boolean;
seedSearchStringFromSelection:boolean;
seedSearchScopeFromSelection:boolean;
shouldFocus:FindStartFocusAction;
shouldAnimate:boolean;
}
const CONTEXT_FIND_WIDGET_VISIBLE = 'findWidgetVisible';
export class CommonFindController extends Disposable implements EditorCommon.IEditorContribution {
static ID = 'editor.contrib.findController';
private _editor: EditorCommon.ICommonCodeEditor;
private _findWidgetVisible: IKeybindingContextKey<boolean>;
protected _state: FindReplaceState;
private _model: FindModelBoundToEditorModel;
static getFindController(editor:EditorCommon.ICommonCodeEditor): CommonFindController {
return <CommonFindController>editor.getContribution(CommonFindController.ID);
}
constructor(editor:EditorCommon.ICommonCodeEditor, @IKeybindingService keybindingService: IKeybindingService) {
super();
this._editor = editor;
this._findWidgetVisible = keybindingService.createKey(CONTEXT_FIND_WIDGET_VISIBLE, false);
this._state = this._register(new FindReplaceState());
this._register(this._state.addChangeListener((e) => this._onStateChanged(e)));
this._model = null;
this._register(this._editor.addListener2(EditorCommon.EventType.ModelChanged, () => {
let shouldRestartFind = (this._editor.getModel() && this._state.isRevealed);
this.disposeModel();
if (shouldRestartFind) {
this._start({
forceRevealReplace: false,
seedSearchStringFromSelection: false,
seedSearchScopeFromSelection: false,
shouldFocus: FindStartFocusAction.NoFocusChange,
shouldAnimate: false
});
}
}));
}
public dispose(): void {
this.disposeModel();
super.dispose();
}
private disposeModel(): void {
if (this._model) {
this._model.dispose();
this._model = null;
}
}
public getId(): string {
return CommonFindController.ID;
}
private _onStateChanged(e:FindReplaceStateChangedEvent): void {
if (e.isRevealed) {
if (this._state.isRevealed) {
this._findWidgetVisible.set(true);
} else {
this._findWidgetVisible.reset();
this.disposeModel();
}
}
}
public getState(): FindReplaceState {
return this._state;
}
public closeFindWidget(): void {
this._state.change({ isRevealed: false }, false);
this._editor.focus();
}
public toggleCaseSensitive(): void {
this._state.change({ matchCase: !this._state.matchCase }, false);
}
public toggleWholeWords(): void {
this._state.change({ wholeWord: !this._state.wholeWord }, false);
}
public toggleRegex(): void {
this._state.change({ isRegex: !this._state.isRegex }, false);
}
public setSearchString(searchString:string): void {
this._state.change({ searchString: searchString }, false);
}
public getSelectionSearchString(): string {
let selection = this._editor.getSelection();
if (selection.startLineNumber === selection.endLineNumber) {
if (selection.isEmpty()) {
let wordAtPosition = this._editor.getModel().getWordAtPosition(selection.getStartPosition());
if (wordAtPosition) {
return wordAtPosition.word;
}
} else {
return this._editor.getModel().getValueInRange(selection);
}
}
return null;
}
protected _start(opts:IFindStartOptions): void {
this.disposeModel();
if (!this._editor.getModel()) {
// cannot do anything with an editor that doesn't have a model...
return;
}
let stateChanges: INewFindReplaceState = {
isRevealed: true
};
// Consider editor selection and overwrite the state with it
if (opts.seedSearchStringFromSelection) {
let selectionSearchString = this.getSelectionSearchString();
if (selectionSearchString) {
stateChanges.searchString = selectionSearchString;
}
}
let selection = this._editor.getSelection();
stateChanges.searchScope = null;
if (opts.seedSearchScopeFromSelection && selection.startLineNumber < selection.endLineNumber) {
// Take search scope into account only if it is more than one line.
stateChanges.searchScope = selection;
}
// Overwrite isReplaceRevealed
if (opts.forceRevealReplace) {
stateChanges.isReplaceRevealed = true;
}
this._state.change(stateChanges, false);
if (!this._model) {
this._model = new FindModelBoundToEditorModel(this._editor, this._state);
}
}
public start(opts:IFindStartOptions): void {
this._start(opts);
}
public moveToNextMatch(): boolean {
if (this._model) {
this._model.moveToNextMatch();
return true;
}
return false;
}
public moveToPrevMatch(): boolean {
if (this._model) {
this._model.moveToPrevMatch();
return true;
}
return false;
}
public replace(): boolean {
if (this._model) {
this._model.replace();
return true;
}
return false;
}
public replaceAll(): boolean {
if (this._model) {
this._model.replaceAll();
return true;
}
return false;
}
}
export class StartFindAction extends EditorAction {
constructor(descriptor: EditorCommon.IEditorActionDescriptorData, editor: EditorCommon.ICommonCodeEditor, @INullService ns) {
super(descriptor, editor, Behaviour.WidgetFocus);
}
public run(): TPromise<boolean> {
let controller = CommonFindController.getFindController(this.editor);
controller.start({
forceRevealReplace: false,
seedSearchStringFromSelection: true,
seedSearchScopeFromSelection: true,
shouldFocus: FindStartFocusAction.FocusFindInput,
shouldAnimate: true
});
return TPromise.as(true);
}
}
export abstract class MatchFindAction extends EditorAction {
constructor(descriptor:EditorCommon.IEditorActionDescriptorData, editor:EditorCommon.ICommonCodeEditor, @INullService ns) {
super(descriptor, editor, Behaviour.WidgetFocus);
}
public run(): TPromise<boolean> {
let controller = CommonFindController.getFindController(this.editor);
if (!this._run(controller)) {
controller.start({
forceRevealReplace: false,
seedSearchStringFromSelection: (controller.getState().searchString.length === 0),
seedSearchScopeFromSelection: false,
shouldFocus: FindStartFocusAction.NoFocusChange,
shouldAnimate: true
});
this._run(controller);
}
return TPromise.as(true);
}
protected abstract _run(controller:CommonFindController): boolean;
}
export class NextMatchFindAction extends MatchFindAction {
protected _run(controller:CommonFindController): boolean {
return controller.moveToNextMatch();
}
}
export class PreviousMatchFindAction extends MatchFindAction {
protected _run(controller:CommonFindController): boolean {
return controller.moveToPrevMatch();
}
}
export abstract class SelectionMatchFindAction extends EditorAction {
constructor(descriptor:EditorCommon.IEditorActionDescriptorData, editor:EditorCommon.ICommonCodeEditor, @INullService ns) {
super(descriptor, editor, Behaviour.WidgetFocus);
}
public run(): TPromise<boolean> {
let controller = CommonFindController.getFindController(this.editor);
let selectionSearchString = controller.getSelectionSearchString();
if (selectionSearchString) {
controller.setSearchString(selectionSearchString);
}
if (!this._run(controller)) {
controller.start({
forceRevealReplace: false,
seedSearchStringFromSelection: false,
seedSearchScopeFromSelection: false,
shouldFocus: FindStartFocusAction.NoFocusChange,
shouldAnimate: true
});
this._run(controller);
}
return TPromise.as(true);
}
protected abstract _run(controller:CommonFindController): boolean;
}
export class NextSelectionMatchFindAction extends SelectionMatchFindAction {
protected _run(controller:CommonFindController): boolean {
return controller.moveToNextMatch();
}
}
export class PreviousSelectionMatchFindAction extends SelectionMatchFindAction {
protected _run(controller:CommonFindController): boolean {
return controller.moveToPrevMatch();
}
}
export class StartFindReplaceAction extends EditorAction {
constructor(descriptor:EditorCommon.IEditorActionDescriptorData, editor:EditorCommon.ICommonCodeEditor, @INullService ns) {
super(descriptor, editor, Behaviour.WidgetFocus | Behaviour.Writeable);
}
public run(): TPromise<boolean> {
let controller = CommonFindController.getFindController(this.editor);
controller.start({
forceRevealReplace: true,
seedSearchStringFromSelection: (controller.getState().searchString.length === 0),
seedSearchScopeFromSelection: true,
shouldFocus: FindStartFocusAction.FocusReplaceInput,
shouldAnimate: true
});
return TPromise.as(true);
}
}
export interface IMultiCursorFindResult {
searchText:string;
matchCase:boolean;
wholeWord:boolean;
nextMatch: EditorCommon.IEditorSelection;
}
export function multiCursorFind(editor:EditorCommon.ICommonCodeEditor, changeFindSearchString:boolean): IMultiCursorFindResult {
let controller = CommonFindController.getFindController(editor);
let state = controller.getState();
let searchText: string,
nextMatch: EditorCommon.IEditorSelection;
// In any case, if the find widget was ever opened, the options are taken from it
let wholeWord = state.wholeWord;
let matchCase = state.matchCase;
// Find widget owns what we search for if:
// - focus is not in the editor (i.e. it is in the find widget)
// - and the search widget is visible
// - and the search string is non-empty
if (!editor.isFocused() && state.isRevealed && state.searchString.length > 0) {
// Find widget owns what is searched for
searchText = state.searchString;
} else {
// Selection owns what is searched for
let s = editor.getSelection();
if (s.startLineNumber !== s.endLineNumber) {
// Cannot search for multiline string... yet...
return null;
}
if (s.isEmpty()) {
// selection is empty => expand to current word
let word = editor.getModel().getWordAtPosition(s.getStartPosition());
if (!word) {
return null;
}
searchText = word.word;
nextMatch = Selection.createSelection(s.startLineNumber, word.startColumn, s.startLineNumber, word.endColumn);
} else {
searchText = editor.getModel().getValueInRange(s);
}
if (changeFindSearchString) {
controller.setSearchString(searchText);
}
}
return {
searchText: searchText,
matchCase: matchCase,
wholeWord: wholeWord,
nextMatch: nextMatch
};
}
export class SelectNextFindMatchAction extends EditorAction {
constructor(descriptor:EditorCommon.IEditorActionDescriptorData, editor:EditorCommon.ICommonCodeEditor, @INullService ns) {
super(descriptor, editor, Behaviour.WidgetFocus);
}
protected _getNextMatch(): EditorCommon.IEditorSelection {
let r = multiCursorFind(this.editor, true);
if (!r) {
return null;
}
if (r.nextMatch) {
return r.nextMatch;
}
let allSelections = this.editor.getSelections();
let lastAddedSelection = allSelections[allSelections.length - 1];
let nextMatch = this.editor.getModel().findNextMatch(r.searchText, lastAddedSelection.getEndPosition(), false, r.matchCase, r.wholeWord);
if (!nextMatch) {
return null;
}
return Selection.createSelection(nextMatch.startLineNumber, nextMatch.startColumn, nextMatch.endLineNumber, nextMatch.endColumn);
}
}
export class AddSelectionToNextFindMatchAction extends SelectNextFindMatchAction {
static ID = FIND_IDS.AddSelectionToNextFindMatchAction;
constructor(descriptor:EditorCommon.IEditorActionDescriptorData, editor:EditorCommon.ICommonCodeEditor, @INullService ns) {
super(descriptor, editor, ns);
}
public run(): TPromise<boolean> {
let nextMatch = this._getNextMatch();
if (!nextMatch) {
return TPromise.as(false);
}
let allSelections = this.editor.getSelections();
this.editor.setSelections(allSelections.concat(nextMatch));
this.editor.revealRangeInCenterIfOutsideViewport(nextMatch);
return TPromise.as(true);
}
}
export class MoveSelectionToNextFindMatchAction extends SelectNextFindMatchAction {
static ID = FIND_IDS.MoveSelectionToNextFindMatchAction;
constructor(descriptor:EditorCommon.IEditorActionDescriptorData, editor:EditorCommon.ICommonCodeEditor, @INullService ns) {
super(descriptor, editor, ns);
}
public run(): TPromise<boolean> {
let nextMatch = this._getNextMatch();
if (!nextMatch) {
return TPromise.as(false);
}
let allSelections = this.editor.getSelections();
let lastAddedSelection = allSelections[allSelections.length - 1];
this.editor.setSelections(allSelections.slice(0, allSelections.length - 1).concat(nextMatch));
this.editor.revealRangeInCenterIfOutsideViewport(nextMatch);
return TPromise.as(true);
}
}
export class SelectHighlightsAction extends EditorAction {
static ID = 'editor.action.selectHighlights';
static COMPAT_ID = 'editor.action.changeAll';
constructor(descriptor:EditorCommon.IEditorActionDescriptorData, editor:EditorCommon.ICommonCodeEditor, @INullService ns) {
let behaviour = Behaviour.WidgetFocus;
if (descriptor.id === SelectHighlightsAction.COMPAT_ID) {
behaviour |= Behaviour.ShowInContextMenu;
}
super(descriptor, editor, behaviour);
}
public getGroupId(): string {
return '2_change/1_changeAll';
}
public run(): TPromise<boolean> {
let r = multiCursorFind(this.editor, true);
if (!r) {
return TPromise.as(false);
}
let matches = this.editor.getModel().findMatches(r.searchText, true, false, r.matchCase, r.wholeWord);
if (matches.length > 0) {
this.editor.setSelections(matches.map(m => Selection.createSelection(m.startLineNumber, m.startColumn, m.endLineNumber, m.endColumn)));
}
return TPromise.as(true);
}
}
export class SelectionHighlighter extends Disposable implements EditorCommon.IEditorContribution {
static ID = 'editor.contrib.selectionHighlighter';
private editor: EditorCommon.ICommonCodeEditor;
private decorations: string[];
constructor(editor:EditorCommon.ICommonCodeEditor, @INullService ns) {
super();
this.editor = editor;
this.decorations = [];
this._register(editor.addListener2(EditorCommon.EventType.CursorPositionChanged, _ => this._update()));
this._register(editor.addListener2(EditorCommon.EventType.ModelChanged, (e) => {
this.removeDecorations();
}));
this._register(CommonFindController.getFindController(editor).getState().addChangeListener((e) => this._update()));
}
public getId(): string {
return SelectionHighlighter.ID;
}
private removeDecorations(): void {
if (this.decorations.length > 0) {
this.decorations = this.editor.deltaDecorations(this.decorations, []);
}
}
private _update(): void {
if (!this.editor.getConfiguration().selectionHighlight) {
return;
}
let r = multiCursorFind(this.editor, false);
if (!r) {
this.removeDecorations();
return;
}
let model = this.editor.getModel();
if (r.nextMatch) {
// This is an empty selection
if (OccurrencesRegistry.has(model)) {
// Do not interfere with semantic word highlighting in the no selection case
this.removeDecorations();
return;
}
}
if (/^[ \t]+$/.test(r.searchText)) {
// whitespace only selection
this.removeDecorations();
return;
}
if (r.searchText.length > 200) {
// very long selection
this.removeDecorations();
return;
}
let allMatches = model.findMatches(r.searchText, true, false, r.matchCase, r.wholeWord);
allMatches.sort(Range.compareRangesUsingStarts);
let selections = this.editor.getSelections();
selections.sort(Range.compareRangesUsingStarts);
// do not overlap with selection (issue #64 and #512)
let matches: EditorCommon.IEditorRange[] = [];
for (let i = 0, j = 0, len = allMatches.length, lenJ = selections.length; i < len; ) {
let match = allMatches[i];
if (j >= lenJ) {
// finished all editor selections
matches.push(match);
i++;
} else {
let cmp = Range.compareRangesUsingStarts(match, selections[j]);
if (cmp < 0) {
// match is before sel
matches.push(match);
i++;
} else if (cmp > 0) {
// sel is before match
j++;
} else {
// sel is equal to match
i++;
j++;
}
}
}
let decorations = matches.map(r => {
return {
range: r,
options: {
stickiness: EditorCommon.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
className: 'selectionHighlight'
}
};
});
this.decorations = this.editor.deltaDecorations(this.decorations, decorations);
}
public dispose(): void {
this.removeDecorations();
super.dispose();
}
}
CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(SelectHighlightsAction, SelectHighlightsAction.ID, nls.localize('selectAllOccurencesOfFindMatch', "Select All Occurences of Find Match"), {
context: ContextKey.EditorFocus,
primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_L
}));
// register SelectHighlightsAction again to replace the now removed Change All action
CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(SelectHighlightsAction, SelectHighlightsAction.COMPAT_ID, nls.localize('changeAll.label', "Change All Occurrences"), {
context: ContextKey.EditorTextFocus,
primary: KeyMod.CtrlCmd | KeyCode.F2
}));
// register actions
CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(StartFindAction, FIND_IDS.StartFindAction, nls.localize('startFindAction',"Find"), {
context: ContextKey.None,
primary: KeyMod.CtrlCmd | KeyCode.KEY_F
}));
CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(NextMatchFindAction, FIND_IDS.NextMatchFindAction, nls.localize('findNextMatchAction', "Find Next"), {
context: ContextKey.EditorFocus,
primary: KeyCode.F3,
mac: { primary: KeyMod.CtrlCmd | KeyCode.KEY_G, secondary: [KeyCode.F3] }
}));
CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(PreviousMatchFindAction, FIND_IDS.PreviousMatchFindAction, nls.localize('findPreviousMatchAction', "Find Previous"), {
context: ContextKey.EditorFocus,
primary: KeyMod.Shift | KeyCode.F3,
mac: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_G, secondary: [KeyMod.Shift | KeyCode.F3] }
}));
CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(NextSelectionMatchFindAction, FIND_IDS.NextSelectionMatchFindAction, nls.localize('nextSelectionMatchFindAction', "Find Next Selection"), {
context: ContextKey.EditorFocus,
primary: KeyMod.CtrlCmd | KeyCode.F3
}));
CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(PreviousSelectionMatchFindAction, FIND_IDS.PreviousSelectionMatchFindAction, nls.localize('previousSelectionMatchFindAction', "Find Previous Selection"), {
context: ContextKey.EditorFocus,
primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.F3
}));
CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(StartFindReplaceAction, FIND_IDS.StartFindReplaceAction, nls.localize('startReplace', "Replace"), {
context: ContextKey.None,
primary: KeyMod.CtrlCmd | KeyCode.KEY_H,
mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_F }
}));
CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(MoveSelectionToNextFindMatchAction, MoveSelectionToNextFindMatchAction.ID, nls.localize('moveSelectionToNextFindMatch', "Move Last Selection To Next Find Match"), {
context: ContextKey.EditorFocus,
primary: KeyMod.chord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_D)
}));
CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(AddSelectionToNextFindMatchAction, AddSelectionToNextFindMatchAction.ID, nls.localize('addSelectionToNextFindMatch', "Add Selection To Next Find Match"), {
context: ContextKey.EditorFocus,
primary: KeyMod.CtrlCmd | KeyCode.KEY_D
}));
function registerFindCommand(id:string, callback:(controller:CommonFindController)=>void, keybindings:IKeybindings, needsKey:string = null): void {
CommonEditorRegistry.registerEditorCommand(id, CommonEditorRegistry.commandWeight(5), keybindings, false, needsKey, (ctx, editor, args) => {
callback(CommonFindController.getFindController(editor));
});
}
registerFindCommand(FIND_IDS.CloseFindWidgetCommand, x => x.closeFindWidget(), {
primary: KeyCode.Escape
}, CONTEXT_FIND_WIDGET_VISIBLE);
registerFindCommand(FIND_IDS.ToggleCaseSensitiveCommand, x => x.toggleCaseSensitive(), {
primary: KeyMod.Alt | KeyCode.KEY_C,
mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_C }
});
registerFindCommand(FIND_IDS.ToggleWholeWordCommand, x => x.toggleWholeWords(), {
primary: KeyMod.Alt | KeyCode.KEY_W,
mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_W }
});
registerFindCommand(FIND_IDS.ToggleRegexCommand, x => x.toggleRegex(), {
primary: KeyMod.Alt | KeyCode.KEY_R,
mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_R }
});
| src/vs/editor/contrib/find/common/findController.ts | 0 | https://github.com/microsoft/vscode/commit/29303185aa7199f8f26b6ce73bd2bb5722c8bf6e | [
0.00034602521918714046,
0.0001815879950299859,
0.00016739859711378813,
0.0001748880313243717,
0.00003103264680248685
] |
{
"id": 5,
"code_window": [
"\t\tassert.ok(scorer.matches('hello world', 'horl'));\n",
"\t\tassert.ok(scorer.matches('hello world', 'd'));\n",
"\t\tassert.ok(!scorer.matches('hello world', 'wh'));\n",
"\t});\n",
"});\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.ok(!scorer.matches('d', 'dd'));\n"
],
"file_path": "src/vs/base/test/common/scorer.test.ts",
"type": "add",
"edit_start_line_idx": 51
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import {EventType} from 'vs/platform/files/common/files';
import watcher = require('vs/workbench/services/files/node/watcher/common');
import {OutOfProcessWin32FolderWatcher} from 'vs/workbench/services/files/node/watcher/win32/csharpWatcherService';
import {IEventService} from 'vs/platform/event/common/event';
export class FileWatcher {
private eventEmitter: IEventService;
constructor(private basePath: string, private ignored: string[], eventEmitter: IEventService, private errorLogger: (msg: string) => void, private verboseLogging: boolean) {
this.eventEmitter = eventEmitter;
}
public startWatching(): () => void /* dispose */ {
let watcher = new OutOfProcessWin32FolderWatcher(
this.basePath,
this.ignored,
this.errorLogger,
(events) => this.onRawFileEvents(events),
this.verboseLogging
);
return () => watcher.dispose();
}
private onRawFileEvents(events: watcher.IRawFileChange[]): void {
// Emit through broadcast service
if (events.length > 0) {
this.eventEmitter.emit(EventType.FILE_CHANGES, watcher.toFileChangesEvent(events));
}
}
} | src/vs/workbench/services/files/node/watcher/win32/watcherService.ts | 0 | https://github.com/microsoft/vscode/commit/29303185aa7199f8f26b6ce73bd2bb5722c8bf6e | [
0.0001767756330082193,
0.00017619060236029327,
0.00017541376291774213,
0.0001762864994816482,
4.917449700769794e-7
] |
{
"id": 5,
"code_window": [
"\t\tassert.ok(scorer.matches('hello world', 'horl'));\n",
"\t\tassert.ok(scorer.matches('hello world', 'd'));\n",
"\t\tassert.ok(!scorer.matches('hello world', 'wh'));\n",
"\t});\n",
"});\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"\t\tassert.ok(!scorer.matches('d', 'dd'));\n"
],
"file_path": "src/vs/base/test/common/scorer.test.ts",
"type": "add",
"edit_start_line_idx": 51
} | {
"comments": {
"lineComment": "//",
"blockComment": [ "/*", "*/" ]
},
"brackets": [
["{", "}"],
["[", "]"],
["(", ")"]
]
} | extensions/objective-c/objective-c.configuration.json | 0 | https://github.com/microsoft/vscode/commit/29303185aa7199f8f26b6ce73bd2bb5722c8bf6e | [
0.00018077436834573746,
0.00017873625620268285,
0.00017669812950771302,
0.00017873625620268285,
0.0000020381194190122187
] |
{
"id": 0,
"code_window": [
"superBlock: Responsive Web Design\n",
"---\n",
"## Introduction to Responsive Web Design\n",
"\n",
"Time to put your newly learnt skills to work! By working on projects you would have the opportunity of applying all the skills, principles and concepts you have learnt so far HTML, CSS, Visual Design, Accessibility, etc. \n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"This introduction is a stub\n"
],
"file_path": "packages/learn/src/introductions/responsive-web-design/index.md",
"type": "replace",
"edit_start_line_idx": 6
} | ---
title: Responsive Web Design
superBlock: Responsive Web Design
---
## Introduction to Responsive Web Design
Time to put your newly learnt skills to work! By working on projects you would have the opportunity of applying all the skills, principles and concepts you have learnt so far HTML, CSS, Visual Design, Accessibility, etc.
In this section you get the chance to:
* Build a Tribute Page
* Build a Survey Form
* Build a Product Landing Page
* Build a Technical Documentation Page
* Build a Personal Portfolio Webpage
By the end of this, you would have 5 responsive websites under your belt that you can show off to friends, family, employers, etc. Have fun and remember to use the [Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514) method if you get stuck.
| packages/learn/src/introductions/responsive-web-design/index.md | 1 | https://github.com/freeCodeCamp/freeCodeCamp/commit/f3e8ecd1338b6b56bd7a0e9667e845a3f08796c8 | [
0.9876603484153748,
0.49391257762908936,
0.00016480735212098807,
0.49391257762908936,
0.4937477707862854
] |
{
"id": 0,
"code_window": [
"superBlock: Responsive Web Design\n",
"---\n",
"## Introduction to Responsive Web Design\n",
"\n",
"Time to put your newly learnt skills to work! By working on projects you would have the opportunity of applying all the skills, principles and concepts you have learnt so far HTML, CSS, Visual Design, Accessibility, etc. \n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"This introduction is a stub\n"
],
"file_path": "packages/learn/src/introductions/responsive-web-design/index.md",
"type": "replace",
"edit_start_line_idx": 6
} | /* global graphql */
import React, { Fragment } from 'react';
import PropTypes from 'prop-types';
import Link, { navigateTo } from 'gatsby-link';
import Helmet from 'react-helmet';
import { Button, ListGroup, ListGroupItem } from 'react-bootstrap';
import FullWidthRow from '../../components/util/FullWidthRow';
import ButtonSpacer from '../../components/util/ButtonSpacer';
import { MarkdownRemark, AllChallengeNode } from '../../redux/propTypes';
import './intro.css';
const propTypes = {
data: PropTypes.shape({
markdownRemark: MarkdownRemark,
allChallengeNode: AllChallengeNode
})
};
function renderMenuItems({ edges = [] }) {
return edges.map(({ node }) => node).map(({ title, fields: { slug } }) => (
<Link key={'intro-' + slug} to={slug}>
<ListGroupItem>{title}</ListGroupItem>
</Link>
));
}
function handleCurriculumClick() {
return navigateTo('/');
}
function IntroductionPage({ data: { markdownRemark, allChallengeNode } }) {
const { html, frontmatter: { block } } = markdownRemark;
const firstLesson = allChallengeNode && allChallengeNode.edges[0].node;
const firstLessonPath = firstLesson
? firstLesson.fields.slug
: '/strange-place';
return (
<Fragment>
<Helmet>
<title>{block} | freeCodeCamp</title>
</Helmet>
<FullWidthRow>
<div
className='intro-layout'
dangerouslySetInnerHTML={{ __html: html }}
/>
</FullWidthRow>
<FullWidthRow>
<Link className='btn btn-lg btn-primary btn-block' to={firstLessonPath}>
Go to the first lesson
</Link>
<ButtonSpacer />
<Button
block={true}
bsSize='lg'
className='btn-primary-invert'
onClick={handleCurriculumClick}
>
View the curriculum
</Button>
<ButtonSpacer />
<hr />
</FullWidthRow>
<FullWidthRow>
<h2 className='intro-toc-title'>Upcoming Lessons</h2>
<ListGroup className='intro-toc'>
{allChallengeNode ? renderMenuItems(allChallengeNode) : null}
</ListGroup>
</FullWidthRow>
</Fragment>
);
}
IntroductionPage.displayName = 'IntroductionPage';
IntroductionPage.propTypes = propTypes;
export default IntroductionPage;
export const query = graphql`
query IntroPageBySlug($slug: String!, $block: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
frontmatter {
block
}
html
}
allChallengeNode(
filter: { block: { eq: $block } }
sort: { fields: [superOrder, order, suborder] }
) {
edges {
node {
fields {
slug
}
title
}
}
}
}
`;
| packages/learn/src/templates/Introduction/Intro.js | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/f3e8ecd1338b6b56bd7a0e9667e845a3f08796c8 | [
0.000431070220656693,
0.00020032118482049555,
0.0001675439125392586,
0.0001719710126053542,
0.00007390961400233209
] |
{
"id": 0,
"code_window": [
"superBlock: Responsive Web Design\n",
"---\n",
"## Introduction to Responsive Web Design\n",
"\n",
"Time to put your newly learnt skills to work! By working on projects you would have the opportunity of applying all the skills, principles and concepts you have learnt so far HTML, CSS, Visual Design, Accessibility, etc. \n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"This introduction is a stub\n"
],
"file_path": "packages/learn/src/introductions/responsive-web-design/index.md",
"type": "replace",
"edit_start_line_idx": 6
} | {
"name": "Additon and Subtraction",
"order": 2,
"challenges": [
{
"id": "59a5801209a6acac5983b411",
"title": "Add Whole Numbers",
"description": [
""
],
"challengeSeed": [
""
],
"tests": [
""
]
},
{
"id": "59a5801209a6acac59836306",
"title": "Subtract Whole Numbers",
"description": [
""
],
"challengeSeed": [
""
],
"tests": [
""
]
},
{
"id": "59a5801209a6acac59836307",
"title": "Estimate Whole Number Sums and Differences",
"description": [
""
],
"challengeSeed": [
""
],
"tests": [
""
]
}
]
} | curriculum/math-challenges/30-arithmetic/additon-and-subtraction.json | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/f3e8ecd1338b6b56bd7a0e9667e845a3f08796c8 | [
0.00017238077998626977,
0.00017126159218605608,
0.00016978592611849308,
0.00017133513756562024,
8.42214376461925e-7
] |
{
"id": 0,
"code_window": [
"superBlock: Responsive Web Design\n",
"---\n",
"## Introduction to Responsive Web Design\n",
"\n",
"Time to put your newly learnt skills to work! By working on projects you would have the opportunity of applying all the skills, principles and concepts you have learnt so far HTML, CSS, Visual Design, Accessibility, etc. \n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"This introduction is a stub\n"
],
"file_path": "packages/learn/src/introductions/responsive-web-design/index.md",
"type": "replace",
"edit_start_line_idx": 6
} | module.exports = function mountRestApi(app) {
const restApi = app.loopback.rest();
const restApiRoot = app.get('restApiRoot');
app.use(restApiRoot, restApi);
app.use(`/internal${restApiRoot}`, restApi);
};
| api-server/server/boot/restApi.js | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/f3e8ecd1338b6b56bd7a0e9667e845a3f08796c8 | [
0.00016771876835264266,
0.00016771876835264266,
0.00016771876835264266,
0.00016771876835264266,
0
] |
{
"id": 1,
"code_window": [
"\n",
"In this section you get the chance to:\n",
" * Build a Tribute Page\n",
" * Build a Survey Form\n",
" * Build a Product Landing Page\n",
" * Build a Technical Documentation Page\n",
" * Build a Personal Portfolio Webpage\n",
"\n",
"By the end of this, you would have 5 responsive websites under your belt that you can show off to friends, family, employers, etc. Have fun and remember to use the [Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514) method if you get stuck.\n",
" "
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"Help us make it real on [GitHub](https://github.com/freeCodeCamp/learn/tree/master/src/introductions).\n"
],
"file_path": "packages/learn/src/introductions/responsive-web-design/index.md",
"type": "replace",
"edit_start_line_idx": 8
} | ---
title: Responsive Web Design
superBlock: Responsive Web Design
---
## Introduction to Responsive Web Design
Time to put your newly learnt skills to work! By working on projects you would have the opportunity of applying all the skills, principles and concepts you have learnt so far HTML, CSS, Visual Design, Accessibility, etc.
In this section you get the chance to:
* Build a Tribute Page
* Build a Survey Form
* Build a Product Landing Page
* Build a Technical Documentation Page
* Build a Personal Portfolio Webpage
By the end of this, you would have 5 responsive websites under your belt that you can show off to friends, family, employers, etc. Have fun and remember to use the [Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514) method if you get stuck.
| packages/learn/src/introductions/responsive-web-design/index.md | 1 | https://github.com/freeCodeCamp/freeCodeCamp/commit/f3e8ecd1338b6b56bd7a0e9667e845a3f08796c8 | [
0.002149787964299321,
0.0012518170988187194,
0.00035384620423428714,
0.0012518170988187194,
0.0008979708654806018
] |
{
"id": 1,
"code_window": [
"\n",
"In this section you get the chance to:\n",
" * Build a Tribute Page\n",
" * Build a Survey Form\n",
" * Build a Product Landing Page\n",
" * Build a Technical Documentation Page\n",
" * Build a Personal Portfolio Webpage\n",
"\n",
"By the end of this, you would have 5 responsive websites under your belt that you can show off to friends, family, employers, etc. Have fun and remember to use the [Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514) method if you get stuck.\n",
" "
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"Help us make it real on [GitHub](https://github.com/freeCodeCamp/learn/tree/master/src/introductions).\n"
],
"file_path": "packages/learn/src/introductions/responsive-web-design/index.md",
"type": "replace",
"edit_start_line_idx": 8
} | /* global expect */
import React from 'react';
import renderer from 'react-test-renderer';
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { DynamicForm } from './Form';
Enzyme.configure({ adapter: new Adapter() });
const defaultTestProps = {
errors: {},
fields: {
_meta: {
allPristine: true,
name: 'name',
onChange: () => {},
value: ''
}
},
handleSubmit: () => {},
buttonText: 'Submit',
enableSubmit: true,
formFields: ['name', 'website'],
hideButton: false,
id: 'my-test-form',
options: {
types: {
name: 'text',
website: 'url'
},
required: ['website']
},
submit: () => {}
};
test('<DynamicForm /> snapshot', () => {
const component = renderer.create(<DynamicForm {...defaultTestProps} />);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
| packages/learn/src/components/formHelpers/Form.test.js | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/f3e8ecd1338b6b56bd7a0e9667e845a3f08796c8 | [
0.00016902416246011853,
0.00016728625632822514,
0.00016552455781493336,
0.00016781537851784378,
0.0000013820282447341015
] |
{
"id": 1,
"code_window": [
"\n",
"In this section you get the chance to:\n",
" * Build a Tribute Page\n",
" * Build a Survey Form\n",
" * Build a Product Landing Page\n",
" * Build a Technical Documentation Page\n",
" * Build a Personal Portfolio Webpage\n",
"\n",
"By the end of this, you would have 5 responsive websites under your belt that you can show off to friends, family, employers, etc. Have fun and remember to use the [Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514) method if you get stuck.\n",
" "
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"Help us make it real on [GitHub](https://github.com/freeCodeCamp/learn/tree/master/src/introductions).\n"
],
"file_path": "packages/learn/src/introductions/responsive-web-design/index.md",
"type": "replace",
"edit_start_line_idx": 8
} | {
"name": "Triangle Congruency",
"order": 14,
"challenges": [
{
"id": "59a5801209a6acac5983b505",
"title": "CPCTC",
"description": [
""
],
"challengeSeed": [
""
],
"tests": [
""
]
},
{
"id": "59a5801209a6acac5983a319",
"title": "Congruence Statements",
"description": [
""
],
"challengeSeed": [
""
],
"tests": [
""
]
},
{
"id": "59a5801209a6acac5983a320",
"title": "Third Angle Theorem",
"description": [
""
],
"challengeSeed": [
""
],
"tests": [
""
]
},
{
"id": "59a5801209a6acac5983a321",
"title": "Congruent Triangles",
"description": [
""
],
"challengeSeed": [
""
],
"tests": [
""
]
},
{
"id": "59a5801209a6acac5983a322",
"title": "SSS",
"description": [
""
],
"challengeSeed": [
""
],
"tests": [
""
]
},
{
"id": "59a5801209a6acac5983a323",
"title": "SAS",
"description": [
""
],
"challengeSeed": [
""
],
"tests": [
""
]
},
{
"id": "59a5801209a6acac5983a324",
"title": "ASA and AAS",
"description": [
""
],
"challengeSeed": [
""
],
"tests": [
""
]
},
{
"id": "59a5801209a6acac5983a325",
"title": "HL",
"description": [
""
],
"challengeSeed": [
""
],
"tests": [
""
]
}
]
} | curriculum/math-challenges/33-geometry/triangle-congruency.json | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/f3e8ecd1338b6b56bd7a0e9667e845a3f08796c8 | [
0.00016861577751114964,
0.00016722379950806499,
0.00016519517521373928,
0.00016756137483753264,
0.0000010737657021309133
] |
{
"id": 1,
"code_window": [
"\n",
"In this section you get the chance to:\n",
" * Build a Tribute Page\n",
" * Build a Survey Form\n",
" * Build a Product Landing Page\n",
" * Build a Technical Documentation Page\n",
" * Build a Personal Portfolio Webpage\n",
"\n",
"By the end of this, you would have 5 responsive websites under your belt that you can show off to friends, family, employers, etc. Have fun and remember to use the [Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514) method if you get stuck.\n",
" "
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"Help us make it real on [GitHub](https://github.com/freeCodeCamp/learn/tree/master/src/introductions).\n"
],
"file_path": "packages/learn/src/introductions/responsive-web-design/index.md",
"type": "replace",
"edit_start_line_idx": 8
} | {
"name": "Non-Right Triangle Trigonometry",
"order": 14,
"challenges": [
{
"id": "59a5801209a6adac5983b548",
"title": "Laws of Sines and Cosines",
"description": [
""
],
"challengeSeed": [
""
],
"tests": [
""
]
},
{
"id": "59a5801209a6acac5983a563",
"title": "Law of Sines",
"description": [
""
],
"challengeSeed": [
""
],
"tests": [
""
]
},
{
"id": "59a5801209a6acac5983a564",
"title": "Angle-Angle-Side Triangles",
"description": [
""
],
"challengeSeed": [
""
],
"tests": [
""
]
},
{
"id": "59a5801209a6acac5983a565",
"title": "Angle-Side-Angle Triangles",
"description": [
""
],
"challengeSeed": [
""
],
"tests": [
""
]
},
{
"id": "59a5801209a6acac5983a566",
"title": "Side-Side-Angle: The Ambiguous Case",
"description": [
""
],
"challengeSeed": [
""
],
"tests": [
""
]
},
{
"id": "59a5801209a6acac5983a567",
"title": "Law of Cosines",
"description": [
""
],
"challengeSeed": [
""
],
"tests": [
""
]
},
{
"id": "59a5801209a6acac5983a568",
"title": "Determination of Unknown Angles Using Law of Cosines",
"description": [
""
],
"challengeSeed": [
""
],
"tests": [
""
]
},
{
"id": "59a5801209a6acac5983a569",
"title": "Identify Accurate Drawings of Triangles",
"description": [
""
],
"challengeSeed": [
""
],
"tests": [
""
]
},
{
"id": "59a5801209a6acac5983a570",
"title": "Applications of the Law of Cosines",
"description": [
""
],
"challengeSeed": [
""
],
"tests": [
""
]
},
{
"id": "59a5801209a6acac5983a571",
"title": "Trigonometry Word Problems",
"description": [
""
],
"challengeSeed": [
""
],
"tests": [
""
]
}
]
} | curriculum/math-challenges/34-trigonometry/non-right-triangle-trigonometry.json | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/f3e8ecd1338b6b56bd7a0e9667e845a3f08796c8 | [
0.00016789605433586985,
0.00016685861919540912,
0.00016555564070586115,
0.00016687849711161107,
7.903753385107848e-7
] |
{
"id": 2,
"code_window": [
"superBlock: Responsive Web Design\n",
"---\n",
"## Introduction to the Responsive Web Design Projects\n",
"\n",
"This introduction is a stub\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"Time to put your newly learnt skills to work! By working on projects you would have the opportunity of applying all the skills, principles and concepts you have learnt so far HTML, CSS, Visual Design, Accessibility, etc. \n"
],
"file_path": "packages/learn/src/introductions/responsive-web-design/responsive-web-design-projects/index.md",
"type": "replace",
"edit_start_line_idx": 7
} | ---
title: Responsive Web Design
superBlock: Responsive Web Design
---
## Introduction to Responsive Web Design
Time to put your newly learnt skills to work! By working on projects you would have the opportunity of applying all the skills, principles and concepts you have learnt so far HTML, CSS, Visual Design, Accessibility, etc.
In this section you get the chance to:
* Build a Tribute Page
* Build a Survey Form
* Build a Product Landing Page
* Build a Technical Documentation Page
* Build a Personal Portfolio Webpage
By the end of this, you would have 5 responsive websites under your belt that you can show off to friends, family, employers, etc. Have fun and remember to use the [Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514) method if you get stuck.
| packages/learn/src/introductions/responsive-web-design/index.md | 1 | https://github.com/freeCodeCamp/freeCodeCamp/commit/f3e8ecd1338b6b56bd7a0e9667e845a3f08796c8 | [
0.005228074733167887,
0.0026966920122504234,
0.00016530910215806216,
0.0026966920122504234,
0.0025313827209174633
] |
{
"id": 2,
"code_window": [
"superBlock: Responsive Web Design\n",
"---\n",
"## Introduction to the Responsive Web Design Projects\n",
"\n",
"This introduction is a stub\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"Time to put your newly learnt skills to work! By working on projects you would have the opportunity of applying all the skills, principles and concepts you have learnt so far HTML, CSS, Visual Design, Accessibility, etc. \n"
],
"file_path": "packages/learn/src/introductions/responsive-web-design/responsive-web-design-projects/index.md",
"type": "replace",
"edit_start_line_idx": 7
} | import React from 'react';
import { Router } from '@reach/router';
import RedirectHome from '../components/RedirectHome';
import ShowUnsubscribed from '../client-only-routes/ShowUnsubscribed';
function Unsubscribed() {
return (
<Router>
<ShowUnsubscribed path='/unsubscribed/:unsubscribeId' />
<ShowUnsubscribed path='/unsubscribed' />
<RedirectHome default={true} />
</Router>
);
}
Unsubscribed.displayName = 'Unsubscribed';
export default Unsubscribed;
| client/src/pages/unsubscribed.js | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/f3e8ecd1338b6b56bd7a0e9667e845a3f08796c8 | [
0.00017117591050919145,
0.0001703598245512694,
0.00016954373859334737,
0.0001703598245512694,
8.160859579220414e-7
] |
{
"id": 2,
"code_window": [
"superBlock: Responsive Web Design\n",
"---\n",
"## Introduction to the Responsive Web Design Projects\n",
"\n",
"This introduction is a stub\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"Time to put your newly learnt skills to work! By working on projects you would have the opportunity of applying all the skills, principles and concepts you have learnt so far HTML, CSS, Visual Design, Accessibility, etc. \n"
],
"file_path": "packages/learn/src/introductions/responsive-web-design/responsive-web-design-projects/index.md",
"type": "replace",
"edit_start_line_idx": 7
} | {
"name": "Linear Transformations",
"order": 7,
"challenges": [
{
"id": "59a5801209a6acac5983b586",
"title": "Linear transformations",
"description": [
""
],
"challengeSeed": [
""
],
"tests": [
""
]
},
{
"id": "59a5801209a6acac5983a812",
"title": "Injective linear transformations",
"description": [
""
],
"challengeSeed": [
""
],
"tests": [
""
]
},
{
"id": "59a5801209a6acac5983a813",
"title": "Surjective linear transformations",
"description": [
""
],
"challengeSeed": [
""
],
"tests": [
""
]
},
{
"id": "59a5801209a6acac5983a814",
"title": "Invertible linear transformations",
"description": [
""
],
"challengeSeed": [
""
],
"tests": [
""
]
}
]
} | curriculum/math-challenges/39-linear-algebra/linear-transformations.json | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/f3e8ecd1338b6b56bd7a0e9667e845a3f08796c8 | [
0.00017353883595205843,
0.00017054227646440268,
0.0001671722566243261,
0.00017007894348353148,
0.0000021887788079766324
] |
{
"id": 2,
"code_window": [
"superBlock: Responsive Web Design\n",
"---\n",
"## Introduction to the Responsive Web Design Projects\n",
"\n",
"This introduction is a stub\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"Time to put your newly learnt skills to work! By working on projects you would have the opportunity of applying all the skills, principles and concepts you have learnt so far HTML, CSS, Visual Design, Accessibility, etc. \n"
],
"file_path": "packages/learn/src/introductions/responsive-web-design/responsive-web-design-projects/index.md",
"type": "replace",
"edit_start_line_idx": 7
} | import React from 'react';
import PropTypes from 'prop-types';
import Helmet from 'react-helmet';
import differenceInMinutes from 'date-fns/difference_in_minutes';
import differenceInHours from 'date-fns/difference_in_hours';
import differenceInDays from 'date-fns/difference_in_calendar_days';
import format from 'date-fns/format';
import FontAwesomeIcon from '@fortawesome/react-fontawesome';
import { faCalendarAlt, faClock } from '@fortawesome/free-regular-svg-icons';
import { faFreeCodeCamp } from '@fortawesome/free-brands-svg-icons';
const propTypes = {
article: PropTypes.object
};
const styles = `
.meta-wrapper {
padding-top: 10px;
}
.meta-wrapper span,
.meta-wrapper a {
font-size: 16px;
}
.meta-item {
margin-right: 20px;
}
`;
function pluralise(singular, count) {
return `${singular}${count === 1 ? '' : 's'}`;
}
function getTimeString(pubDate) {
const now = new Date(Date.now());
const minuteDiff = differenceInMinutes(now, pubDate);
if (minuteDiff < 60) {
return `${minuteDiff} ${pluralise('minute', minuteDiff)} ago`;
}
const hourDiff = differenceInHours(now, pubDate);
if (hourDiff < 24) {
return `${hourDiff} ${pluralise('hour', hourDiff)} ago`;
}
const dayDiff = differenceInDays(now, pubDate);
if (dayDiff < 8) {
return `${dayDiff} ${pluralise('day', dayDiff)} ago`;
}
if (dayDiff < 365) {
return format(pubDate, 'MMM D');
}
return format(pubDate, 'MMM D YYYY');
}
function ArticleMeta({
article: { viewCount, author, meta, firstPublishedDate }
}) {
return (
<div className='meta-wrapper'>
<Helmet>
<style>{styles}</style>
</Helmet>
<div className='meta-item-wrapper'>
<span className='meta-item'>By {author.name}</span>
<span className='meta-item'>
<FontAwesomeIcon icon={faCalendarAlt} />{' '}
{getTimeString(firstPublishedDate)}
</span>
<span className='meta-item'>
<FontAwesomeIcon icon={faClock} /> {`${meta.readTime} minute read`}
</span>
{viewCount >= 100 ? (
<span className='meta-item'>
<FontAwesomeIcon icon={faFreeCodeCamp} /> {`${viewCount} views`}
</span>
) : null}
</div>
</div>
);
}
ArticleMeta.displayName = 'ArticleMeta';
ArticleMeta.propTypes = propTypes;
export default ArticleMeta;
| news/components/ArticleMeta.js | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/f3e8ecd1338b6b56bd7a0e9667e845a3f08796c8 | [
0.00017826670955400914,
0.0001715483667794615,
0.00016768726345617324,
0.00017124711303040385,
0.0000030476485335384496
] |
{
"id": 3,
"code_window": [
"\n",
"Help us make it real on [GitHub](https://github.com/freeCodeCamp/learn/tree/master/src/introductions).\n"
],
"labels": [
"keep",
"replace"
],
"after_edit": [
"In this section you get the chance to:\n",
" * Build a Tribute Page\n",
" * Build a Survey Form\n",
" * Build a Product Landing Page\n",
" * Build a Technical Documentation Page\n",
" * Build a Personal Portfolio Webpage\n",
"\n",
"By the end of this, you would have 5 responsive websites under your belt that you can show off to friends, family, employers, etc. Have fun and remember to use the [Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514) method if you get stuck."
],
"file_path": "packages/learn/src/introductions/responsive-web-design/responsive-web-design-projects/index.md",
"type": "replace",
"edit_start_line_idx": 9
} | ---
title: Introduction to the Responsive Web Design Projects
block: Responsive Web Design Projects
superBlock: Responsive Web Design
---
## Introduction to the Responsive Web Design Projects
This introduction is a stub
Help us make it real on [GitHub](https://github.com/freeCodeCamp/learn/tree/master/src/introductions). | packages/learn/src/introductions/responsive-web-design/responsive-web-design-projects/index.md | 1 | https://github.com/freeCodeCamp/freeCodeCamp/commit/f3e8ecd1338b6b56bd7a0e9667e845a3f08796c8 | [
0.04798240587115288,
0.024079211056232452,
0.00017601490253582597,
0.024079211056232452,
0.023903196677565575
] |
{
"id": 3,
"code_window": [
"\n",
"Help us make it real on [GitHub](https://github.com/freeCodeCamp/learn/tree/master/src/introductions).\n"
],
"labels": [
"keep",
"replace"
],
"after_edit": [
"In this section you get the chance to:\n",
" * Build a Tribute Page\n",
" * Build a Survey Form\n",
" * Build a Product Landing Page\n",
" * Build a Technical Documentation Page\n",
" * Build a Personal Portfolio Webpage\n",
"\n",
"By the end of this, you would have 5 responsive websites under your belt that you can show off to friends, family, employers, etc. Have fun and remember to use the [Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514) method if you get stuck."
],
"file_path": "packages/learn/src/introductions/responsive-web-design/responsive-web-design-projects/index.md",
"type": "replace",
"edit_start_line_idx": 9
} | .reset-modal-header {
color: #fff;
background-color: #d9534f;
border-color: #d43f3a;
}
.reset-modal-header .close {
color: #fff;
font-size: 28px;
text-shadow: none;
} | packages/learn/src/templates/Challenges/components/reset-modal.css | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/f3e8ecd1338b6b56bd7a0e9667e845a3f08796c8 | [
0.0001789610687410459,
0.00017249977099709213,
0.00016603845870122313,
0.00017249977099709213,
0.000006461305019911379
] |
{
"id": 3,
"code_window": [
"\n",
"Help us make it real on [GitHub](https://github.com/freeCodeCamp/learn/tree/master/src/introductions).\n"
],
"labels": [
"keep",
"replace"
],
"after_edit": [
"In this section you get the chance to:\n",
" * Build a Tribute Page\n",
" * Build a Survey Form\n",
" * Build a Product Landing Page\n",
" * Build a Technical Documentation Page\n",
" * Build a Personal Portfolio Webpage\n",
"\n",
"By the end of this, you would have 5 responsive websites under your belt that you can show off to friends, family, employers, etc. Have fun and remember to use the [Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514) method if you get stuck."
],
"file_path": "packages/learn/src/introductions/responsive-web-design/responsive-web-design-projects/index.md",
"type": "replace",
"edit_start_line_idx": 9
} | import React from 'react';
import { Grid, Row, Col, Image } from '@freecodecamp/react-bootstrap';
import FontAwesomeIcon from '@fortawesome/react-fontawesome';
import {
faHtml5,
faCss3Alt,
faJs,
faGithub,
faNodeJs,
faReact
} from '@fortawesome/free-brands-svg-icons';
import { faDatabase } from '@fortawesome/free-solid-svg-icons';
import Helmet from 'react-helmet';
import { Spacer } from '../components/helpers';
import Layout from '../components/Layout';
import Login from '../components/Header/components/Login';
import './index.css';
const BigCallToAction = () => (
<Row>
<Col sm={8} smOffset={2} xs={12}>
<Login block={true}>Start coding (it's free)</Login>
</Col>
</Row>
);
const IndexPage = () => (
<Layout disableSettings={true} landingPage={true}>
<Helmet>
<title>Learn to code | freeCodeCamp.org</title>
</Helmet>
<Spacer />
<Spacer />
<Grid className='text-center'>
<Row>
<h1 className='big-heading'>Learn to code for free.</h1>
<Spacer />
<Col md={4} sm={12}>
<Image
alt={
'Get great references and connections to start your software ' +
'engineer career'
}
className='landing-icon img-center'
responsive={true}
src={
'https://s3.amazonaws.com/freecodecamp/landing-icon-community.svg'
}
/>
<p className='large-p'>
Join a supportive community of millions of coders.
</p>
</Col>
<Col md={4} sm={12}>
<Image
alt='Help nonprofits with bro bono code projects'
className='landing-icon img-center'
responsive={true}
src={
'https://s3.amazonaws.com/freecodecamp/landing-icon-' +
'certificate.svg'
}
/>
<p className='large-p'>
Build projects and earn free certifications.
</p>
</Col>
<Col md={4} sm={12}>
<Image
alt={
'Get hired as a developer and start your software engineer career'
}
className='landing-icon img-center'
responsive={true}
src={
'https://s3.amazonaws.com/freecodecamp/landing-icon-' +
'experience.svg'
}
/>
<p className='large-p'>Get experience by coding for nonprofits.</p>
</Col>
</Row>
<Spacer />
<Spacer />
<BigCallToAction />
<Spacer />
<h2>As featured in:</h2>
<Image
className='img-center'
responsive={true}
src='https://s3.amazonaws.com/freecodecamp/as-seen-on.png'
/>
<Spacer />
<hr />
<Spacer />
<h2>Launch your developer career</h2>
<Spacer />
<Row>
<Col md={4} sm={12}>
<Image
alt="Meta's testimonial image"
className='testimonial-image img-center'
responsive={true}
src='https://i.imgur.com/nsvNixW.jpg'
/>
<p className='testimonial-copy'>
Through freeCodeCamp, I built a robust and highly functional web app
for a nonprofit. This led me to getting a fantastic job.
</p>
<h3>- Meta Hirschl</h3>
</Col>
<Col md={4} sm={12}>
<Image
alt="Brian's testimonial image"
className='testimonial-image img-center'
responsive={true}
src='https://i.imgur.com/QPpjPac.jpg'
/>
<p className='testimonial-copy'>
freeCodeCamp is a great way for disabled veterans like me to
retrain. I'm already receiving software engineering job offers.
</p>
<h3>- Brian Grant</h3>
</Col>
<Col md={4} sm={12}>
<Image
alt="Maxim Orlov's testimonial image"
className='testimonial-image img-center'
responsive={true}
src='https://i.imgur.com/wjlDigg.jpg'
/>
<p className='testimonial-copy'>
I joined freeCodeCamp with zero knowledge of web development. 6
months later, I landed my first job as a back end engineer.
</p>
<h3>- Maxim Orlov</h3>
</Col>
</Row>
<Spacer />
<hr />
<Spacer />
<h2>Learn powerful skills</h2>
<Spacer />
<Row className='text-center'>
<Col md={3} sm={6} xs={12}>
<FontAwesomeIcon
className='landing-skill-icon'
icon={faHtml5}
size='9x'
/>
<h2 className='black-text'>HTML5</h2>
</Col>
<Col md={3} sm={6} xs={12}>
<FontAwesomeIcon
className='landing-skill-icon'
icon={faCss3Alt}
size='9x'
/>
<h2 className='black-text'>CSS3</h2>
</Col>
<Col md={3} sm={6} xs={12}>
<FontAwesomeIcon
className='landing-skill-icon'
icon={faJs}
size='9x'
/>
<h2 className='black-text'>JavaScript</h2>
</Col>
<Col md={3} sm={6} xs={12}>
<FontAwesomeIcon
className='landing-skill-icon'
icon={faDatabase}
size='9x'
/>
<h2 className='black-text'>Databases</h2>
</Col>
</Row>
<Row className='text-center'>
<Col md={3} sm={6} xs={12}>
<FontAwesomeIcon
className='landing-skill-icon'
icon={faGithub}
size='9x'
/>
<h2 className='black-text'>Git & GitHub</h2>
</Col>
<Col md={3} sm={6} xs={12}>
<FontAwesomeIcon
className='landing-skill-icon'
icon={faNodeJs}
size='9x'
/>
<h2 className='black-text'>Node.js</h2>
</Col>
<Col md={3} sm={6} xs={12}>
<FontAwesomeIcon
className='landing-skill-icon'
icon={faReact}
size='9x'
/>
<h2 className='black-text'>React.js</h2>
</Col>
<Col md={3} sm={6} xs={12}>
<Image
alt='The D3.js Logo'
className='landing-skill-icon custom-landing-skill-icon'
src='https://s3.amazonaws.com/freecodecamp/d3-logo.svg'
/>
<h2 className='black-text'>D3.js</h2>
</Col>
</Row>
<Spacer />
<BigCallToAction />
<Spacer />
<Spacer />
<hr />
<Spacer />
<Spacer />
<Spacer />
</Grid>
</Layout>
);
export default IndexPage;
| client/src/pages/index.js | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/f3e8ecd1338b6b56bd7a0e9667e845a3f08796c8 | [
0.0002568535855971277,
0.0001816057920223102,
0.00016594254702795297,
0.00017026140994857997,
0.00002363101884839125
] |
{
"id": 3,
"code_window": [
"\n",
"Help us make it real on [GitHub](https://github.com/freeCodeCamp/learn/tree/master/src/introductions).\n"
],
"labels": [
"keep",
"replace"
],
"after_edit": [
"In this section you get the chance to:\n",
" * Build a Tribute Page\n",
" * Build a Survey Form\n",
" * Build a Product Landing Page\n",
" * Build a Technical Documentation Page\n",
" * Build a Personal Portfolio Webpage\n",
"\n",
"By the end of this, you would have 5 responsive websites under your belt that you can show off to friends, family, employers, etc. Have fun and remember to use the [Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514) method if you get stuck."
],
"file_path": "packages/learn/src/introductions/responsive-web-design/responsive-web-design-projects/index.md",
"type": "replace",
"edit_start_line_idx": 9
} | /* eslint-disable no-eval, no-process-exit */
import fs from 'fs-extra';
import path from 'path';
import {UnpackedChallenge, ChallengeFile} from './unpackedChallenge';
// Repack all challenges from all
// seed/unpacked/00-foo/bar/000-xxx-id.html files
// into
// seed/challenges/00-foo/bar.json files
let unpackedRoot = path.join(__dirname, 'unpacked');
let seedChallengesRoot = path.join(__dirname, 'challenges');
function directoriesIn(parentDir) {
return fs.readdirSync(parentDir)
.filter(entry => fs.statSync(path.join(parentDir, entry)).isDirectory());
}
let superBlocks = directoriesIn(unpackedRoot);
superBlocks.forEach(superBlock => {
let superBlockPath = path.join(unpackedRoot, superBlock);
console.log(`Repacking ${superBlockPath}...`);
let blocks = directoriesIn(superBlockPath);
blocks.forEach(blockName => {
let blockPath = path.join(superBlockPath, blockName);
let blockFilePath = path.join(blockPath, blockName + '.json');
let block = require(blockFilePath);
let index = 0;
block.challenges.forEach(challengeJson => {
let unpackedChallenge =
new UnpackedChallenge(blockPath, challengeJson, index);
let unpackedFile = unpackedChallenge.challengeFile();
let chunks = unpackedFile.readChunks();
Object.assign(block.challenges[ index ], chunks);
index += 1;
});
let outputFilePath =
path.join(seedChallengesRoot, superBlock, blockName + '.json');
// todo: async
fs.writeFileSync(outputFilePath, JSON.stringify(block, null, 2));
});
});
// let challenges = getChallenges();
// challenges.forEach(challengeBlock => {
// console.log()
// });
| curriculum/repack.js | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/f3e8ecd1338b6b56bd7a0e9667e845a3f08796c8 | [
0.00017516555089969188,
0.00016939901979640126,
0.00016741183935664594,
0.00016825419152155519,
0.0000027143012175656622
] |
{
"id": 0,
"code_window": [
" styleOverrides?: ComponentsOverrides<Theme>['MuiSpeedDialIcon'];\n",
" variants?: ComponentsVariants['MuiSpeedDialIcon'];\n",
" };\n",
" MuiStack?: {\n",
" defaultProps?: ComponentsProps['MuiStack'];\n",
" variants?: ComponentsVariants['MuiStack'];\n",
" };\n",
" MuiStep?: {\n",
" defaultProps?: ComponentsProps['MuiStep'];\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" styleOverrides?: ComponentsOverrides<Theme>['MuiStack'];\n"
],
"file_path": "packages/mui-material/src/styles/components.d.ts",
"type": "add",
"edit_start_line_idx": 445
} | import { ComponentsProps } from './props';
import { ComponentsOverrides } from './overrides';
import { ComponentsVariants } from './variants';
export interface Components<Theme = unknown> {
MuiAlert?: {
defaultProps?: ComponentsProps['MuiAlert'];
styleOverrides?: ComponentsOverrides<Theme>['MuiAlert'];
variants?: ComponentsVariants['MuiAlert'];
};
MuiAlertTitle?: {
defaultProps?: ComponentsProps['MuiAlertTitle'];
styleOverrides?: ComponentsOverrides<Theme>['MuiAlertTitle'];
variants?: ComponentsVariants['MuiAlertTitle'];
};
MuiAppBar?: {
defaultProps?: ComponentsProps['MuiAppBar'];
styleOverrides?: ComponentsOverrides<Theme>['MuiAppBar'];
variants?: ComponentsVariants['MuiAppBar'];
};
MuiAutocomplete?: {
defaultProps?: ComponentsProps['MuiAutocomplete'];
styleOverrides?: ComponentsOverrides<Theme>['MuiAutocomplete'];
variants?: ComponentsVariants['MuiAutocomplete'];
};
MuiAvatar?: {
defaultProps?: ComponentsProps['MuiAvatar'];
styleOverrides?: ComponentsOverrides<Theme>['MuiAvatar'];
variants?: ComponentsVariants['MuiAvatar'];
};
MuiAvatarGroup?: {
defaultProps?: ComponentsProps['MuiAvatarGroup'];
styleOverrides?: ComponentsOverrides<Theme>['MuiAvatarGroup'];
variants?: ComponentsVariants['MuiAvatarGroup'];
};
MuiBackdrop?: {
defaultProps?: ComponentsProps['MuiBackdrop'];
styleOverrides?: ComponentsOverrides<Theme>['MuiBackdrop'];
variants?: ComponentsVariants['MuiBackdrop'];
};
MuiBadge?: {
defaultProps?: ComponentsProps['MuiBadge'];
styleOverrides?: ComponentsOverrides<Theme>['MuiBadge'];
variants?: ComponentsVariants['MuiBadge'];
};
MuiBottomNavigation?: {
defaultProps?: ComponentsProps['MuiBottomNavigation'];
styleOverrides?: ComponentsOverrides<Theme>['MuiBottomNavigation'];
variants?: ComponentsVariants['MuiBottomNavigation'];
};
MuiBottomNavigationAction?: {
defaultProps?: ComponentsProps['MuiBottomNavigationAction'];
styleOverrides?: ComponentsOverrides<Theme>['MuiBottomNavigationAction'];
variants?: ComponentsVariants['MuiBottomNavigationAction'];
};
MuiBreadcrumbs?: {
defaultProps?: ComponentsProps['MuiBreadcrumbs'];
styleOverrides?: ComponentsOverrides<Theme>['MuiBreadcrumbs'];
variants?: ComponentsVariants['MuiBreadcrumbs'];
};
MuiButton?: {
defaultProps?: ComponentsProps['MuiButton'];
styleOverrides?: ComponentsOverrides<Theme>['MuiButton'];
variants?: ComponentsVariants['MuiButton'];
};
MuiButtonBase?: {
defaultProps?: ComponentsProps['MuiButtonBase'];
styleOverrides?: ComponentsOverrides<Theme>['MuiButtonBase'];
variants?: ComponentsVariants['MuiButtonBase'];
};
MuiButtonGroup?: {
defaultProps?: ComponentsProps['MuiButtonGroup'];
styleOverrides?: ComponentsOverrides<Theme>['MuiButtonGroup'];
variants?: ComponentsVariants['MuiButtonGroup'];
};
MuiCard?: {
defaultProps?: ComponentsProps['MuiCard'];
styleOverrides?: ComponentsOverrides<Theme>['MuiCard'];
variants?: ComponentsVariants['MuiCard'];
};
MuiCardActionArea?: {
defaultProps?: ComponentsProps['MuiCardActionArea'];
styleOverrides?: ComponentsOverrides<Theme>['MuiCardActionArea'];
variants?: ComponentsVariants['MuiCardActionArea'];
};
MuiCardActions?: {
defaultProps?: ComponentsProps['MuiCardActions'];
styleOverrides?: ComponentsOverrides<Theme>['MuiCardActions'];
variants?: ComponentsVariants['MuiCardActions'];
};
MuiCardContent?: {
defaultProps?: ComponentsProps['MuiCardContent'];
styleOverrides?: ComponentsOverrides<Theme>['MuiCardContent'];
variants?: ComponentsVariants['MuiCardContent'];
};
MuiCardHeader?: {
defaultProps?: ComponentsProps['MuiCardHeader'];
styleOverrides?: ComponentsOverrides<Theme>['MuiCardHeader'];
variants?: ComponentsVariants['MuiCardHeader'];
};
MuiCardMedia?: {
defaultProps?: ComponentsProps['MuiCardMedia'];
styleOverrides?: ComponentsOverrides<Theme>['MuiCardMedia'];
variants?: ComponentsVariants['MuiCardMedia'];
};
MuiCheckbox?: {
defaultProps?: ComponentsProps['MuiCheckbox'];
styleOverrides?: ComponentsOverrides<Theme>['MuiCheckbox'];
variants?: ComponentsVariants['MuiCheckbox'];
};
MuiChip?: {
defaultProps?: ComponentsProps['MuiChip'];
styleOverrides?: ComponentsOverrides<Theme>['MuiChip'];
variants?: ComponentsVariants['MuiChip'];
};
MuiCircularProgress?: {
defaultProps?: ComponentsProps['MuiCircularProgress'];
styleOverrides?: ComponentsOverrides<Theme>['MuiCircularProgress'];
variants?: ComponentsVariants['MuiCircularProgress'];
};
MuiCollapse?: {
defaultProps?: ComponentsProps['MuiCollapse'];
styleOverrides?: ComponentsOverrides<Theme>['MuiCollapse'];
variants?: ComponentsVariants['MuiCollapse'];
};
MuiContainer?: {
defaultProps?: ComponentsProps['MuiContainer'];
styleOverrides?: ComponentsOverrides<Theme>['MuiContainer'];
variants?: ComponentsVariants['MuiContainer'];
};
MuiCssBaseline?: {
defaultProps?: ComponentsProps['MuiCssBaseline'];
styleOverrides?: ComponentsOverrides<Theme>['MuiCssBaseline'];
variants?: ComponentsVariants['MuiCssBaseline'];
};
MuiDialog?: {
defaultProps?: ComponentsProps['MuiDialog'];
styleOverrides?: ComponentsOverrides<Theme>['MuiDialog'];
variants?: ComponentsVariants['MuiDialog'];
};
MuiDialogActions?: {
defaultProps?: ComponentsProps['MuiDialogActions'];
styleOverrides?: ComponentsOverrides<Theme>['MuiDialogActions'];
variants?: ComponentsVariants['MuiDialogActions'];
};
MuiDialogContent?: {
defaultProps?: ComponentsProps['MuiDialogContent'];
styleOverrides?: ComponentsOverrides<Theme>['MuiDialogContent'];
variants?: ComponentsVariants['MuiDialogContent'];
};
MuiDialogContentText?: {
defaultProps?: ComponentsProps['MuiDialogContentText'];
styleOverrides?: ComponentsOverrides<Theme>['MuiDialogContentText'];
variants?: ComponentsVariants['MuiDialogContentText'];
};
MuiDialogTitle?: {
defaultProps?: ComponentsProps['MuiDialogTitle'];
styleOverrides?: ComponentsOverrides<Theme>['MuiDialogTitle'];
variants?: ComponentsVariants['MuiDialogTitle'];
};
MuiDivider?: {
defaultProps?: ComponentsProps['MuiDivider'];
styleOverrides?: ComponentsOverrides<Theme>['MuiDivider'];
variants?: ComponentsVariants['MuiDivider'];
};
MuiDrawer?: {
defaultProps?: ComponentsProps['MuiDrawer'];
styleOverrides?: ComponentsOverrides<Theme>['MuiDrawer'];
variants?: ComponentsVariants['MuiDrawer'];
};
MuiAccordion?: {
defaultProps?: ComponentsProps['MuiAccordion'];
styleOverrides?: ComponentsOverrides<Theme>['MuiAccordion'];
variants?: ComponentsVariants['MuiAccordion'];
};
MuiAccordionActions?: {
defaultProps?: ComponentsProps['MuiAccordionActions'];
styleOverrides?: ComponentsOverrides<Theme>['MuiAccordionActions'];
variants?: ComponentsVariants['MuiAccordionActions'];
};
MuiAccordionDetails?: {
defaultProps?: ComponentsProps['MuiAccordionDetails'];
styleOverrides?: ComponentsOverrides<Theme>['MuiAccordionDetails'];
variants?: ComponentsVariants['MuiAccordionDetails'];
};
MuiAccordionSummary?: {
defaultProps?: ComponentsProps['MuiAccordionSummary'];
styleOverrides?: ComponentsOverrides<Theme>['MuiAccordionSummary'];
variants?: ComponentsVariants['MuiAccordionSummary'];
};
MuiFab?: {
defaultProps?: ComponentsProps['MuiFab'];
styleOverrides?: ComponentsOverrides<Theme>['MuiFab'];
variants?: ComponentsVariants['MuiFab'];
};
MuiFilledInput?: {
defaultProps?: ComponentsProps['MuiFilledInput'];
styleOverrides?: ComponentsOverrides<Theme>['MuiFilledInput'];
variants?: ComponentsVariants['MuiFilledInput'];
};
MuiFormControl?: {
defaultProps?: ComponentsProps['MuiFormControl'];
styleOverrides?: ComponentsOverrides<Theme>['MuiFormControl'];
variants?: ComponentsVariants['MuiFormControl'];
};
MuiFormControlLabel?: {
defaultProps?: ComponentsProps['MuiFormControlLabel'];
styleOverrides?: ComponentsOverrides<Theme>['MuiFormControlLabel'];
variants?: ComponentsVariants['MuiFormControlLabel'];
};
MuiFormGroup?: {
defaultProps?: ComponentsProps['MuiFormGroup'];
styleOverrides?: ComponentsOverrides<Theme>['MuiFormGroup'];
variants?: ComponentsVariants['MuiFormGroup'];
};
MuiFormHelperText?: {
defaultProps?: ComponentsProps['MuiFormHelperText'];
styleOverrides?: ComponentsOverrides<Theme>['MuiFormHelperText'];
variants?: ComponentsVariants['MuiFormHelperText'];
};
MuiFormLabel?: {
defaultProps?: ComponentsProps['MuiFormLabel'];
styleOverrides?: ComponentsOverrides<Theme>['MuiFormLabel'];
variants?: ComponentsVariants['MuiFormLabel'];
};
MuiGrid?: {
defaultProps?: ComponentsProps['MuiGrid'];
styleOverrides?: ComponentsOverrides<Theme>['MuiGrid'];
variants?: ComponentsVariants['MuiGrid'];
};
MuiGrid2?: {
defaultProps?: ComponentsProps['MuiGrid2'];
styleOverrides?: ComponentsOverrides<Theme>['MuiGrid2'];
variants?: ComponentsVariants['MuiGrid2'];
};
MuiImageList?: {
defaultProps?: ComponentsProps['MuiImageList'];
styleOverrides?: ComponentsOverrides<Theme>['MuiImageList'];
variants?: ComponentsVariants['MuiImageList'];
};
MuiImageListItem?: {
defaultProps?: ComponentsProps['MuiImageListItem'];
styleOverrides?: ComponentsOverrides<Theme>['MuiImageListItem'];
variants?: ComponentsVariants['MuiImageListItem'];
};
MuiImageListItemBar?: {
defaultProps?: ComponentsProps['MuiImageListItemBar'];
styleOverrides?: ComponentsOverrides<Theme>['MuiImageListItemBar'];
variants?: ComponentsVariants['MuiImageListItemBar'];
};
MuiIcon?: {
defaultProps?: ComponentsProps['MuiIcon'];
styleOverrides?: ComponentsOverrides<Theme>['MuiIcon'];
variants?: ComponentsVariants['MuiIcon'];
};
MuiIconButton?: {
defaultProps?: ComponentsProps['MuiIconButton'];
styleOverrides?: ComponentsOverrides<Theme>['MuiIconButton'];
variants?: ComponentsVariants['MuiIconButton'];
};
MuiInput?: {
defaultProps?: ComponentsProps['MuiInput'];
styleOverrides?: ComponentsOverrides<Theme>['MuiInput'];
variants?: ComponentsVariants['MuiInput'];
};
MuiInputAdornment?: {
defaultProps?: ComponentsProps['MuiInputAdornment'];
styleOverrides?: ComponentsOverrides<Theme>['MuiInputAdornment'];
variants?: ComponentsVariants['MuiInputAdornment'];
};
MuiInputBase?: {
defaultProps?: ComponentsProps['MuiInputBase'];
styleOverrides?: ComponentsOverrides<Theme>['MuiInputBase'];
variants?: ComponentsVariants['MuiInputBase'];
};
MuiInputLabel?: {
defaultProps?: ComponentsProps['MuiInputLabel'];
styleOverrides?: ComponentsOverrides<Theme>['MuiInputLabel'];
variants?: ComponentsVariants['MuiInputLabel'];
};
MuiLinearProgress?: {
defaultProps?: ComponentsProps['MuiLinearProgress'];
styleOverrides?: ComponentsOverrides<Theme>['MuiLinearProgress'];
variants?: ComponentsVariants['MuiLinearProgress'];
};
MuiLink?: {
defaultProps?: ComponentsProps['MuiLink'];
styleOverrides?: ComponentsOverrides<Theme>['MuiLink'];
variants?: ComponentsVariants['MuiLink'];
};
MuiList?: {
defaultProps?: ComponentsProps['MuiList'];
styleOverrides?: ComponentsOverrides<Theme>['MuiList'];
variants?: ComponentsVariants['MuiList'];
};
MuiListItem?: {
defaultProps?: ComponentsProps['MuiListItem'];
styleOverrides?: ComponentsOverrides<Theme>['MuiListItem'];
variants?: ComponentsVariants['MuiListItem'];
};
MuiListItemButton?: {
defaultProps?: ComponentsProps['MuiListItemButton'];
styleOverrides?: ComponentsOverrides<Theme>['MuiListItemButton'];
variants?: ComponentsVariants['MuiListItemButton'];
};
MuiListItemAvatar?: {
defaultProps?: ComponentsProps['MuiListItemAvatar'];
styleOverrides?: ComponentsOverrides<Theme>['MuiListItemAvatar'];
variants?: ComponentsVariants['MuiListItemAvatar'];
};
MuiListItemIcon?: {
defaultProps?: ComponentsProps['MuiListItemIcon'];
styleOverrides?: ComponentsOverrides<Theme>['MuiListItemIcon'];
variants?: ComponentsVariants['MuiListItemIcon'];
};
MuiListItemSecondaryAction?: {
defaultProps?: ComponentsProps['MuiListItemSecondaryAction'];
styleOverrides?: ComponentsOverrides<Theme>['MuiListItemSecondaryAction'];
variants?: ComponentsVariants['MuiListItemSecondaryAction'];
};
MuiListItemText?: {
defaultProps?: ComponentsProps['MuiListItemText'];
styleOverrides?: ComponentsOverrides<Theme>['MuiListItemText'];
variants?: ComponentsVariants['MuiListItemText'];
};
MuiListSubheader?: {
defaultProps?: ComponentsProps['MuiListSubheader'];
styleOverrides?: ComponentsOverrides<Theme>['MuiListSubheader'];
variants?: ComponentsVariants['MuiListSubheader'];
};
MuiMenu?: {
defaultProps?: ComponentsProps['MuiMenu'];
styleOverrides?: ComponentsOverrides<Theme>['MuiMenu'];
variants?: ComponentsVariants['MuiMenu'];
};
MuiMenuItem?: {
defaultProps?: ComponentsProps['MuiMenuItem'];
styleOverrides?: ComponentsOverrides<Theme>['MuiMenuItem'];
variants?: ComponentsVariants['MuiMenuItem'];
};
MuiMenuList?: {
defaultProps?: ComponentsProps['MuiMenuList'];
styleOverrides?: ComponentsOverrides<Theme>['MuiMenuList'];
variants?: ComponentsVariants['MuiMenuList'];
};
MuiMobileStepper?: {
defaultProps?: ComponentsProps['MuiMobileStepper'];
styleOverrides?: ComponentsOverrides<Theme>['MuiMobileStepper'];
variants?: ComponentsVariants['MuiMobileStepper'];
};
MuiModal?: {
defaultProps?: ComponentsProps['MuiModal'];
styleOverrides?: ComponentsOverrides<Theme>['MuiModal'];
variants?: ComponentsVariants['MuiModal'];
};
MuiNativeSelect?: {
defaultProps?: ComponentsProps['MuiNativeSelect'];
styleOverrides?: ComponentsOverrides<Theme>['MuiNativeSelect'];
variants?: ComponentsVariants['MuiNativeSelect'];
};
MuiOutlinedInput?: {
defaultProps?: ComponentsProps['MuiOutlinedInput'];
styleOverrides?: ComponentsOverrides<Theme>['MuiOutlinedInput'];
variants?: ComponentsVariants['MuiOutlinedInput'];
};
MuiPagination?: {
defaultProps?: ComponentsProps['MuiPagination'];
styleOverrides?: ComponentsOverrides<Theme>['MuiPagination'];
variants?: ComponentsVariants['MuiPagination'];
};
MuiPaginationItem?: {
defaultProps?: ComponentsProps['MuiPaginationItem'];
styleOverrides?: ComponentsOverrides<Theme>['MuiPaginationItem'];
variants?: ComponentsVariants['MuiPaginationItem'];
};
MuiPaper?: {
defaultProps?: ComponentsProps['MuiPaper'];
styleOverrides?: ComponentsOverrides<Theme>['MuiPaper'];
variants?: ComponentsVariants['MuiPaper'];
};
MuiPopper?: {
defaultProps?: ComponentsProps['MuiPopper'];
};
MuiPopover?: {
defaultProps?: ComponentsProps['MuiPopover'];
styleOverrides?: ComponentsOverrides<Theme>['MuiPopover'];
variants?: ComponentsVariants['MuiPopover'];
};
MuiRadio?: {
defaultProps?: ComponentsProps['MuiRadio'];
styleOverrides?: ComponentsOverrides<Theme>['MuiRadio'];
variants?: ComponentsVariants['MuiRadio'];
};
MuiRating?: {
defaultProps?: ComponentsProps['MuiRating'];
styleOverrides?: ComponentsOverrides<Theme>['MuiRating'];
variants?: ComponentsVariants['MuiRating'];
};
MuiScopedCssBaseline?: {
defaultProps?: ComponentsProps['MuiScopedCssBaseline'];
styleOverrides?: ComponentsOverrides<Theme>['MuiScopedCssBaseline'];
variants?: ComponentsVariants['MuiScopedCssBaseline'];
};
MuiSelect?: {
defaultProps?: ComponentsProps['MuiSelect'];
styleOverrides?: ComponentsOverrides<Theme>['MuiSelect'];
variants?: ComponentsVariants['MuiSelect'];
};
MuiSkeleton?: {
defaultProps?: ComponentsProps['MuiSkeleton'];
styleOverrides?: ComponentsOverrides<Theme>['MuiSkeleton'];
variants?: ComponentsVariants['MuiSkeleton'];
};
MuiSlider?: {
defaultProps?: ComponentsProps['MuiSlider'];
styleOverrides?: ComponentsOverrides<Theme>['MuiSlider'];
variants?: ComponentsVariants['MuiSlider'];
};
MuiSnackbar?: {
defaultProps?: ComponentsProps['MuiSnackbar'];
styleOverrides?: ComponentsOverrides<Theme>['MuiSnackbar'];
variants?: ComponentsVariants['MuiSnackbar'];
};
MuiSnackbarContent?: {
defaultProps?: ComponentsProps['MuiSnackbarContent'];
styleOverrides?: ComponentsOverrides<Theme>['MuiSnackbarContent'];
variants?: ComponentsVariants['MuiSnackbarContent'];
};
MuiSpeedDial?: {
defaultProps?: ComponentsProps['MuiSpeedDial'];
styleOverrides?: ComponentsOverrides<Theme>['MuiSpeedDial'];
variants?: ComponentsVariants['MuiSpeedDial'];
};
MuiSpeedDialAction?: {
defaultProps?: ComponentsProps['MuiSpeedDialAction'];
styleOverrides?: ComponentsOverrides<Theme>['MuiSpeedDialAction'];
variants?: ComponentsVariants['MuiSpeedDialAction'];
};
MuiSpeedDialIcon?: {
defaultProps?: ComponentsProps['MuiSpeedDialIcon'];
styleOverrides?: ComponentsOverrides<Theme>['MuiSpeedDialIcon'];
variants?: ComponentsVariants['MuiSpeedDialIcon'];
};
MuiStack?: {
defaultProps?: ComponentsProps['MuiStack'];
variants?: ComponentsVariants['MuiStack'];
};
MuiStep?: {
defaultProps?: ComponentsProps['MuiStep'];
styleOverrides?: ComponentsOverrides<Theme>['MuiStep'];
variants?: ComponentsVariants['MuiStep'];
};
MuiStepButton?: {
defaultProps?: ComponentsProps['MuiStepButton'];
styleOverrides?: ComponentsOverrides<Theme>['MuiStepButton'];
variants?: ComponentsVariants['MuiStepButton'];
};
MuiStepConnector?: {
defaultProps?: ComponentsProps['MuiStepConnector'];
styleOverrides?: ComponentsOverrides<Theme>['MuiStepConnector'];
variants?: ComponentsVariants['MuiStepConnector'];
};
MuiStepContent?: {
defaultProps?: ComponentsProps['MuiStepContent'];
styleOverrides?: ComponentsOverrides<Theme>['MuiStepContent'];
variants?: ComponentsVariants['MuiStepContent'];
};
MuiStepIcon?: {
defaultProps?: ComponentsProps['MuiStepIcon'];
styleOverrides?: ComponentsOverrides<Theme>['MuiStepIcon'];
variants?: ComponentsVariants['MuiStepIcon'];
};
MuiStepLabel?: {
defaultProps?: ComponentsProps['MuiStepLabel'];
styleOverrides?: ComponentsOverrides<Theme>['MuiStepLabel'];
variants?: ComponentsVariants['MuiStepLabel'];
};
MuiStepper?: {
defaultProps?: ComponentsProps['MuiStepper'];
styleOverrides?: ComponentsOverrides<Theme>['MuiStepper'];
variants?: ComponentsVariants['MuiStepper'];
};
MuiSvgIcon?: {
defaultProps?: ComponentsProps['MuiSvgIcon'];
styleOverrides?: ComponentsOverrides<Theme>['MuiSvgIcon'];
variants?: ComponentsVariants['MuiSvgIcon'];
};
MuiSwipeableDrawer?: {
defaultProps?: ComponentsProps['MuiSwipeableDrawer'];
};
MuiSwitch?: {
defaultProps?: ComponentsProps['MuiSwitch'];
styleOverrides?: ComponentsOverrides<Theme>['MuiSwitch'];
variants?: ComponentsVariants['MuiSwitch'];
};
MuiTab?: {
defaultProps?: ComponentsProps['MuiTab'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTab'];
variants?: ComponentsVariants['MuiTab'];
};
MuiTable?: {
defaultProps?: ComponentsProps['MuiTable'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTable'];
variants?: ComponentsVariants['MuiTable'];
};
MuiTableBody?: {
defaultProps?: ComponentsProps['MuiTableBody'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTableBody'];
variants?: ComponentsVariants['MuiTableBody'];
};
MuiTableCell?: {
defaultProps?: ComponentsProps['MuiTableCell'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTableCell'];
variants?: ComponentsVariants['MuiTableCell'];
};
MuiTableContainer?: {
defaultProps?: ComponentsProps['MuiTableContainer'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTableContainer'];
variants?: ComponentsVariants['MuiTableContainer'];
};
MuiTableFooter?: {
defaultProps?: ComponentsProps['MuiTableFooter'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTableFooter'];
variants?: ComponentsVariants['MuiTableFooter'];
};
MuiTableHead?: {
defaultProps?: ComponentsProps['MuiTableHead'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTableHead'];
variants?: ComponentsVariants['MuiTableHead'];
};
MuiTablePagination?: {
defaultProps?: ComponentsProps['MuiTablePagination'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTablePagination'];
variants?: ComponentsVariants['MuiTablePagination'];
};
MuiTableRow?: {
defaultProps?: ComponentsProps['MuiTableRow'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTableRow'];
variants?: ComponentsVariants['MuiTableRow'];
};
MuiTableSortLabel?: {
defaultProps?: ComponentsProps['MuiTableSortLabel'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTableSortLabel'];
variants?: ComponentsVariants['MuiTableSortLabel'];
};
MuiTabs?: {
defaultProps?: ComponentsProps['MuiTabs'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTabs'];
variants?: ComponentsVariants['MuiTabs'];
};
MuiTextField?: {
defaultProps?: ComponentsProps['MuiTextField'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTextField'];
variants?: ComponentsVariants['MuiTextField'];
};
MuiToggleButton?: {
defaultProps?: ComponentsProps['MuiToggleButton'];
styleOverrides?: ComponentsOverrides<Theme>['MuiToggleButton'];
variants?: ComponentsVariants['MuiToggleButton'];
};
MuiToggleButtonGroup?: {
defaultProps?: ComponentsProps['MuiToggleButtonGroup'];
styleOverrides?: ComponentsOverrides<Theme>['MuiToggleButtonGroup'];
variants?: ComponentsVariants['MuiToggleButtonGroup'];
};
MuiToolbar?: {
defaultProps?: ComponentsProps['MuiToolbar'];
styleOverrides?: ComponentsOverrides<Theme>['MuiToolbar'];
variants?: ComponentsVariants['MuiToolbar'];
};
MuiTooltip?: {
defaultProps?: ComponentsProps['MuiTooltip'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTooltip'];
variants?: ComponentsVariants['MuiTooltip'];
};
MuiTouchRipple?: {
defaultProps?: ComponentsProps['MuiTouchRipple'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTouchRipple'];
variants?: ComponentsVariants['MuiTouchRipple'];
};
MuiTypography?: {
defaultProps?: ComponentsProps['MuiTypography'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTypography'];
variants?: ComponentsVariants['MuiTypography'];
};
MuiUseMediaQuery?: {
defaultProps?: ComponentsProps['MuiUseMediaQuery'];
};
}
| packages/mui-material/src/styles/components.d.ts | 1 | https://github.com/mui/material-ui/commit/8f06a1efc80f1289a65b6c1262fe769411d2e71c | [
0.9954219460487366,
0.06413639336824417,
0.012132485397160053,
0.03196597099304199,
0.13542070984840393
] |
{
"id": 0,
"code_window": [
" styleOverrides?: ComponentsOverrides<Theme>['MuiSpeedDialIcon'];\n",
" variants?: ComponentsVariants['MuiSpeedDialIcon'];\n",
" };\n",
" MuiStack?: {\n",
" defaultProps?: ComponentsProps['MuiStack'];\n",
" variants?: ComponentsVariants['MuiStack'];\n",
" };\n",
" MuiStep?: {\n",
" defaultProps?: ComponentsProps['MuiStep'];\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" styleOverrides?: ComponentsOverrides<Theme>['MuiStack'];\n"
],
"file_path": "packages/mui-material/src/styles/components.d.ts",
"type": "add",
"edit_start_line_idx": 445
} | "use client";
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M17 4h-3V2h-4v2H7v18h10V4z"
}), 'BatteryFullSharp'); | packages/mui-icons-material/lib/esm/BatteryFullSharp.js | 0 | https://github.com/mui/material-ui/commit/8f06a1efc80f1289a65b6c1262fe769411d2e71c | [
0.0001753433607518673,
0.0001753433607518673,
0.0001753433607518673,
0.0001753433607518673,
0
] |
{
"id": 0,
"code_window": [
" styleOverrides?: ComponentsOverrides<Theme>['MuiSpeedDialIcon'];\n",
" variants?: ComponentsVariants['MuiSpeedDialIcon'];\n",
" };\n",
" MuiStack?: {\n",
" defaultProps?: ComponentsProps['MuiStack'];\n",
" variants?: ComponentsVariants['MuiStack'];\n",
" };\n",
" MuiStep?: {\n",
" defaultProps?: ComponentsProps['MuiStep'];\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" styleOverrides?: ComponentsOverrides<Theme>['MuiStack'];\n"
],
"file_path": "packages/mui-material/src/styles/components.d.ts",
"type": "add",
"edit_start_line_idx": 445
} | <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M9.01 14H2v2h7.01v3L13 15l-3.99-4v3zm5.98-1v-3H22V8h-7.01V5L11 9l3.99 4z"/></svg> | packages/mui-icons-material/material-icons/compare_arrows_outlined_24px.svg | 0 | https://github.com/mui/material-ui/commit/8f06a1efc80f1289a65b6c1262fe769411d2e71c | [
0.00017330501577816904,
0.00017330501577816904,
0.00017330501577816904,
0.00017330501577816904,
0
] |
{
"id": 0,
"code_window": [
" styleOverrides?: ComponentsOverrides<Theme>['MuiSpeedDialIcon'];\n",
" variants?: ComponentsVariants['MuiSpeedDialIcon'];\n",
" };\n",
" MuiStack?: {\n",
" defaultProps?: ComponentsProps['MuiStack'];\n",
" variants?: ComponentsVariants['MuiStack'];\n",
" };\n",
" MuiStep?: {\n",
" defaultProps?: ComponentsProps['MuiStep'];\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" styleOverrides?: ComponentsOverrides<Theme>['MuiStack'];\n"
],
"file_path": "packages/mui-material/src/styles/components.d.ts",
"type": "add",
"edit_start_line_idx": 445
} | <svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"><g><rect fill="none" height="24" width="24"/></g><g><polygon points="17.2,3 6.8,3 1.6,12 6.8,21 17.2,21 22.4,12"/></g></svg> | packages/mui-icons-material/material-icons/hexagon_24px.svg | 0 | https://github.com/mui/material-ui/commit/8f06a1efc80f1289a65b6c1262fe769411d2e71c | [
0.00017509557073935866,
0.00017509557073935866,
0.00017509557073935866,
0.00017509557073935866,
0
] |
{
"id": 1,
"code_window": [
"import { SnackbarClassKey } from '../Snackbar';\n",
"import { SnackbarContentClassKey } from '../SnackbarContent';\n",
"import { SpeedDialClassKey } from '../SpeedDial';\n",
"import { SpeedDialActionClassKey } from '../SpeedDialAction';\n",
"import { SpeedDialIconClassKey } from '../SpeedDialIcon';\n",
"import { StepButtonClasskey } from '../StepButton';\n",
"import { StepClasskey } from '../Step';\n",
"import { StepConnectorClasskey } from '../StepConnector';\n",
"import { StepContentClasskey } from '../StepContent';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { StackClassKey } from '../Stack';\n"
],
"file_path": "packages/mui-material/src/styles/overrides.d.ts",
"type": "add",
"edit_start_line_idx": 88
} | import { ComponentsProps } from './props';
import { ComponentsOverrides } from './overrides';
import { ComponentsVariants } from './variants';
export interface Components<Theme = unknown> {
MuiAlert?: {
defaultProps?: ComponentsProps['MuiAlert'];
styleOverrides?: ComponentsOverrides<Theme>['MuiAlert'];
variants?: ComponentsVariants['MuiAlert'];
};
MuiAlertTitle?: {
defaultProps?: ComponentsProps['MuiAlertTitle'];
styleOverrides?: ComponentsOverrides<Theme>['MuiAlertTitle'];
variants?: ComponentsVariants['MuiAlertTitle'];
};
MuiAppBar?: {
defaultProps?: ComponentsProps['MuiAppBar'];
styleOverrides?: ComponentsOverrides<Theme>['MuiAppBar'];
variants?: ComponentsVariants['MuiAppBar'];
};
MuiAutocomplete?: {
defaultProps?: ComponentsProps['MuiAutocomplete'];
styleOverrides?: ComponentsOverrides<Theme>['MuiAutocomplete'];
variants?: ComponentsVariants['MuiAutocomplete'];
};
MuiAvatar?: {
defaultProps?: ComponentsProps['MuiAvatar'];
styleOverrides?: ComponentsOverrides<Theme>['MuiAvatar'];
variants?: ComponentsVariants['MuiAvatar'];
};
MuiAvatarGroup?: {
defaultProps?: ComponentsProps['MuiAvatarGroup'];
styleOverrides?: ComponentsOverrides<Theme>['MuiAvatarGroup'];
variants?: ComponentsVariants['MuiAvatarGroup'];
};
MuiBackdrop?: {
defaultProps?: ComponentsProps['MuiBackdrop'];
styleOverrides?: ComponentsOverrides<Theme>['MuiBackdrop'];
variants?: ComponentsVariants['MuiBackdrop'];
};
MuiBadge?: {
defaultProps?: ComponentsProps['MuiBadge'];
styleOverrides?: ComponentsOverrides<Theme>['MuiBadge'];
variants?: ComponentsVariants['MuiBadge'];
};
MuiBottomNavigation?: {
defaultProps?: ComponentsProps['MuiBottomNavigation'];
styleOverrides?: ComponentsOverrides<Theme>['MuiBottomNavigation'];
variants?: ComponentsVariants['MuiBottomNavigation'];
};
MuiBottomNavigationAction?: {
defaultProps?: ComponentsProps['MuiBottomNavigationAction'];
styleOverrides?: ComponentsOverrides<Theme>['MuiBottomNavigationAction'];
variants?: ComponentsVariants['MuiBottomNavigationAction'];
};
MuiBreadcrumbs?: {
defaultProps?: ComponentsProps['MuiBreadcrumbs'];
styleOverrides?: ComponentsOverrides<Theme>['MuiBreadcrumbs'];
variants?: ComponentsVariants['MuiBreadcrumbs'];
};
MuiButton?: {
defaultProps?: ComponentsProps['MuiButton'];
styleOverrides?: ComponentsOverrides<Theme>['MuiButton'];
variants?: ComponentsVariants['MuiButton'];
};
MuiButtonBase?: {
defaultProps?: ComponentsProps['MuiButtonBase'];
styleOverrides?: ComponentsOverrides<Theme>['MuiButtonBase'];
variants?: ComponentsVariants['MuiButtonBase'];
};
MuiButtonGroup?: {
defaultProps?: ComponentsProps['MuiButtonGroup'];
styleOverrides?: ComponentsOverrides<Theme>['MuiButtonGroup'];
variants?: ComponentsVariants['MuiButtonGroup'];
};
MuiCard?: {
defaultProps?: ComponentsProps['MuiCard'];
styleOverrides?: ComponentsOverrides<Theme>['MuiCard'];
variants?: ComponentsVariants['MuiCard'];
};
MuiCardActionArea?: {
defaultProps?: ComponentsProps['MuiCardActionArea'];
styleOverrides?: ComponentsOverrides<Theme>['MuiCardActionArea'];
variants?: ComponentsVariants['MuiCardActionArea'];
};
MuiCardActions?: {
defaultProps?: ComponentsProps['MuiCardActions'];
styleOverrides?: ComponentsOverrides<Theme>['MuiCardActions'];
variants?: ComponentsVariants['MuiCardActions'];
};
MuiCardContent?: {
defaultProps?: ComponentsProps['MuiCardContent'];
styleOverrides?: ComponentsOverrides<Theme>['MuiCardContent'];
variants?: ComponentsVariants['MuiCardContent'];
};
MuiCardHeader?: {
defaultProps?: ComponentsProps['MuiCardHeader'];
styleOverrides?: ComponentsOverrides<Theme>['MuiCardHeader'];
variants?: ComponentsVariants['MuiCardHeader'];
};
MuiCardMedia?: {
defaultProps?: ComponentsProps['MuiCardMedia'];
styleOverrides?: ComponentsOverrides<Theme>['MuiCardMedia'];
variants?: ComponentsVariants['MuiCardMedia'];
};
MuiCheckbox?: {
defaultProps?: ComponentsProps['MuiCheckbox'];
styleOverrides?: ComponentsOverrides<Theme>['MuiCheckbox'];
variants?: ComponentsVariants['MuiCheckbox'];
};
MuiChip?: {
defaultProps?: ComponentsProps['MuiChip'];
styleOverrides?: ComponentsOverrides<Theme>['MuiChip'];
variants?: ComponentsVariants['MuiChip'];
};
MuiCircularProgress?: {
defaultProps?: ComponentsProps['MuiCircularProgress'];
styleOverrides?: ComponentsOverrides<Theme>['MuiCircularProgress'];
variants?: ComponentsVariants['MuiCircularProgress'];
};
MuiCollapse?: {
defaultProps?: ComponentsProps['MuiCollapse'];
styleOverrides?: ComponentsOverrides<Theme>['MuiCollapse'];
variants?: ComponentsVariants['MuiCollapse'];
};
MuiContainer?: {
defaultProps?: ComponentsProps['MuiContainer'];
styleOverrides?: ComponentsOverrides<Theme>['MuiContainer'];
variants?: ComponentsVariants['MuiContainer'];
};
MuiCssBaseline?: {
defaultProps?: ComponentsProps['MuiCssBaseline'];
styleOverrides?: ComponentsOverrides<Theme>['MuiCssBaseline'];
variants?: ComponentsVariants['MuiCssBaseline'];
};
MuiDialog?: {
defaultProps?: ComponentsProps['MuiDialog'];
styleOverrides?: ComponentsOverrides<Theme>['MuiDialog'];
variants?: ComponentsVariants['MuiDialog'];
};
MuiDialogActions?: {
defaultProps?: ComponentsProps['MuiDialogActions'];
styleOverrides?: ComponentsOverrides<Theme>['MuiDialogActions'];
variants?: ComponentsVariants['MuiDialogActions'];
};
MuiDialogContent?: {
defaultProps?: ComponentsProps['MuiDialogContent'];
styleOverrides?: ComponentsOverrides<Theme>['MuiDialogContent'];
variants?: ComponentsVariants['MuiDialogContent'];
};
MuiDialogContentText?: {
defaultProps?: ComponentsProps['MuiDialogContentText'];
styleOverrides?: ComponentsOverrides<Theme>['MuiDialogContentText'];
variants?: ComponentsVariants['MuiDialogContentText'];
};
MuiDialogTitle?: {
defaultProps?: ComponentsProps['MuiDialogTitle'];
styleOverrides?: ComponentsOverrides<Theme>['MuiDialogTitle'];
variants?: ComponentsVariants['MuiDialogTitle'];
};
MuiDivider?: {
defaultProps?: ComponentsProps['MuiDivider'];
styleOverrides?: ComponentsOverrides<Theme>['MuiDivider'];
variants?: ComponentsVariants['MuiDivider'];
};
MuiDrawer?: {
defaultProps?: ComponentsProps['MuiDrawer'];
styleOverrides?: ComponentsOverrides<Theme>['MuiDrawer'];
variants?: ComponentsVariants['MuiDrawer'];
};
MuiAccordion?: {
defaultProps?: ComponentsProps['MuiAccordion'];
styleOverrides?: ComponentsOverrides<Theme>['MuiAccordion'];
variants?: ComponentsVariants['MuiAccordion'];
};
MuiAccordionActions?: {
defaultProps?: ComponentsProps['MuiAccordionActions'];
styleOverrides?: ComponentsOverrides<Theme>['MuiAccordionActions'];
variants?: ComponentsVariants['MuiAccordionActions'];
};
MuiAccordionDetails?: {
defaultProps?: ComponentsProps['MuiAccordionDetails'];
styleOverrides?: ComponentsOverrides<Theme>['MuiAccordionDetails'];
variants?: ComponentsVariants['MuiAccordionDetails'];
};
MuiAccordionSummary?: {
defaultProps?: ComponentsProps['MuiAccordionSummary'];
styleOverrides?: ComponentsOverrides<Theme>['MuiAccordionSummary'];
variants?: ComponentsVariants['MuiAccordionSummary'];
};
MuiFab?: {
defaultProps?: ComponentsProps['MuiFab'];
styleOverrides?: ComponentsOverrides<Theme>['MuiFab'];
variants?: ComponentsVariants['MuiFab'];
};
MuiFilledInput?: {
defaultProps?: ComponentsProps['MuiFilledInput'];
styleOverrides?: ComponentsOverrides<Theme>['MuiFilledInput'];
variants?: ComponentsVariants['MuiFilledInput'];
};
MuiFormControl?: {
defaultProps?: ComponentsProps['MuiFormControl'];
styleOverrides?: ComponentsOverrides<Theme>['MuiFormControl'];
variants?: ComponentsVariants['MuiFormControl'];
};
MuiFormControlLabel?: {
defaultProps?: ComponentsProps['MuiFormControlLabel'];
styleOverrides?: ComponentsOverrides<Theme>['MuiFormControlLabel'];
variants?: ComponentsVariants['MuiFormControlLabel'];
};
MuiFormGroup?: {
defaultProps?: ComponentsProps['MuiFormGroup'];
styleOverrides?: ComponentsOverrides<Theme>['MuiFormGroup'];
variants?: ComponentsVariants['MuiFormGroup'];
};
MuiFormHelperText?: {
defaultProps?: ComponentsProps['MuiFormHelperText'];
styleOverrides?: ComponentsOverrides<Theme>['MuiFormHelperText'];
variants?: ComponentsVariants['MuiFormHelperText'];
};
MuiFormLabel?: {
defaultProps?: ComponentsProps['MuiFormLabel'];
styleOverrides?: ComponentsOverrides<Theme>['MuiFormLabel'];
variants?: ComponentsVariants['MuiFormLabel'];
};
MuiGrid?: {
defaultProps?: ComponentsProps['MuiGrid'];
styleOverrides?: ComponentsOverrides<Theme>['MuiGrid'];
variants?: ComponentsVariants['MuiGrid'];
};
MuiGrid2?: {
defaultProps?: ComponentsProps['MuiGrid2'];
styleOverrides?: ComponentsOverrides<Theme>['MuiGrid2'];
variants?: ComponentsVariants['MuiGrid2'];
};
MuiImageList?: {
defaultProps?: ComponentsProps['MuiImageList'];
styleOverrides?: ComponentsOverrides<Theme>['MuiImageList'];
variants?: ComponentsVariants['MuiImageList'];
};
MuiImageListItem?: {
defaultProps?: ComponentsProps['MuiImageListItem'];
styleOverrides?: ComponentsOverrides<Theme>['MuiImageListItem'];
variants?: ComponentsVariants['MuiImageListItem'];
};
MuiImageListItemBar?: {
defaultProps?: ComponentsProps['MuiImageListItemBar'];
styleOverrides?: ComponentsOverrides<Theme>['MuiImageListItemBar'];
variants?: ComponentsVariants['MuiImageListItemBar'];
};
MuiIcon?: {
defaultProps?: ComponentsProps['MuiIcon'];
styleOverrides?: ComponentsOverrides<Theme>['MuiIcon'];
variants?: ComponentsVariants['MuiIcon'];
};
MuiIconButton?: {
defaultProps?: ComponentsProps['MuiIconButton'];
styleOverrides?: ComponentsOverrides<Theme>['MuiIconButton'];
variants?: ComponentsVariants['MuiIconButton'];
};
MuiInput?: {
defaultProps?: ComponentsProps['MuiInput'];
styleOverrides?: ComponentsOverrides<Theme>['MuiInput'];
variants?: ComponentsVariants['MuiInput'];
};
MuiInputAdornment?: {
defaultProps?: ComponentsProps['MuiInputAdornment'];
styleOverrides?: ComponentsOverrides<Theme>['MuiInputAdornment'];
variants?: ComponentsVariants['MuiInputAdornment'];
};
MuiInputBase?: {
defaultProps?: ComponentsProps['MuiInputBase'];
styleOverrides?: ComponentsOverrides<Theme>['MuiInputBase'];
variants?: ComponentsVariants['MuiInputBase'];
};
MuiInputLabel?: {
defaultProps?: ComponentsProps['MuiInputLabel'];
styleOverrides?: ComponentsOverrides<Theme>['MuiInputLabel'];
variants?: ComponentsVariants['MuiInputLabel'];
};
MuiLinearProgress?: {
defaultProps?: ComponentsProps['MuiLinearProgress'];
styleOverrides?: ComponentsOverrides<Theme>['MuiLinearProgress'];
variants?: ComponentsVariants['MuiLinearProgress'];
};
MuiLink?: {
defaultProps?: ComponentsProps['MuiLink'];
styleOverrides?: ComponentsOverrides<Theme>['MuiLink'];
variants?: ComponentsVariants['MuiLink'];
};
MuiList?: {
defaultProps?: ComponentsProps['MuiList'];
styleOverrides?: ComponentsOverrides<Theme>['MuiList'];
variants?: ComponentsVariants['MuiList'];
};
MuiListItem?: {
defaultProps?: ComponentsProps['MuiListItem'];
styleOverrides?: ComponentsOverrides<Theme>['MuiListItem'];
variants?: ComponentsVariants['MuiListItem'];
};
MuiListItemButton?: {
defaultProps?: ComponentsProps['MuiListItemButton'];
styleOverrides?: ComponentsOverrides<Theme>['MuiListItemButton'];
variants?: ComponentsVariants['MuiListItemButton'];
};
MuiListItemAvatar?: {
defaultProps?: ComponentsProps['MuiListItemAvatar'];
styleOverrides?: ComponentsOverrides<Theme>['MuiListItemAvatar'];
variants?: ComponentsVariants['MuiListItemAvatar'];
};
MuiListItemIcon?: {
defaultProps?: ComponentsProps['MuiListItemIcon'];
styleOverrides?: ComponentsOverrides<Theme>['MuiListItemIcon'];
variants?: ComponentsVariants['MuiListItemIcon'];
};
MuiListItemSecondaryAction?: {
defaultProps?: ComponentsProps['MuiListItemSecondaryAction'];
styleOverrides?: ComponentsOverrides<Theme>['MuiListItemSecondaryAction'];
variants?: ComponentsVariants['MuiListItemSecondaryAction'];
};
MuiListItemText?: {
defaultProps?: ComponentsProps['MuiListItemText'];
styleOverrides?: ComponentsOverrides<Theme>['MuiListItemText'];
variants?: ComponentsVariants['MuiListItemText'];
};
MuiListSubheader?: {
defaultProps?: ComponentsProps['MuiListSubheader'];
styleOverrides?: ComponentsOverrides<Theme>['MuiListSubheader'];
variants?: ComponentsVariants['MuiListSubheader'];
};
MuiMenu?: {
defaultProps?: ComponentsProps['MuiMenu'];
styleOverrides?: ComponentsOverrides<Theme>['MuiMenu'];
variants?: ComponentsVariants['MuiMenu'];
};
MuiMenuItem?: {
defaultProps?: ComponentsProps['MuiMenuItem'];
styleOverrides?: ComponentsOverrides<Theme>['MuiMenuItem'];
variants?: ComponentsVariants['MuiMenuItem'];
};
MuiMenuList?: {
defaultProps?: ComponentsProps['MuiMenuList'];
styleOverrides?: ComponentsOverrides<Theme>['MuiMenuList'];
variants?: ComponentsVariants['MuiMenuList'];
};
MuiMobileStepper?: {
defaultProps?: ComponentsProps['MuiMobileStepper'];
styleOverrides?: ComponentsOverrides<Theme>['MuiMobileStepper'];
variants?: ComponentsVariants['MuiMobileStepper'];
};
MuiModal?: {
defaultProps?: ComponentsProps['MuiModal'];
styleOverrides?: ComponentsOverrides<Theme>['MuiModal'];
variants?: ComponentsVariants['MuiModal'];
};
MuiNativeSelect?: {
defaultProps?: ComponentsProps['MuiNativeSelect'];
styleOverrides?: ComponentsOverrides<Theme>['MuiNativeSelect'];
variants?: ComponentsVariants['MuiNativeSelect'];
};
MuiOutlinedInput?: {
defaultProps?: ComponentsProps['MuiOutlinedInput'];
styleOverrides?: ComponentsOverrides<Theme>['MuiOutlinedInput'];
variants?: ComponentsVariants['MuiOutlinedInput'];
};
MuiPagination?: {
defaultProps?: ComponentsProps['MuiPagination'];
styleOverrides?: ComponentsOverrides<Theme>['MuiPagination'];
variants?: ComponentsVariants['MuiPagination'];
};
MuiPaginationItem?: {
defaultProps?: ComponentsProps['MuiPaginationItem'];
styleOverrides?: ComponentsOverrides<Theme>['MuiPaginationItem'];
variants?: ComponentsVariants['MuiPaginationItem'];
};
MuiPaper?: {
defaultProps?: ComponentsProps['MuiPaper'];
styleOverrides?: ComponentsOverrides<Theme>['MuiPaper'];
variants?: ComponentsVariants['MuiPaper'];
};
MuiPopper?: {
defaultProps?: ComponentsProps['MuiPopper'];
};
MuiPopover?: {
defaultProps?: ComponentsProps['MuiPopover'];
styleOverrides?: ComponentsOverrides<Theme>['MuiPopover'];
variants?: ComponentsVariants['MuiPopover'];
};
MuiRadio?: {
defaultProps?: ComponentsProps['MuiRadio'];
styleOverrides?: ComponentsOverrides<Theme>['MuiRadio'];
variants?: ComponentsVariants['MuiRadio'];
};
MuiRating?: {
defaultProps?: ComponentsProps['MuiRating'];
styleOverrides?: ComponentsOverrides<Theme>['MuiRating'];
variants?: ComponentsVariants['MuiRating'];
};
MuiScopedCssBaseline?: {
defaultProps?: ComponentsProps['MuiScopedCssBaseline'];
styleOverrides?: ComponentsOverrides<Theme>['MuiScopedCssBaseline'];
variants?: ComponentsVariants['MuiScopedCssBaseline'];
};
MuiSelect?: {
defaultProps?: ComponentsProps['MuiSelect'];
styleOverrides?: ComponentsOverrides<Theme>['MuiSelect'];
variants?: ComponentsVariants['MuiSelect'];
};
MuiSkeleton?: {
defaultProps?: ComponentsProps['MuiSkeleton'];
styleOverrides?: ComponentsOverrides<Theme>['MuiSkeleton'];
variants?: ComponentsVariants['MuiSkeleton'];
};
MuiSlider?: {
defaultProps?: ComponentsProps['MuiSlider'];
styleOverrides?: ComponentsOverrides<Theme>['MuiSlider'];
variants?: ComponentsVariants['MuiSlider'];
};
MuiSnackbar?: {
defaultProps?: ComponentsProps['MuiSnackbar'];
styleOverrides?: ComponentsOverrides<Theme>['MuiSnackbar'];
variants?: ComponentsVariants['MuiSnackbar'];
};
MuiSnackbarContent?: {
defaultProps?: ComponentsProps['MuiSnackbarContent'];
styleOverrides?: ComponentsOverrides<Theme>['MuiSnackbarContent'];
variants?: ComponentsVariants['MuiSnackbarContent'];
};
MuiSpeedDial?: {
defaultProps?: ComponentsProps['MuiSpeedDial'];
styleOverrides?: ComponentsOverrides<Theme>['MuiSpeedDial'];
variants?: ComponentsVariants['MuiSpeedDial'];
};
MuiSpeedDialAction?: {
defaultProps?: ComponentsProps['MuiSpeedDialAction'];
styleOverrides?: ComponentsOverrides<Theme>['MuiSpeedDialAction'];
variants?: ComponentsVariants['MuiSpeedDialAction'];
};
MuiSpeedDialIcon?: {
defaultProps?: ComponentsProps['MuiSpeedDialIcon'];
styleOverrides?: ComponentsOverrides<Theme>['MuiSpeedDialIcon'];
variants?: ComponentsVariants['MuiSpeedDialIcon'];
};
MuiStack?: {
defaultProps?: ComponentsProps['MuiStack'];
variants?: ComponentsVariants['MuiStack'];
};
MuiStep?: {
defaultProps?: ComponentsProps['MuiStep'];
styleOverrides?: ComponentsOverrides<Theme>['MuiStep'];
variants?: ComponentsVariants['MuiStep'];
};
MuiStepButton?: {
defaultProps?: ComponentsProps['MuiStepButton'];
styleOverrides?: ComponentsOverrides<Theme>['MuiStepButton'];
variants?: ComponentsVariants['MuiStepButton'];
};
MuiStepConnector?: {
defaultProps?: ComponentsProps['MuiStepConnector'];
styleOverrides?: ComponentsOverrides<Theme>['MuiStepConnector'];
variants?: ComponentsVariants['MuiStepConnector'];
};
MuiStepContent?: {
defaultProps?: ComponentsProps['MuiStepContent'];
styleOverrides?: ComponentsOverrides<Theme>['MuiStepContent'];
variants?: ComponentsVariants['MuiStepContent'];
};
MuiStepIcon?: {
defaultProps?: ComponentsProps['MuiStepIcon'];
styleOverrides?: ComponentsOverrides<Theme>['MuiStepIcon'];
variants?: ComponentsVariants['MuiStepIcon'];
};
MuiStepLabel?: {
defaultProps?: ComponentsProps['MuiStepLabel'];
styleOverrides?: ComponentsOverrides<Theme>['MuiStepLabel'];
variants?: ComponentsVariants['MuiStepLabel'];
};
MuiStepper?: {
defaultProps?: ComponentsProps['MuiStepper'];
styleOverrides?: ComponentsOverrides<Theme>['MuiStepper'];
variants?: ComponentsVariants['MuiStepper'];
};
MuiSvgIcon?: {
defaultProps?: ComponentsProps['MuiSvgIcon'];
styleOverrides?: ComponentsOverrides<Theme>['MuiSvgIcon'];
variants?: ComponentsVariants['MuiSvgIcon'];
};
MuiSwipeableDrawer?: {
defaultProps?: ComponentsProps['MuiSwipeableDrawer'];
};
MuiSwitch?: {
defaultProps?: ComponentsProps['MuiSwitch'];
styleOverrides?: ComponentsOverrides<Theme>['MuiSwitch'];
variants?: ComponentsVariants['MuiSwitch'];
};
MuiTab?: {
defaultProps?: ComponentsProps['MuiTab'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTab'];
variants?: ComponentsVariants['MuiTab'];
};
MuiTable?: {
defaultProps?: ComponentsProps['MuiTable'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTable'];
variants?: ComponentsVariants['MuiTable'];
};
MuiTableBody?: {
defaultProps?: ComponentsProps['MuiTableBody'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTableBody'];
variants?: ComponentsVariants['MuiTableBody'];
};
MuiTableCell?: {
defaultProps?: ComponentsProps['MuiTableCell'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTableCell'];
variants?: ComponentsVariants['MuiTableCell'];
};
MuiTableContainer?: {
defaultProps?: ComponentsProps['MuiTableContainer'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTableContainer'];
variants?: ComponentsVariants['MuiTableContainer'];
};
MuiTableFooter?: {
defaultProps?: ComponentsProps['MuiTableFooter'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTableFooter'];
variants?: ComponentsVariants['MuiTableFooter'];
};
MuiTableHead?: {
defaultProps?: ComponentsProps['MuiTableHead'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTableHead'];
variants?: ComponentsVariants['MuiTableHead'];
};
MuiTablePagination?: {
defaultProps?: ComponentsProps['MuiTablePagination'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTablePagination'];
variants?: ComponentsVariants['MuiTablePagination'];
};
MuiTableRow?: {
defaultProps?: ComponentsProps['MuiTableRow'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTableRow'];
variants?: ComponentsVariants['MuiTableRow'];
};
MuiTableSortLabel?: {
defaultProps?: ComponentsProps['MuiTableSortLabel'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTableSortLabel'];
variants?: ComponentsVariants['MuiTableSortLabel'];
};
MuiTabs?: {
defaultProps?: ComponentsProps['MuiTabs'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTabs'];
variants?: ComponentsVariants['MuiTabs'];
};
MuiTextField?: {
defaultProps?: ComponentsProps['MuiTextField'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTextField'];
variants?: ComponentsVariants['MuiTextField'];
};
MuiToggleButton?: {
defaultProps?: ComponentsProps['MuiToggleButton'];
styleOverrides?: ComponentsOverrides<Theme>['MuiToggleButton'];
variants?: ComponentsVariants['MuiToggleButton'];
};
MuiToggleButtonGroup?: {
defaultProps?: ComponentsProps['MuiToggleButtonGroup'];
styleOverrides?: ComponentsOverrides<Theme>['MuiToggleButtonGroup'];
variants?: ComponentsVariants['MuiToggleButtonGroup'];
};
MuiToolbar?: {
defaultProps?: ComponentsProps['MuiToolbar'];
styleOverrides?: ComponentsOverrides<Theme>['MuiToolbar'];
variants?: ComponentsVariants['MuiToolbar'];
};
MuiTooltip?: {
defaultProps?: ComponentsProps['MuiTooltip'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTooltip'];
variants?: ComponentsVariants['MuiTooltip'];
};
MuiTouchRipple?: {
defaultProps?: ComponentsProps['MuiTouchRipple'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTouchRipple'];
variants?: ComponentsVariants['MuiTouchRipple'];
};
MuiTypography?: {
defaultProps?: ComponentsProps['MuiTypography'];
styleOverrides?: ComponentsOverrides<Theme>['MuiTypography'];
variants?: ComponentsVariants['MuiTypography'];
};
MuiUseMediaQuery?: {
defaultProps?: ComponentsProps['MuiUseMediaQuery'];
};
}
| packages/mui-material/src/styles/components.d.ts | 1 | https://github.com/mui/material-ui/commit/8f06a1efc80f1289a65b6c1262fe769411d2e71c | [
0.0010466683888807893,
0.00019389756198506802,
0.0001631490740692243,
0.0001760828890837729,
0.00011554378579603508
] |
{
"id": 1,
"code_window": [
"import { SnackbarClassKey } from '../Snackbar';\n",
"import { SnackbarContentClassKey } from '../SnackbarContent';\n",
"import { SpeedDialClassKey } from '../SpeedDial';\n",
"import { SpeedDialActionClassKey } from '../SpeedDialAction';\n",
"import { SpeedDialIconClassKey } from '../SpeedDialIcon';\n",
"import { StepButtonClasskey } from '../StepButton';\n",
"import { StepClasskey } from '../Step';\n",
"import { StepConnectorClasskey } from '../StepConnector';\n",
"import { StepContentClasskey } from '../StepContent';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { StackClassKey } from '../Stack';\n"
],
"file_path": "packages/mui-material/src/styles/overrides.d.ts",
"type": "add",
"edit_start_line_idx": 88
} | <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0z" fill="none"/><path d="M18 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm-2.5 4c0-1.38 1.12-2.5 2.5-2.5.42 0 .8.11 1.15.29l-3.36 3.36c-.18-.35-.29-.73-.29-1.15zm2.5 2.5c-.42 0-.8-.11-1.15-.29l3.36-3.36c.18.35.29.73.29 1.15 0 1.38-1.12 2.5-2.5 2.5zM17 18H7V6h10v1h2V3c0-1.1-.9-2-2-2H7c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2v-4h-2v1z"/></svg> | packages/mui-icons-material/material-icons/app_blocking_24px.svg | 0 | https://github.com/mui/material-ui/commit/8f06a1efc80f1289a65b6c1262fe769411d2e71c | [
0.0001673087535891682,
0.0001673087535891682,
0.0001673087535891682,
0.0001673087535891682,
0
] |
{
"id": 1,
"code_window": [
"import { SnackbarClassKey } from '../Snackbar';\n",
"import { SnackbarContentClassKey } from '../SnackbarContent';\n",
"import { SpeedDialClassKey } from '../SpeedDial';\n",
"import { SpeedDialActionClassKey } from '../SpeedDialAction';\n",
"import { SpeedDialIconClassKey } from '../SpeedDialIcon';\n",
"import { StepButtonClasskey } from '../StepButton';\n",
"import { StepClasskey } from '../Step';\n",
"import { StepConnectorClasskey } from '../StepConnector';\n",
"import { StepContentClasskey } from '../StepContent';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { StackClassKey } from '../Stack';\n"
],
"file_path": "packages/mui-material/src/styles/overrides.d.ts",
"type": "add",
"edit_start_line_idx": 88
} | <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0z" fill="none"/><path d="M20 1v3h3v2h-3v3h-2V6h-3V4h3V1h2zm-8 12c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm1-9.94v2.02A6.53 6.53 0 0 0 12 5c-3.35 0-6 2.57-6 6.2 0 2.34 1.95 5.44 6 9.14 4.05-3.7 6-6.79 6-9.14V11h2v.2c0 3.32-2.67 7.25-8 11.8-5.33-4.55-8-8.48-8-11.8C4 6.22 7.8 3 12 3c.34 0 .67.02 1 .06z"/></svg> | packages/mui-icons-material/material-icons/add_location_alt_outlined_24px.svg | 0 | https://github.com/mui/material-ui/commit/8f06a1efc80f1289a65b6c1262fe769411d2e71c | [
0.00017181530711241066,
0.00017181530711241066,
0.00017181530711241066,
0.00017181530711241066,
0
] |
{
"id": 1,
"code_window": [
"import { SnackbarClassKey } from '../Snackbar';\n",
"import { SnackbarContentClassKey } from '../SnackbarContent';\n",
"import { SpeedDialClassKey } from '../SpeedDial';\n",
"import { SpeedDialActionClassKey } from '../SpeedDialAction';\n",
"import { SpeedDialIconClassKey } from '../SpeedDialIcon';\n",
"import { StepButtonClasskey } from '../StepButton';\n",
"import { StepClasskey } from '../Step';\n",
"import { StepConnectorClasskey } from '../StepConnector';\n",
"import { StepContentClasskey } from '../StepContent';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { StackClassKey } from '../Stack';\n"
],
"file_path": "packages/mui-material/src/styles/overrides.d.ts",
"type": "add",
"edit_start_line_idx": 88
} | 'use client';
export { default } from './Popover';
export * from './Popover';
export { default as popoverClasses } from './popoverClasses';
export * from './popoverClasses';
| packages/mui-material/src/Popover/index.js | 0 | https://github.com/mui/material-ui/commit/8f06a1efc80f1289a65b6c1262fe769411d2e71c | [
0.00017656676936894655,
0.00017656676936894655,
0.00017656676936894655,
0.00017656676936894655,
0
] |
{
"id": 2,
"code_window": [
" MuiSnackbarContent: SnackbarContentClassKey;\n",
" MuiSpeedDial: SpeedDialClassKey;\n",
" MuiSpeedDialAction: SpeedDialActionClassKey;\n",
" MuiSpeedDialIcon: SpeedDialIconClassKey;\n",
" MuiStep: StepClasskey;\n",
" MuiStepButton: StepButtonClasskey;\n",
" MuiStepConnector: StepConnectorClasskey;\n",
" MuiStepContent: StepContentClasskey;\n",
" MuiStepIcon: StepIconClasskey;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" MuiStack: StackClassKey;\n"
],
"file_path": "packages/mui-material/src/styles/overrides.d.ts",
"type": "add",
"edit_start_line_idx": 227
} | import { CSSObject, CSSInterpolation } from '@mui/system';
import { ComponentsPropsList } from './props';
import { AccordionActionsClassKey } from '../AccordionActions';
import { AccordionClassKey } from '../Accordion';
import { AccordionDetailsClassKey } from '../AccordionDetails';
import { AccordionSummaryClassKey } from '../AccordionSummary';
import { AlertClassKey } from '../Alert';
import { AlertTitleClassKey } from '../AlertTitle';
import { AppBarClassKey } from '../AppBar';
import { AutocompleteClassKey } from '../Autocomplete';
import { AvatarClassKey } from '../Avatar';
import { AvatarGroupClassKey } from '../AvatarGroup';
import { BackdropClassKey } from '../Backdrop';
import { BadgeClassKey } from '../Badge';
import { BottomNavigationActionClassKey } from '../BottomNavigationAction';
import { BottomNavigationClassKey } from '../BottomNavigation';
import { BreadcrumbsClassKey } from '../Breadcrumbs';
import { ButtonBaseClassKey } from '../ButtonBase';
import { ButtonClassKey } from '../Button';
import { ButtonGroupClassKey } from '../ButtonGroup';
import { CardActionAreaClassKey } from '../CardActionArea';
import { CardActionsClassKey } from '../CardActions';
import { CardClassKey } from '../Card';
import { CardContentClassKey } from '../CardContent';
import { CardHeaderClassKey } from '../CardHeader';
import { CardMediaClassKey } from '../CardMedia';
import { CheckboxClassKey } from '../Checkbox';
import { ChipClassKey } from '../Chip';
import { CircularProgressClassKey } from '../CircularProgress';
import { CollapseClassKey } from '../Collapse';
import { ContainerClassKey } from '../Container';
import { DialogActionsClassKey } from '../DialogActions';
import { DialogClassKey } from '../Dialog';
import { DialogContentClassKey } from '../DialogContent';
import { DialogContentTextClassKey } from '../DialogContentText';
import { DialogTitleClassKey } from '../DialogTitle';
import { DividerClassKey } from '../Divider';
import { DrawerClassKey } from '../Drawer';
import { FabClassKey } from '../Fab';
import { FilledInputClassKey } from '../FilledInput';
import { FormControlClassKey } from '../FormControl';
import { FormControlLabelClassKey } from '../FormControlLabel';
import { FormGroupClassKey } from '../FormGroup';
import { FormHelperTextClassKey } from '../FormHelperText';
import { FormLabelClassKey } from '../FormLabel';
import { GridClassKey } from '../Grid';
import { Grid2Slot } from '../Unstable_Grid2';
import { IconButtonClassKey } from '../IconButton';
import { IconClassKey } from '../Icon';
import { ImageListClassKey } from '../ImageList';
import { ImageListItemBarClassKey } from '../ImageListItemBar';
import { ImageListItemClassKey } from '../ImageListItem';
import { InputAdornmentClassKey } from '../InputAdornment';
import { InputBaseClassKey } from '../InputBase';
import { InputClassKey } from '../Input';
import { InputLabelClassKey } from '../InputLabel';
import { LinearProgressClassKey } from '../LinearProgress';
import { LinkClassKey } from '../Link';
import { ListClassKey } from '../List';
import { ListItemAvatarClassKey } from '../ListItemAvatar';
import { ListItemClassKey } from '../ListItem';
import { ListItemButtonClassKey } from '../ListItemButton';
import { ListItemIconClassKey } from '../ListItemIcon';
import { ListItemSecondaryActionClassKey } from '../ListItemSecondaryAction';
import { ListItemTextClassKey } from '../ListItemText';
import { ListSubheaderClassKey } from '../ListSubheader';
import { MenuClassKey } from '../Menu';
import { MenuItemClassKey } from '../MenuItem';
import { MenuListClassKey } from '../MenuList';
import { MobileStepperClassKey } from '../MobileStepper';
import { ModalClassKey } from '../Modal';
import { NativeSelectClassKey } from '../NativeSelect';
import { OutlinedInputClassKey } from '../OutlinedInput';
import { PaginationClassKey } from '../Pagination';
import { PaginationItemClassKey } from '../PaginationItem';
import { PaperClassKey } from '../Paper';
import { PopoverClassKey } from '../Popover';
import { RadioClassKey } from '../Radio';
import { RatingClassKey } from '../Rating';
import { ScopedCssBaselineClassKey } from '../ScopedCssBaseline';
import { SelectClassKey } from '../Select';
import { SkeletonClassKey } from '../Skeleton';
import { SliderClassKey } from '../Slider';
import { SnackbarClassKey } from '../Snackbar';
import { SnackbarContentClassKey } from '../SnackbarContent';
import { SpeedDialClassKey } from '../SpeedDial';
import { SpeedDialActionClassKey } from '../SpeedDialAction';
import { SpeedDialIconClassKey } from '../SpeedDialIcon';
import { StepButtonClasskey } from '../StepButton';
import { StepClasskey } from '../Step';
import { StepConnectorClasskey } from '../StepConnector';
import { StepContentClasskey } from '../StepContent';
import { StepIconClasskey } from '../StepIcon';
import { StepLabelClasskey } from '../StepLabel';
import { StepperClasskey } from '../Stepper';
import { SvgIconClassKey } from '../SvgIcon';
import { SwitchClassKey } from '../Switch';
import { TabClassKey } from '../Tab';
import { TableBodyClassKey } from '../TableBody';
import { TableCellClassKey } from '../TableCell';
import { TableClassKey } from '../Table';
import { TableContainerClassKey } from '../TableContainer';
import { TableFooterClassKey } from '../TableFooter';
import { TableHeadClassKey } from '../TableHead';
import { TablePaginationClassKey } from '../TablePagination';
import { TableRowClassKey } from '../TableRow';
import { TableSortLabelClassKey } from '../TableSortLabel';
import { TabsClassKey } from '../Tabs';
import { TextFieldClassKey } from '../TextField';
import { ToggleButtonClassKey } from '../ToggleButton';
import { ToggleButtonGroupClassKey } from '../ToggleButtonGroup';
import { ToolbarClassKey } from '../Toolbar';
import { TooltipClassKey } from '../Tooltip';
import { TouchRippleClassKey } from '../ButtonBase/TouchRipple';
import { TypographyClassKey } from '../Typography';
export type OverridesStyleRules<
ClassKey extends string = string,
ComponentName = keyof ComponentsPropsList,
Theme = unknown,
> = Record<
ClassKey,
| CSSInterpolation
| ((
// Record<string, unknown> is for other props that the slot receive internally
// Documenting all ownerStates could be a huge work, let's wait until we have a real needs from developers.
props: (ComponentName extends keyof ComponentsPropsList
? { ownerState: ComponentsPropsList[ComponentName] & Record<string, unknown> }
: {}) & { theme: Theme } & Record<string, unknown>,
) => CSSInterpolation)
>;
export type ComponentsOverrides<Theme = unknown> = {
[Name in keyof ComponentNameToClassKey]?: Partial<
OverridesStyleRules<ComponentNameToClassKey[Name], Name, Theme>
>;
} & {
MuiCssBaseline?: CSSObject | string | ((theme: Theme) => CSSInterpolation);
};
export interface ComponentNameToClassKey {
MuiAlert: AlertClassKey;
MuiAlertTitle: AlertTitleClassKey;
MuiAppBar: AppBarClassKey;
MuiAutocomplete: AutocompleteClassKey;
MuiAvatar: AvatarClassKey;
MuiAvatarGroup: AvatarGroupClassKey;
MuiBackdrop: BackdropClassKey;
MuiBadge: BadgeClassKey;
MuiBottomNavigation: BottomNavigationClassKey;
MuiBottomNavigationAction: BottomNavigationActionClassKey;
MuiBreadcrumbs: BreadcrumbsClassKey;
MuiButton: ButtonClassKey;
MuiButtonBase: ButtonBaseClassKey;
MuiButtonGroup: ButtonGroupClassKey;
MuiCard: CardClassKey;
MuiCardActionArea: CardActionAreaClassKey;
MuiCardActions: CardActionsClassKey;
MuiCardContent: CardContentClassKey;
MuiCardHeader: CardHeaderClassKey;
MuiCardMedia: CardMediaClassKey;
MuiCheckbox: CheckboxClassKey;
MuiChip: ChipClassKey;
MuiCircularProgress: CircularProgressClassKey;
MuiCollapse: CollapseClassKey;
MuiContainer: ContainerClassKey;
MuiDialog: DialogClassKey;
MuiDialogActions: DialogActionsClassKey;
MuiDialogContent: DialogContentClassKey;
MuiDialogContentText: DialogContentTextClassKey;
MuiDialogTitle: DialogTitleClassKey;
MuiDivider: DividerClassKey;
MuiDrawer: DrawerClassKey;
MuiAccordion: AccordionClassKey;
MuiAccordionActions: AccordionActionsClassKey;
MuiAccordionDetails: AccordionDetailsClassKey;
MuiAccordionSummary: AccordionSummaryClassKey;
MuiFab: FabClassKey;
MuiFilledInput: FilledInputClassKey;
MuiFormControl: FormControlClassKey;
MuiFormControlLabel: FormControlLabelClassKey;
MuiFormGroup: FormGroupClassKey;
MuiFormHelperText: FormHelperTextClassKey;
MuiFormLabel: FormLabelClassKey;
MuiGrid: GridClassKey;
MuiGrid2: Grid2Slot;
MuiIcon: IconClassKey;
MuiIconButton: IconButtonClassKey;
MuiImageList: ImageListClassKey;
MuiImageListItem: ImageListItemClassKey;
MuiImageListItemBar: ImageListItemBarClassKey;
MuiInput: InputClassKey;
MuiInputAdornment: InputAdornmentClassKey;
MuiInputBase: InputBaseClassKey;
MuiInputLabel: InputLabelClassKey;
MuiLinearProgress: LinearProgressClassKey;
MuiLink: LinkClassKey;
MuiList: ListClassKey;
MuiListItem: ListItemClassKey;
MuiListItemButton: ListItemButtonClassKey;
MuiListItemAvatar: ListItemAvatarClassKey;
MuiListItemIcon: ListItemIconClassKey;
MuiListItemSecondaryAction: ListItemSecondaryActionClassKey;
MuiListItemText: ListItemTextClassKey;
MuiListSubheader: ListSubheaderClassKey;
MuiMenu: MenuClassKey;
MuiMenuItem: MenuItemClassKey;
MuiMenuList: MenuListClassKey;
MuiMobileStepper: MobileStepperClassKey;
MuiModal: ModalClassKey;
MuiNativeSelect: NativeSelectClassKey;
MuiOutlinedInput: OutlinedInputClassKey;
MuiPagination: PaginationClassKey;
MuiPaginationItem: PaginationItemClassKey;
MuiPaper: PaperClassKey;
MuiPopover: PopoverClassKey;
MuiRadio: RadioClassKey;
MuiRating: RatingClassKey;
MuiScopedCssBaseline: ScopedCssBaselineClassKey;
MuiSelect: SelectClassKey;
MuiSkeleton: SkeletonClassKey;
MuiSlider: SliderClassKey;
MuiSnackbar: SnackbarClassKey;
MuiSnackbarContent: SnackbarContentClassKey;
MuiSpeedDial: SpeedDialClassKey;
MuiSpeedDialAction: SpeedDialActionClassKey;
MuiSpeedDialIcon: SpeedDialIconClassKey;
MuiStep: StepClasskey;
MuiStepButton: StepButtonClasskey;
MuiStepConnector: StepConnectorClasskey;
MuiStepContent: StepContentClasskey;
MuiStepIcon: StepIconClasskey;
MuiStepLabel: StepLabelClasskey;
MuiStepper: StepperClasskey;
MuiSvgIcon: SvgIconClassKey;
MuiSwitch: SwitchClassKey;
MuiTab: TabClassKey;
MuiTable: TableClassKey;
MuiTableBody: TableBodyClassKey;
MuiTableCell: TableCellClassKey;
MuiTableContainer: TableContainerClassKey;
MuiTableFooter: TableFooterClassKey;
MuiTableHead: TableHeadClassKey;
MuiTablePagination: TablePaginationClassKey;
MuiTableRow: TableRowClassKey;
MuiTableSortLabel: TableSortLabelClassKey;
MuiTabs: TabsClassKey;
MuiTextField: TextFieldClassKey;
MuiToggleButton: ToggleButtonClassKey;
MuiToggleButtonGroup: ToggleButtonGroupClassKey;
MuiToolbar: ToolbarClassKey;
MuiTooltip: TooltipClassKey;
MuiTouchRipple: TouchRippleClassKey;
MuiTypography: TypographyClassKey;
}
| packages/mui-material/src/styles/overrides.d.ts | 1 | https://github.com/mui/material-ui/commit/8f06a1efc80f1289a65b6c1262fe769411d2e71c | [
0.9965590834617615,
0.05238712206482887,
0.00016569257422816008,
0.00042354391189292073,
0.19653569161891937
] |
{
"id": 2,
"code_window": [
" MuiSnackbarContent: SnackbarContentClassKey;\n",
" MuiSpeedDial: SpeedDialClassKey;\n",
" MuiSpeedDialAction: SpeedDialActionClassKey;\n",
" MuiSpeedDialIcon: SpeedDialIconClassKey;\n",
" MuiStep: StepClasskey;\n",
" MuiStepButton: StepButtonClasskey;\n",
" MuiStepConnector: StepConnectorClasskey;\n",
" MuiStepContent: StepContentClasskey;\n",
" MuiStepIcon: StepIconClasskey;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" MuiStack: StackClassKey;\n"
],
"file_path": "packages/mui-material/src/styles/overrides.d.ts",
"type": "add",
"edit_start_line_idx": 227
} | <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M12 7V5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2h-8zM6 19H4v-2h2v2zm0-4H4v-2h2v2zm0-4H4V9h2v2zm0-4H4V5h2v2zm4 12H8v-2h2v2zm0-4H8v-2h2v2zm0-4H8V9h2v2zm0-4H8V5h2v2zm9 12h-7v-2h2v-2h-2v-2h2v-2h-2V9h7c.55 0 1 .45 1 1v8c0 .55-.45 1-1 1zm-1-8h-2v2h2v-2zm0 4h-2v2h2v-2z"/></svg> | packages/mui-icons-material/material-icons/domain_rounded_24px.svg | 0 | https://github.com/mui/material-ui/commit/8f06a1efc80f1289a65b6c1262fe769411d2e71c | [
0.0001665862073423341,
0.0001665862073423341,
0.0001665862073423341,
0.0001665862073423341,
0
] |
{
"id": 2,
"code_window": [
" MuiSnackbarContent: SnackbarContentClassKey;\n",
" MuiSpeedDial: SpeedDialClassKey;\n",
" MuiSpeedDialAction: SpeedDialActionClassKey;\n",
" MuiSpeedDialIcon: SpeedDialIconClassKey;\n",
" MuiStep: StepClasskey;\n",
" MuiStepButton: StepButtonClasskey;\n",
" MuiStepConnector: StepConnectorClasskey;\n",
" MuiStepContent: StepContentClasskey;\n",
" MuiStepIcon: StepIconClasskey;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" MuiStack: StackClassKey;\n"
],
"file_path": "packages/mui-material/src/styles/overrides.d.ts",
"type": "add",
"edit_start_line_idx": 227
} | "use strict";
"use client";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "m13.7826 15.1719 2.1213-2.1213 5.9963 5.9962-2.1213 2.1213zM17.5 10c1.93 0 3.5-1.57 3.5-3.5 0-.58-.16-1.12-.41-1.6l-2.7 2.7-1.49-1.49 2.7-2.7c-.48-.25-1.02-.41-1.6-.41C15.57 3 14 4.57 14 6.5c0 .41.08.8.21 1.16l-1.85 1.85-1.78-1.78.71-.71-1.41-1.41L12 3.49c-1.17-1.17-3.07-1.17-4.24 0L4.22 7.03l1.41 1.41H2.81l-.71.71 3.54 3.54.71-.71V9.15l1.41 1.41.71-.71 1.78 1.78-7.41 7.41 2.12 2.12L16.34 9.79c.36.13.75.21 1.16.21z"
}), 'Construction');
exports.default = _default; | packages/mui-icons-material/lib/Construction.js | 0 | https://github.com/mui/material-ui/commit/8f06a1efc80f1289a65b6c1262fe769411d2e71c | [
0.00016868652892298996,
0.00016613361367490143,
0.0001635806984268129,
0.00016613361367490143,
0.0000025529152480885386
] |
{
"id": 2,
"code_window": [
" MuiSnackbarContent: SnackbarContentClassKey;\n",
" MuiSpeedDial: SpeedDialClassKey;\n",
" MuiSpeedDialAction: SpeedDialActionClassKey;\n",
" MuiSpeedDialIcon: SpeedDialIconClassKey;\n",
" MuiStep: StepClasskey;\n",
" MuiStepButton: StepButtonClasskey;\n",
" MuiStepConnector: StepConnectorClasskey;\n",
" MuiStepContent: StepContentClasskey;\n",
" MuiStepIcon: StepIconClasskey;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" MuiStack: StackClassKey;\n"
],
"file_path": "packages/mui-material/src/styles/overrides.d.ts",
"type": "add",
"edit_start_line_idx": 227
} | "use strict";
"use client";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M17.7 11.53c-.7.31-1.45.47-2.21.47C12.46 12 10 9.53 10 6.5c0-.17.01-.34.03-.5H4v14h14v-8.17l-.3-.3zM5.5 18l2.75-3.53 1.96 2.36 2.75-3.54L16.5 18h-11z",
opacity: ".3"
}, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "m10.21 16.83-1.96-2.36L5.5 18h11l-3.54-4.71zM20 6.5C20 4.01 17.99 2 15.5 2S11 4.01 11 6.5s2.01 4.5 4.49 4.5c.88 0 1.7-.26 2.39-.7L21 13.42 22.42 12 19.3 8.89c.44-.7.7-1.51.7-2.39zM15.5 9C14.12 9 13 7.88 13 6.5S14.12 4 15.5 4 18 5.12 18 6.5 16.88 9 15.5 9zM18 20H4V6h6.03c.06-.72.27-1.39.58-2H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-6.17l-2-2V20z"
}, "1")], 'ImageSearchTwoTone');
exports.default = _default; | packages/mui-icons-material/lib/ImageSearchTwoTone.js | 0 | https://github.com/mui/material-ui/commit/8f06a1efc80f1289a65b6c1262fe769411d2e71c | [
0.0003705345734488219,
0.00026961055118590593,
0.00016868652892298996,
0.00026961055118590593,
0.00010092402226291597
] |
{
"id": 0,
"code_window": [
"\n",
"import { Codicon } from 'vs/base/common/codicons';\n",
"import { ServicesAccessor } from 'vs/editor/browser/editorExtensions';\n",
"import { localize } from 'vs/nls';\n",
"import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions';\n",
"import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';\n",
"import { INTERACTIVE_SESSION_CATEGORY } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionActions';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts",
"type": "replace",
"edit_start_line_idx": 9
} | /*---------------------------------------------------------------------------------------------
* 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 { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels';
import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list';
import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';
import { ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree';
import { IntervalTimer } from 'vs/base/common/async';
import { Codicon } from 'vs/base/common/codicons';
import { Emitter, Event } from 'vs/base/common/event';
import { FuzzyScore } from 'vs/base/common/filters';
import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent';
import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import { ResourceMap } from 'vs/base/common/map';
import { FileAccess } from 'vs/base/common/network';
import { ThemeIcon } from 'vs/base/common/themables';
import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions';
import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget';
import { EDITOR_FONT_DEFAULTS, IEditorOptions } from 'vs/editor/common/config/editorOptions';
import { Range } from 'vs/editor/common/core/range';
import { ILanguageService } from 'vs/editor/common/languages/language';
import { ITextModel } from 'vs/editor/common/model';
import { IModelService } from 'vs/editor/common/services/model';
import { BracketMatchingController } from 'vs/editor/contrib/bracketMatching/browser/bracketMatching';
import { ContextMenuController } from 'vs/editor/contrib/contextmenu/browser/contextmenu';
import { IMarkdownRenderResult, MarkdownRenderer } from 'vs/editor/contrib/markdownRenderer/browser/markdownRenderer';
import { ViewportSemanticTokensContribution } from 'vs/editor/contrib/semanticTokens/browser/viewportSemanticTokens';
import { SmartSelectController } from 'vs/editor/contrib/smartSelect/browser/smartSelect';
import { WordHighlighterContribution } from 'vs/editor/contrib/wordHighlighter/browser/wordHighlighter';
import { localize } from 'vs/nls';
import { MenuWorkbenchToolBar } from 'vs/platform/actions/browser/toolbar';
import { MenuId } from 'vs/platform/actions/common/actions';
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 { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { ILogService } from 'vs/platform/log/common/log';
import { defaultButtonStyles } from 'vs/platform/theme/browser/defaultStyles';
import { MenuPreventer } from 'vs/workbench/contrib/codeEditor/browser/menuPreventer';
import { SelectionClipboardContributionID } from 'vs/workbench/contrib/codeEditor/browser/selectionClipboard';
import { getSimpleEditorOptions } from 'vs/workbench/contrib/codeEditor/browser/simpleEditorOptions';
import { IInteractiveSessionCodeBlockActionContext } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionCodeblockActions';
import { InteractiveSessionFollowups } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionFollowups';
import { InteractiveSessionEditorOptions } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionOptions';
import { CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys';
import { IInteractiveSessionReplyFollowup, IInteractiveSessionService, IInteractiveSlashCommand, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';
import { IInteractiveRequestViewModel, IInteractiveResponseViewModel, IInteractiveWelcomeMessageViewModel, isRequestVM, isResponseVM, isWelcomeVM } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel';
import { getNWords } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionWordCounter';
const $ = dom.$;
export type InteractiveTreeItem = IInteractiveRequestViewModel | IInteractiveResponseViewModel | IInteractiveWelcomeMessageViewModel;
interface IInteractiveListItemTemplate {
rowContainer: HTMLElement;
titleToolbar: MenuWorkbenchToolBar;
avatar: HTMLElement;
username: HTMLElement;
value: HTMLElement;
contextKeyService: IContextKeyService;
templateDisposables: IDisposable;
elementDisposables: DisposableStore;
}
interface IItemHeightChangeParams {
element: InteractiveTreeItem;
height: number;
}
const forceVerboseLayoutTracing = false;
export interface IInteractiveSessionRendererDelegate {
getListLength(): number;
getSlashCommands(): IInteractiveSlashCommand[];
}
export class InteractiveListItemRenderer extends Disposable implements ITreeRenderer<InteractiveTreeItem, FuzzyScore, IInteractiveListItemTemplate> {
static readonly cursorCharacter = '\u258c';
static readonly ID = 'item';
private readonly renderer: MarkdownRenderer;
protected readonly _onDidClickFollowup = this._register(new Emitter<IInteractiveSessionReplyFollowup>());
readonly onDidClickFollowup: Event<IInteractiveSessionReplyFollowup> = this._onDidClickFollowup.event;
protected readonly _onDidChangeItemHeight = this._register(new Emitter<IItemHeightChangeParams>());
readonly onDidChangeItemHeight: Event<IItemHeightChangeParams> = this._onDidChangeItemHeight.event;
private readonly _editorPool: EditorPool;
private _currentLayoutWidth: number = 0;
constructor(
private readonly editorOptions: InteractiveSessionEditorOptions,
private readonly delegate: IInteractiveSessionRendererDelegate,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IConfigurationService private readonly configService: IConfigurationService,
@ILogService private readonly logService: ILogService,
@ICommandService private readonly commandService: ICommandService,
@IContextKeyService private readonly contextKeyService: IContextKeyService,
@IInteractiveSessionService private readonly interactiveSessionService: IInteractiveSessionService,
) {
super();
this.renderer = this.instantiationService.createInstance(MarkdownRenderer, {});
this._editorPool = this._register(this.instantiationService.createInstance(EditorPool, this.editorOptions));
}
get templateId(): string {
return InteractiveListItemRenderer.ID;
}
private traceLayout(method: string, message: string) {
if (forceVerboseLayoutTracing) {
this.logService.info(`InteractiveListItemRenderer#${method}: ${message}`);
} else {
this.logService.trace(`InteractiveListItemRenderer#${method}: ${message}`);
}
}
private shouldRenderProgressively(element: IInteractiveResponseViewModel): boolean {
return !this.configService.getValue('interactive.experimental.disableProgressiveRendering') && element.progressiveResponseRenderingEnabled;
}
private getProgressiveRenderRate(element: IInteractiveResponseViewModel): number {
const configuredRate = this.configService.getValue('interactive.experimental.progressiveRenderingRate');
if (typeof configuredRate === 'number') {
return configuredRate;
}
if (element.isComplete) {
return 60;
}
if (element.contentUpdateTimings && element.contentUpdateTimings.impliedWordLoadRate) {
// This doesn't account for dead time after the last update. When the previous update is the final one and the model is only waiting for followupQuestions, that's good.
// When there was one quick update and then you are waiting longer for the next one, that's not good since the rate should be decreasing.
// If it's an issue, we can change this to be based on the total time from now to the beginning.
const rateBoost = 1.5;
return element.contentUpdateTimings.impliedWordLoadRate * rateBoost;
}
return 8;
}
layout(width: number): void {
this._currentLayoutWidth = width - 40; // TODO Padding
this._editorPool.inUse.forEach(editor => {
editor.layout(this._currentLayoutWidth);
});
}
renderTemplate(container: HTMLElement): IInteractiveListItemTemplate {
const templateDisposables = new DisposableStore();
const rowContainer = dom.append(container, $('.interactive-item-container'));
const header = dom.append(rowContainer, $('.header'));
const user = dom.append(header, $('.user'));
const avatar = dom.append(user, $('.avatar'));
const username = dom.append(user, $('h3.username'));
const value = dom.append(rowContainer, $('.value'));
const elementDisposables = new DisposableStore();
const contextKeyService = templateDisposables.add(this.contextKeyService.createScoped(rowContainer));
const scopedInstantiationService = this.instantiationService.createChild(new ServiceCollection([IContextKeyService, contextKeyService]));
const titleToolbar = templateDisposables.add(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, header, MenuId.InteractiveSessionTitle, {
menuOptions: {
shouldForwardArgs: true
}
}));
const template: IInteractiveListItemTemplate = { avatar, username, value, rowContainer, elementDisposables, titleToolbar, templateDisposables, contextKeyService };
return template;
}
renderElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void {
const { element } = node;
const kind = isRequestVM(element) ? 'request' :
isResponseVM(element) ? 'response' :
'welcome';
this.traceLayout('renderElement', `${kind}, index=${index}`);
CONTEXT_RESPONSE_HAS_PROVIDER_ID.bindTo(templateData.contextKeyService).set(isResponseVM(element) && !!element.providerResponseId && !element.isPlaceholder);
if (isResponseVM(element)) {
CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set(element.vote === InteractiveSessionVoteDirection.Up ? 'up' : element.vote === InteractiveSessionVoteDirection.Down ? 'down' : '');
} else {
CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set('');
}
templateData.titleToolbar.context = element;
templateData.rowContainer.classList.toggle('interactive-request', isRequestVM(element));
templateData.rowContainer.classList.toggle('interactive-response', isResponseVM(element));
templateData.rowContainer.classList.toggle('interactive-welcome', isWelcomeVM(element));
templateData.rowContainer.classList.toggle('filtered-response', !!(isResponseVM(element) && element.errorDetails?.responseIsFiltered));
templateData.username.textContent = element.username;
if (element.avatarIconUri) {
const avatarIcon = dom.$<HTMLImageElement>('img.icon');
avatarIcon.src = FileAccess.uriToBrowserUri(element.avatarIconUri).toString(true);
templateData.avatar.replaceChildren(avatarIcon);
} else {
const defaultIcon = isRequestVM(element) ? Codicon.account : Codicon.hubot;
const avatarIcon = dom.$(ThemeIcon.asCSSSelector(defaultIcon));
templateData.avatar.replaceChildren(avatarIcon);
}
// Do a progressive render if
// - This the last response in the list
// - And the response is not complete
// - Or, we previously started a progressive rendering of this element (if the element is complete, we will finish progressive rendering with a very fast rate)
// - And, the feature is not disabled in configuration
if (isResponseVM(element) && index === this.delegate.getListLength() - 1 && (!element.isComplete || element.renderData) && this.shouldRenderProgressively(element)) {
this.traceLayout('renderElement', `start progressive render ${kind}, index=${index}`);
const progressiveRenderingDisposables = templateData.elementDisposables.add(new DisposableStore());
const timer = templateData.elementDisposables.add(new IntervalTimer());
const runProgressiveRender = (initial?: boolean) => {
try {
if (this.doNextProgressiveRender(element, index, templateData, !!initial, progressiveRenderingDisposables)) {
timer.cancel();
}
} catch (err) {
// Kill the timer if anything went wrong, avoid getting stuck in a nasty rendering loop.
timer.cancel();
throw err;
}
};
runProgressiveRender(true);
timer.cancelAndSet(runProgressiveRender, 50);
} else if (isResponseVM(element)) {
this.basicRenderElement(element.response.value, element, index, templateData);
} else if (isRequestVM(element)) {
this.basicRenderElement(element.messageText, element, index, templateData);
} else {
this.renderWelcomeMessage(element, templateData);
}
}
private basicRenderElement(markdownValue: string, element: InteractiveTreeItem, index: number, templateData: IInteractiveListItemTemplate) {
const fillInIncompleteTokens = isResponseVM(element) && (!element.isComplete || element.isCanceled || element.errorDetails?.responseIsFiltered || element.errorDetails?.responseIsIncomplete);
const result = this.renderMarkdown(new MarkdownString(markdownValue), element, templateData.elementDisposables, templateData, fillInIncompleteTokens);
dom.clearNode(templateData.value);
templateData.value.appendChild(result.element);
templateData.elementDisposables.add(result);
if (isResponseVM(element) && element.errorDetails?.message) {
const errorDetails = dom.append(templateData.value, $('.interactive-response-error-details', undefined, renderIcon(Codicon.error)));
errorDetails.appendChild($('span', undefined, element.errorDetails.message));
}
if (isResponseVM(element) && element.commandFollowups?.length) {
const followupsContainer = dom.append(templateData.value, $('.interactive-response-followups'));
templateData.elementDisposables.add(new InteractiveSessionFollowups(
followupsContainer,
element.commandFollowups,
defaultButtonStyles,
followup => {
this.interactiveSessionService.notifyUserAction({
providerId: element.providerId,
action: {
kind: 'command',
command: followup
}
});
return this.commandService.executeCommand(followup.commandId, ...(followup.args ?? []));
}));
}
}
private renderWelcomeMessage(element: IInteractiveWelcomeMessageViewModel, templateData: IInteractiveListItemTemplate) {
dom.clearNode(templateData.value);
const slashCommands = this.delegate.getSlashCommands();
for (const item of element.content) {
if (Array.isArray(item)) {
templateData.elementDisposables.add(new InteractiveSessionFollowups(
templateData.value,
item,
undefined,
followup => this._onDidClickFollowup.fire(followup)));
} else {
const result = this.renderMarkdown(item as IMarkdownString, element, templateData.elementDisposables, templateData);
for (const codeElement of result.element.querySelectorAll('code')) {
if (codeElement.textContent && slashCommands.find(command => codeElement.textContent === `/${command.command}`)) {
codeElement.classList.add('interactive-slash-command');
}
}
templateData.value.appendChild(result.element);
templateData.elementDisposables.add(result);
}
}
}
private doNextProgressiveRender(element: IInteractiveResponseViewModel, index: number, templateData: IInteractiveListItemTemplate, isInRenderElement: boolean, disposables: DisposableStore): boolean {
disposables.clear();
let isFullyRendered = false;
if (element.isCanceled) {
this.traceLayout('runProgressiveRender', `canceled, index=${index}`);
element.renderData = undefined;
this.basicRenderElement(element.response.value, element, index, templateData);
isFullyRendered = true;
} else {
// TODO- this method has the side effect of updating element.renderData
const toRender = this.getProgressiveMarkdownToRender(element);
isFullyRendered = !!element.renderData?.isFullyRendered;
if (isFullyRendered) {
// We've reached the end of the available content, so do a normal render
this.traceLayout('runProgressiveRender', `end progressive render, index=${index}`);
if (element.isComplete) {
this.traceLayout('runProgressiveRender', `and disposing renderData, response is complete, index=${index}`);
element.renderData = undefined;
} else {
this.traceLayout('runProgressiveRender', `Rendered all available words, but model is not complete.`);
}
disposables.clear();
this.basicRenderElement(element.response.value, element, index, templateData);
} else if (toRender) {
// Doing the progressive render
const plusCursor = toRender.match(/```.*$/) ? toRender + `\n${InteractiveListItemRenderer.cursorCharacter}` : toRender + ` ${InteractiveListItemRenderer.cursorCharacter}`;
const result = this.renderMarkdown(new MarkdownString(plusCursor), element, disposables, templateData, true);
dom.clearNode(templateData.value);
templateData.value.appendChild(result.element);
disposables.add(result);
} else {
// Nothing new to render, not done, keep waiting
return false;
}
}
// Some render happened - update the height
const height = templateData.rowContainer.offsetHeight;
element.currentRenderedHeight = height;
if (!isInRenderElement) {
this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight });
}
return !!isFullyRendered;
}
private renderMarkdown(markdown: IMarkdownString, element: InteractiveTreeItem, disposables: DisposableStore, templateData: IInteractiveListItemTemplate, fillInIncompleteTokens = false): IMarkdownRenderResult {
const disposablesList: IDisposable[] = [];
let codeBlockIndex = 0;
// TODO if the slash commands stay completely dynamic, this isn't quite right
const slashCommands = this.delegate.getSlashCommands();
const usedSlashCommand = slashCommands.find(s => markdown.value.startsWith(`/${s.command} `));
const toRender = usedSlashCommand ? markdown.value.slice(usedSlashCommand.command.length + 2) : markdown.value;
markdown = new MarkdownString(toRender);
const result = this.renderer.render(markdown, {
fillInIncompleteTokens,
codeBlockRendererSync: (languageId, text) => {
const ref = this.renderCodeBlock({ languageId, text, codeBlockIndex: codeBlockIndex++, element, parentContextKeyService: templateData.contextKeyService }, disposables);
// Attach this after updating text/layout of the editor, so it should only be fired when the size updates later (horizontal scrollbar, wrapping)
// not during a renderElement OR a progressive render (when we will be firing this event anyway at the end of the render)
disposables.add(ref.object.onDidChangeContentHeight(() => {
ref.object.layout(this._currentLayoutWidth);
this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight });
}));
disposablesList.push(ref);
return ref.object.element;
}
});
if (usedSlashCommand) {
const slashCommandElement = $('span.interactive-slash-command', { title: usedSlashCommand.detail }, `/${usedSlashCommand.command} `);
if (result.element.firstChild?.nodeName.toLowerCase() === 'p') {
result.element.firstChild.insertBefore(slashCommandElement, result.element.firstChild.firstChild);
} else {
result.element.insertBefore($('p', undefined, slashCommandElement), result.element.firstChild);
}
}
disposablesList.reverse().forEach(d => disposables.add(d));
return result;
}
private renderCodeBlock(data: IInteractiveResultCodeBlockData, disposables: DisposableStore): IDisposableReference<IInteractiveResultCodeBlockPart> {
const ref = this._editorPool.get();
const editorInfo = ref.object;
editorInfo.render(data, this._currentLayoutWidth);
return ref;
}
private getProgressiveMarkdownToRender(element: IInteractiveResponseViewModel): string | undefined {
const renderData = element.renderData ?? { renderedWordCount: 0, lastRenderTime: 0 };
const rate = this.getProgressiveRenderRate(element);
const numWordsToRender = renderData.lastRenderTime === 0 ?
1 :
renderData.renderedWordCount +
// Additional words to render beyond what's already rendered
Math.floor((Date.now() - renderData.lastRenderTime) / 1000 * rate);
if (numWordsToRender === renderData.renderedWordCount) {
return undefined;
}
const result = getNWords(element.response.value, numWordsToRender);
element.renderData = {
renderedWordCount: result.actualWordCount,
lastRenderTime: Date.now(),
isFullyRendered: result.isFullString
};
return result.value;
}
disposeElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void {
templateData.elementDisposables.clear();
}
disposeTemplate(templateData: IInteractiveListItemTemplate): void {
templateData.templateDisposables.dispose();
}
}
export class InteractiveSessionListDelegate implements IListVirtualDelegate<InteractiveTreeItem> {
constructor(
@ILogService private readonly logService: ILogService
) { }
private _traceLayout(method: string, message: string) {
if (forceVerboseLayoutTracing) {
this.logService.info(`InteractiveSessionListDelegate#${method}: ${message}`);
} else {
this.logService.trace(`InteractiveSessionListDelegate#${method}: ${message}`);
}
}
getHeight(element: InteractiveTreeItem): number {
const kind = isRequestVM(element) ? 'request' : 'response';
const height = ('currentRenderedHeight' in element ? element.currentRenderedHeight : undefined) ?? 200;
this._traceLayout('getHeight', `${kind}, height=${height}`);
return height;
}
getTemplateId(element: InteractiveTreeItem): string {
return InteractiveListItemRenderer.ID;
}
hasDynamicHeight(element: InteractiveTreeItem): boolean {
return true;
}
}
export class InteractiveSessionAccessibilityProvider implements IListAccessibilityProvider<InteractiveTreeItem> {
getWidgetAriaLabel(): string {
return localize('interactiveSession', "Interactive Session");
}
getAriaLabel(element: InteractiveTreeItem): string {
if (isRequestVM(element)) {
return localize('interactiveRequest', "Request: {0}", element.messageText);
}
if (isResponseVM(element)) {
return localize('interactiveResponse', "Response: {0}", element.response.value);
}
return '';
}
}
interface IInteractiveResultCodeBlockData {
text: string;
languageId: string;
codeBlockIndex: number;
element: InteractiveTreeItem;
parentContextKeyService: IContextKeyService;
}
interface IInteractiveResultCodeBlockPart {
readonly onDidChangeContentHeight: Event<number>;
readonly element: HTMLElement;
readonly textModel: ITextModel;
layout(width: number): void;
render(data: IInteractiveResultCodeBlockData, width: number): void;
dispose(): void;
}
export interface IInteractiveResultCodeBlockInfo {
providerId: string;
responseId: string;
codeBlockIndex: number;
}
export const codeBlockInfosByModelUri = new ResourceMap<IInteractiveResultCodeBlockInfo>();
class CodeBlockPart extends Disposable implements IInteractiveResultCodeBlockPart {
private readonly _onDidChangeContentHeight = this._register(new Emitter<number>());
public readonly onDidChangeContentHeight = this._onDidChangeContentHeight.event;
private readonly editor: CodeEditorWidget;
private readonly toolbar: MenuWorkbenchToolBar;
private readonly contextKeyService: IContextKeyService;
public readonly textModel: ITextModel;
public readonly element: HTMLElement;
constructor(
private readonly options: InteractiveSessionEditorOptions,
@IInstantiationService instantiationService: IInstantiationService,
@IContextKeyService contextKeyService: IContextKeyService,
@ILanguageService private readonly languageService: ILanguageService,
@IModelService private readonly modelService: IModelService,
) {
super();
this.element = $('.interactive-result-editor-wrapper');
this.contextKeyService = this._register(contextKeyService.createScoped(this.element));
const scopedInstantiationService = instantiationService.createChild(new ServiceCollection([IContextKeyService, this.contextKeyService]));
this.toolbar = this._register(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, this.element, MenuId.InteractiveSessionCodeBlock, {
menuOptions: {
shouldForwardArgs: true
}
}));
const editorElement = dom.append(this.element, $('.interactive-result-editor'));
this.editor = this._register(scopedInstantiationService.createInstance(CodeEditorWidget, editorElement, {
...getSimpleEditorOptions(),
readOnly: true,
lineNumbers: 'off',
selectOnLineNumbers: true,
scrollBeyondLastLine: false,
lineDecorationsWidth: 8,
dragAndDrop: false,
padding: { top: 2, bottom: 2 },
mouseWheelZoom: false,
scrollbar: {
alwaysConsumeMouseWheel: false
},
...this.getEditorOptionsFromConfig()
}, {
isSimpleWidget: true,
contributions: EditorExtensionsRegistry.getSomeEditorContributions([
MenuPreventer.ID,
SelectionClipboardContributionID,
ContextMenuController.ID,
WordHighlighterContribution.ID,
ViewportSemanticTokensContribution.ID,
BracketMatchingController.ID,
SmartSelectController.ID,
])
}));
this._register(this.options.onDidChange(() => {
this.editor.updateOptions(this.getEditorOptionsFromConfig());
}));
this._register(this.editor.onDidContentSizeChange(e => {
if (e.contentHeightChanged) {
this._onDidChangeContentHeight.fire(e.contentHeight);
}
}));
this._register(this.editor.onDidBlurEditorWidget(() => {
WordHighlighterContribution.get(this.editor)?.stopHighlighting();
}));
this._register(this.editor.onDidFocusEditorWidget(() => {
WordHighlighterContribution.get(this.editor)?.restoreViewState(true);
}));
const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName('javascript');
this.textModel = this._register(this.modelService.createModel('', this.languageService.createById(vscodeLanguageId), undefined));
this.editor.setModel(this.textModel);
}
private getEditorOptionsFromConfig(): IEditorOptions {
return {
wordWrap: this.options.configuration.resultEditor.wordWrap,
fontLigatures: this.options.configuration.resultEditor.fontLigatures,
bracketPairColorization: this.options.configuration.resultEditor.bracketPairColorization,
fontFamily: this.options.configuration.resultEditor.fontFamily === 'default' ?
EDITOR_FONT_DEFAULTS.fontFamily :
this.options.configuration.resultEditor.fontFamily,
fontSize: this.options.configuration.resultEditor.fontSize,
fontWeight: this.options.configuration.resultEditor.fontWeight,
lineHeight: this.options.configuration.resultEditor.lineHeight,
};
}
layout(width: number): void {
const realContentHeight = this.editor.getContentHeight();
const editorBorder = 2;
this.editor.layout({ width: width - editorBorder, height: realContentHeight });
}
render(data: IInteractiveResultCodeBlockData, width: number): void {
this.contextKeyService.updateParent(data.parentContextKeyService);
if (this.options.configuration.resultEditor.wordWrap === 'on') {
// Intialize the editor with the new proper width so that getContentHeight
// will be computed correctly in the next call to layout()
this.layout(width);
}
this.setText(data.text);
this.setLanguage(data.languageId);
this.layout(width);
if (isResponseVM(data.element) && data.element.providerResponseId) {
// For telemetry reporting
codeBlockInfosByModelUri.set(this.textModel.uri, {
providerId: data.element.providerId,
responseId: data.element.providerResponseId,
codeBlockIndex: data.codeBlockIndex
});
} else {
codeBlockInfosByModelUri.delete(this.textModel.uri);
}
this.toolbar.context = <IInteractiveSessionCodeBlockActionContext>{
code: data.text,
codeBlockIndex: data.codeBlockIndex,
element: data.element
};
}
private setText(newText: string): void {
let currentText = this.textModel.getLinesContent().join('\n');
if (newText === currentText) {
return;
}
let removedChars = 0;
if (currentText.endsWith(` ${InteractiveListItemRenderer.cursorCharacter}`)) {
removedChars = 2;
} else if (currentText.endsWith(InteractiveListItemRenderer.cursorCharacter)) {
removedChars = 1;
}
if (removedChars > 0) {
currentText = currentText.slice(0, currentText.length - removedChars);
}
if (newText.startsWith(currentText)) {
const text = newText.slice(currentText.length);
const lastLine = this.textModel.getLineCount();
const lastCol = this.textModel.getLineMaxColumn(lastLine);
const insertAtCol = lastCol - removedChars;
this.textModel.applyEdits([{ range: new Range(lastLine, insertAtCol, lastLine, lastCol), text }]);
} else {
// console.log(`Failed to optimize setText`);
this.textModel.setValue(newText);
}
}
private setLanguage(languageId: string): void {
const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName(languageId);
if (vscodeLanguageId) {
this.textModel.setLanguage(vscodeLanguageId);
}
}
}
interface IDisposableReference<T> extends IDisposable {
object: T;
}
class EditorPool extends Disposable {
private _pool: ResourcePool<IInteractiveResultCodeBlockPart>;
public get inUse(): ReadonlySet<IInteractiveResultCodeBlockPart> {
return this._pool.inUse;
}
constructor(
private readonly options: InteractiveSessionEditorOptions,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
this._pool = this._register(new ResourcePool(() => this.editorFactory()));
// TODO listen to changes on options
}
private editorFactory(): IInteractiveResultCodeBlockPart {
return this.instantiationService.createInstance(CodeBlockPart, this.options);
}
get(): IDisposableReference<IInteractiveResultCodeBlockPart> {
const object = this._pool.get();
return {
object,
dispose: () => this._pool.release(object)
};
}
}
// TODO does something in lifecycle.ts cover this?
class ResourcePool<T extends IDisposable> extends Disposable {
private readonly pool: T[] = [];
private _inUse = new Set<T>;
public get inUse(): ReadonlySet<T> {
return this._inUse;
}
constructor(
private readonly _itemFactory: () => T,
) {
super();
}
get(): T {
if (this.pool.length > 0) {
const item = this.pool.pop()!;
this._inUse.add(item);
return item;
}
const item = this._register(this._itemFactory());
this._inUse.add(item);
return item;
}
release(item: T): void {
this._inUse.delete(item);
this.pool.push(item);
}
}
| src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts | 1 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.012052689678966999,
0.0003636102192103863,
0.00016116102051455528,
0.00017105427104979753,
0.0013714684173464775
] |
{
"id": 0,
"code_window": [
"\n",
"import { Codicon } from 'vs/base/common/codicons';\n",
"import { ServicesAccessor } from 'vs/editor/browser/editorExtensions';\n",
"import { localize } from 'vs/nls';\n",
"import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions';\n",
"import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';\n",
"import { INTERACTIVE_SESSION_CATEGORY } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionActions';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts",
"type": "replace",
"edit_start_line_idx": 9
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Event } from 'vs/base/common/event';
import { Disposable, IDisposable } from 'vs/base/common/lifecycle';
import { URI } from 'vs/base/common/uri';
import { IFileDeleteOptions, IFileOverwriteOptions, FileSystemProviderCapabilities, FileType, IFileWriteOptions, hasReadWriteCapability, IFileService, IFileSystemProvider, IFileSystemProviderWithFileReadWriteCapability, IStat, IWatchOptions } from 'vs/platform/files/common/files';
import { isEqual } from 'vs/base/common/resources';
import { VSBuffer } from 'vs/base/common/buffer';
interface ILocalHistoryResource {
/**
* The location of the local history entry to read from.
*/
readonly location: URI;
/**
* The associated resource the local history entry is about.
*/
readonly associatedResource: URI;
}
interface ISerializedLocalHistoryResource {
readonly location: string;
readonly associatedResource: string;
}
/**
* A wrapper around a standard file system provider
* that is entirely readonly.
*/
export class LocalHistoryFileSystemProvider implements IFileSystemProvider, IFileSystemProviderWithFileReadWriteCapability {
static readonly SCHEMA = 'vscode-local-history';
static toLocalHistoryFileSystem(resource: ILocalHistoryResource): URI {
const serializedLocalHistoryResource: ISerializedLocalHistoryResource = {
location: resource.location.toString(true),
associatedResource: resource.associatedResource.toString(true)
};
// Try to preserve the associated resource as much as possible
// and only keep the `query` part dynamic. This enables other
// components (e.g. other timeline providers) to continue
// providing timeline entries even when our resource is active.
return resource.associatedResource.with({
scheme: LocalHistoryFileSystemProvider.SCHEMA,
query: JSON.stringify(serializedLocalHistoryResource)
});
}
static fromLocalHistoryFileSystem(resource: URI): ILocalHistoryResource {
const serializedLocalHistoryResource: ISerializedLocalHistoryResource = JSON.parse(resource.query);
return {
location: URI.parse(serializedLocalHistoryResource.location),
associatedResource: URI.parse(serializedLocalHistoryResource.associatedResource)
};
}
private static readonly EMPTY_RESOURCE = URI.from({ scheme: LocalHistoryFileSystemProvider.SCHEMA, path: '/empty' });
static readonly EMPTY: ILocalHistoryResource = {
location: LocalHistoryFileSystemProvider.EMPTY_RESOURCE,
associatedResource: LocalHistoryFileSystemProvider.EMPTY_RESOURCE
};
get capabilities() {
return FileSystemProviderCapabilities.FileReadWrite | FileSystemProviderCapabilities.Readonly;
}
constructor(private readonly fileService: IFileService) { }
private readonly mapSchemeToProvider = new Map<string, Promise<IFileSystemProvider>>();
private async withProvider(resource: URI): Promise<IFileSystemProvider> {
const scheme = resource.scheme;
let providerPromise = this.mapSchemeToProvider.get(scheme);
if (!providerPromise) {
// Resolve early when provider already exists
const provider = this.fileService.getProvider(scheme);
if (provider) {
providerPromise = Promise.resolve(provider);
}
// Otherwise wait for registration
else {
providerPromise = new Promise<IFileSystemProvider>(resolve => {
const disposable = this.fileService.onDidChangeFileSystemProviderRegistrations(e => {
if (e.added && e.provider && e.scheme === scheme) {
disposable.dispose();
resolve(e.provider);
}
});
});
}
this.mapSchemeToProvider.set(scheme, providerPromise);
}
return providerPromise;
}
//#region Supported File Operations
async stat(resource: URI): Promise<IStat> {
const location = LocalHistoryFileSystemProvider.fromLocalHistoryFileSystem(resource).location;
// Special case: empty resource
if (isEqual(LocalHistoryFileSystemProvider.EMPTY_RESOURCE, location)) {
return { type: FileType.File, ctime: 0, mtime: 0, size: 0 };
}
// Otherwise delegate to provider
return (await this.withProvider(location)).stat(location);
}
async readFile(resource: URI): Promise<Uint8Array> {
const location = LocalHistoryFileSystemProvider.fromLocalHistoryFileSystem(resource).location;
// Special case: empty resource
if (isEqual(LocalHistoryFileSystemProvider.EMPTY_RESOURCE, location)) {
return VSBuffer.fromString('').buffer;
}
// Otherwise delegate to provider
const provider = await this.withProvider(location);
if (hasReadWriteCapability(provider)) {
return provider.readFile(location);
}
throw new Error('Unsupported');
}
//#endregion
//#region Unsupported File Operations
readonly onDidChangeCapabilities = Event.None;
readonly onDidChangeFile = Event.None;
async writeFile(resource: URI, content: Uint8Array, opts: IFileWriteOptions): Promise<void> { }
async mkdir(resource: URI): Promise<void> { }
async readdir(resource: URI): Promise<[string, FileType][]> { return []; }
async rename(from: URI, to: URI, opts: IFileOverwriteOptions): Promise<void> { }
async delete(resource: URI, opts: IFileDeleteOptions): Promise<void> { }
watch(resource: URI, opts: IWatchOptions): IDisposable { return Disposable.None; }
//#endregion
}
| src/vs/workbench/contrib/localHistory/browser/localHistoryFileSystemProvider.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017584027955308557,
0.00017073508934117854,
0.00016287300968542695,
0.00017115689115598798,
0.000003173333880113205
] |
{
"id": 0,
"code_window": [
"\n",
"import { Codicon } from 'vs/base/common/codicons';\n",
"import { ServicesAccessor } from 'vs/editor/browser/editorExtensions';\n",
"import { localize } from 'vs/nls';\n",
"import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions';\n",
"import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';\n",
"import { INTERACTIVE_SESSION_CATEGORY } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionActions';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts",
"type": "replace",
"edit_start_line_idx": 9
} | declare module 'github-releases' {
} | build/lib/typings/github-releases.d.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00016846759535837919,
0.00016846759535837919,
0.00016846759535837919,
0.00016846759535837919,
0
] |
{
"id": 0,
"code_window": [
"\n",
"import { Codicon } from 'vs/base/common/codicons';\n",
"import { ServicesAccessor } from 'vs/editor/browser/editorExtensions';\n",
"import { localize } from 'vs/nls';\n",
"import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions';\n",
"import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';\n",
"import { INTERACTIVE_SESSION_CATEGORY } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionActions';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts",
"type": "replace",
"edit_start_line_idx": 9
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import { isCancellationError } from 'vs/base/common/errors';
import { DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import { isNative } from 'vs/base/common/platform';
import { withNullAsUndefined } from 'vs/base/common/types';
import { URI, UriComponents } from 'vs/base/common/uri';
import { localize } from 'vs/nls';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IFileService } from 'vs/platform/files/common/files';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ILabelService } from 'vs/platform/label/common/label';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IRequestService } from 'vs/platform/request/common/request';
import { WorkspaceTrustRequestOptions, IWorkspaceTrustManagementService, IWorkspaceTrustRequestService } from 'vs/platform/workspace/common/workspaceTrust';
import { IWorkspace, IWorkspaceContextService, WorkbenchState, isUntitledWorkspace, WorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { extHostNamedCustomer, IExtHostContext } from 'vs/workbench/services/extensions/common/extHostCustomers';
import { checkGlobFileExists } from 'vs/workbench/services/extensions/common/workspaceContains';
import { ITextQueryBuilderOptions, QueryBuilder } from 'vs/workbench/services/search/common/queryBuilder';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IFileMatch, IPatternInfo, ISearchProgressItem, ISearchService } from 'vs/workbench/services/search/common/search';
import { IWorkspaceEditingService } from 'vs/workbench/services/workspaces/common/workspaceEditing';
import { ExtHostContext, ExtHostWorkspaceShape, ITextSearchComplete, IWorkspaceData, MainContext, MainThreadWorkspaceShape } from '../common/extHost.protocol';
import { IEditSessionIdentityService } from 'vs/platform/workspace/common/editSessions';
@extHostNamedCustomer(MainContext.MainThreadWorkspace)
export class MainThreadWorkspace implements MainThreadWorkspaceShape {
private readonly _toDispose = new DisposableStore();
private readonly _activeCancelTokens: { [id: number]: CancellationTokenSource } = Object.create(null);
private readonly _proxy: ExtHostWorkspaceShape;
private readonly _queryBuilder = this._instantiationService.createInstance(QueryBuilder);
constructor(
extHostContext: IExtHostContext,
@ISearchService private readonly _searchService: ISearchService,
@IWorkspaceContextService private readonly _contextService: IWorkspaceContextService,
@IEditSessionIdentityService private readonly _editSessionIdentityService: IEditSessionIdentityService,
@IEditorService private readonly _editorService: IEditorService,
@IWorkspaceEditingService private readonly _workspaceEditingService: IWorkspaceEditingService,
@INotificationService private readonly _notificationService: INotificationService,
@IRequestService private readonly _requestService: IRequestService,
@IInstantiationService private readonly _instantiationService: IInstantiationService,
@ILabelService private readonly _labelService: ILabelService,
@IEnvironmentService private readonly _environmentService: IEnvironmentService,
@IFileService fileService: IFileService,
@IWorkspaceTrustManagementService private readonly _workspaceTrustManagementService: IWorkspaceTrustManagementService,
@IWorkspaceTrustRequestService private readonly _workspaceTrustRequestService: IWorkspaceTrustRequestService
) {
this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostWorkspace);
const workspace = this._contextService.getWorkspace();
// The workspace file is provided be a unknown file system provider. It might come
// from the extension host. So initialize now knowing that `rootPath` is undefined.
if (workspace.configuration && !isNative && !fileService.hasProvider(workspace.configuration)) {
this._proxy.$initializeWorkspace(this.getWorkspaceData(workspace), this.isWorkspaceTrusted());
} else {
this._contextService.getCompleteWorkspace().then(workspace => this._proxy.$initializeWorkspace(this.getWorkspaceData(workspace), this.isWorkspaceTrusted()));
}
this._contextService.onDidChangeWorkspaceFolders(this._onDidChangeWorkspace, this, this._toDispose);
this._contextService.onDidChangeWorkbenchState(this._onDidChangeWorkspace, this, this._toDispose);
this._workspaceTrustManagementService.onDidChangeTrust(this._onDidGrantWorkspaceTrust, this, this._toDispose);
}
dispose(): void {
this._toDispose.dispose();
for (const requestId in this._activeCancelTokens) {
const tokenSource = this._activeCancelTokens[requestId];
tokenSource.cancel();
}
}
// --- workspace ---
$updateWorkspaceFolders(extensionName: string, index: number, deleteCount: number, foldersToAdd: { uri: UriComponents; name?: string }[]): Promise<void> {
const workspaceFoldersToAdd = foldersToAdd.map(f => ({ uri: URI.revive(f.uri), name: f.name }));
// Indicate in status message
this._notificationService.status(this.getStatusMessage(extensionName, workspaceFoldersToAdd.length, deleteCount), { hideAfter: 10 * 1000 /* 10s */ });
return this._workspaceEditingService.updateFolders(index, deleteCount, workspaceFoldersToAdd, true);
}
private getStatusMessage(extensionName: string, addCount: number, removeCount: number): string {
let message: string;
const wantsToAdd = addCount > 0;
const wantsToDelete = removeCount > 0;
// Add Folders
if (wantsToAdd && !wantsToDelete) {
if (addCount === 1) {
message = localize('folderStatusMessageAddSingleFolder', "Extension '{0}' added 1 folder to the workspace", extensionName);
} else {
message = localize('folderStatusMessageAddMultipleFolders', "Extension '{0}' added {1} folders to the workspace", extensionName, addCount);
}
}
// Delete Folders
else if (wantsToDelete && !wantsToAdd) {
if (removeCount === 1) {
message = localize('folderStatusMessageRemoveSingleFolder', "Extension '{0}' removed 1 folder from the workspace", extensionName);
} else {
message = localize('folderStatusMessageRemoveMultipleFolders', "Extension '{0}' removed {1} folders from the workspace", extensionName, removeCount);
}
}
// Change Folders
else {
message = localize('folderStatusChangeFolder', "Extension '{0}' changed folders of the workspace", extensionName);
}
return message;
}
private _onDidChangeWorkspace(): void {
this._proxy.$acceptWorkspaceData(this.getWorkspaceData(this._contextService.getWorkspace()));
}
private getWorkspaceData(workspace: IWorkspace): IWorkspaceData | null {
if (this._contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
return null;
}
return {
configuration: workspace.configuration || undefined,
isUntitled: workspace.configuration ? isUntitledWorkspace(workspace.configuration, this._environmentService) : false,
folders: workspace.folders,
id: workspace.id,
name: this._labelService.getWorkspaceLabel(workspace),
transient: workspace.transient
};
}
// --- search ---
$startFileSearch(includePattern: string | null, _includeFolder: UriComponents | null, excludePatternOrDisregardExcludes: string | false | null, maxResults: number | null, token: CancellationToken): Promise<UriComponents[] | null> {
const includeFolder = URI.revive(_includeFolder);
const workspace = this._contextService.getWorkspace();
if (!workspace.folders.length) {
return Promise.resolve(null);
}
const query = this._queryBuilder.file(
includeFolder ? [includeFolder] : workspace.folders,
{
maxResults: withNullAsUndefined(maxResults),
disregardExcludeSettings: (excludePatternOrDisregardExcludes === false) || undefined,
disregardSearchExcludeSettings: true,
disregardIgnoreFiles: true,
includePattern: withNullAsUndefined(includePattern),
excludePattern: typeof excludePatternOrDisregardExcludes === 'string' ? excludePatternOrDisregardExcludes : undefined,
_reason: 'startFileSearch'
});
return this._searchService.fileSearch(query, token).then(result => {
return result.results.map(m => m.resource);
}, err => {
if (!isCancellationError(err)) {
return Promise.reject(err);
}
return null;
});
}
$startTextSearch(pattern: IPatternInfo, _folder: UriComponents | null, options: ITextQueryBuilderOptions, requestId: number, token: CancellationToken): Promise<ITextSearchComplete | null> {
const folder = URI.revive(_folder);
const workspace = this._contextService.getWorkspace();
const folders = folder ? [folder] : workspace.folders.map(folder => folder.uri);
const query = this._queryBuilder.text(pattern, folders, options);
query._reason = 'startTextSearch';
const onProgress = (p: ISearchProgressItem) => {
if ((<IFileMatch>p).results) {
this._proxy.$handleTextSearchResult(<IFileMatch>p, requestId);
}
};
const search = this._searchService.textSearch(query, token, onProgress).then(
result => {
return { limitHit: result.limitHit };
},
err => {
if (!isCancellationError(err)) {
return Promise.reject(err);
}
return null;
});
return search;
}
$checkExists(folders: readonly UriComponents[], includes: string[], token: CancellationToken): Promise<boolean> {
return this._instantiationService.invokeFunction((accessor) => checkGlobFileExists(accessor, folders, includes, token));
}
// --- save & edit resources ---
$saveAll(includeUntitled?: boolean): Promise<boolean> {
return this._editorService.saveAll({ includeUntitled });
}
$resolveProxy(url: string): Promise<string | undefined> {
return this._requestService.resolveProxy(url);
}
// --- trust ---
$requestWorkspaceTrust(options?: WorkspaceTrustRequestOptions): Promise<boolean | undefined> {
return this._workspaceTrustRequestService.requestWorkspaceTrust(options);
}
private isWorkspaceTrusted(): boolean {
return this._workspaceTrustManagementService.isWorkspaceTrusted();
}
private _onDidGrantWorkspaceTrust(): void {
this._proxy.$onDidGrantWorkspaceTrust();
}
// --- edit sessions ---
private registeredEditSessionProviders = new Map<number, IDisposable>();
$registerEditSessionIdentityProvider(handle: number, scheme: string) {
const disposable = this._editSessionIdentityService.registerEditSessionIdentityProvider({
scheme: scheme,
getEditSessionIdentifier: async (workspaceFolder: WorkspaceFolder, token: CancellationToken) => {
return this._proxy.$getEditSessionIdentifier(workspaceFolder.uri, token);
},
provideEditSessionIdentityMatch: async (workspaceFolder: WorkspaceFolder, identity1: string, identity2: string, token: CancellationToken) => {
return this._proxy.$provideEditSessionIdentityMatch(workspaceFolder.uri, identity1, identity2, token);
}
});
this.registeredEditSessionProviders.set(handle, disposable);
this._toDispose.add(disposable);
}
$unregisterEditSessionIdentityProvider(handle: number) {
const disposable = this.registeredEditSessionProviders.get(handle);
disposable?.dispose();
this.registeredEditSessionProviders.delete(handle);
}
}
| src/vs/workbench/api/browser/mainThreadWorkspace.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017372494039591402,
0.0001685413153609261,
0.0001633609354030341,
0.00016856320144142956,
0.000002606343286970514
] |
{
"id": 1,
"code_window": [
"import { INTERACTIVE_SESSION_CATEGORY } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionActions';\n",
"import { CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys';\n",
"import { IInteractiveSessionService, IInteractiveSessionUserActionEvent, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n",
"import { isResponseVM } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel';\n",
"\n",
"export function registerInteractiveSessionTitleActions() {\n",
"\tregisterAction2(class VoteUpAction extends Action2 {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys';\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts",
"type": "replace",
"edit_start_line_idx": 11
} | /*---------------------------------------------------------------------------------------------
* 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 { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels';
import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list';
import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';
import { ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree';
import { IntervalTimer } from 'vs/base/common/async';
import { Codicon } from 'vs/base/common/codicons';
import { Emitter, Event } from 'vs/base/common/event';
import { FuzzyScore } from 'vs/base/common/filters';
import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent';
import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import { ResourceMap } from 'vs/base/common/map';
import { FileAccess } from 'vs/base/common/network';
import { ThemeIcon } from 'vs/base/common/themables';
import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions';
import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget';
import { EDITOR_FONT_DEFAULTS, IEditorOptions } from 'vs/editor/common/config/editorOptions';
import { Range } from 'vs/editor/common/core/range';
import { ILanguageService } from 'vs/editor/common/languages/language';
import { ITextModel } from 'vs/editor/common/model';
import { IModelService } from 'vs/editor/common/services/model';
import { BracketMatchingController } from 'vs/editor/contrib/bracketMatching/browser/bracketMatching';
import { ContextMenuController } from 'vs/editor/contrib/contextmenu/browser/contextmenu';
import { IMarkdownRenderResult, MarkdownRenderer } from 'vs/editor/contrib/markdownRenderer/browser/markdownRenderer';
import { ViewportSemanticTokensContribution } from 'vs/editor/contrib/semanticTokens/browser/viewportSemanticTokens';
import { SmartSelectController } from 'vs/editor/contrib/smartSelect/browser/smartSelect';
import { WordHighlighterContribution } from 'vs/editor/contrib/wordHighlighter/browser/wordHighlighter';
import { localize } from 'vs/nls';
import { MenuWorkbenchToolBar } from 'vs/platform/actions/browser/toolbar';
import { MenuId } from 'vs/platform/actions/common/actions';
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 { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { ILogService } from 'vs/platform/log/common/log';
import { defaultButtonStyles } from 'vs/platform/theme/browser/defaultStyles';
import { MenuPreventer } from 'vs/workbench/contrib/codeEditor/browser/menuPreventer';
import { SelectionClipboardContributionID } from 'vs/workbench/contrib/codeEditor/browser/selectionClipboard';
import { getSimpleEditorOptions } from 'vs/workbench/contrib/codeEditor/browser/simpleEditorOptions';
import { IInteractiveSessionCodeBlockActionContext } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionCodeblockActions';
import { InteractiveSessionFollowups } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionFollowups';
import { InteractiveSessionEditorOptions } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionOptions';
import { CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys';
import { IInteractiveSessionReplyFollowup, IInteractiveSessionService, IInteractiveSlashCommand, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';
import { IInteractiveRequestViewModel, IInteractiveResponseViewModel, IInteractiveWelcomeMessageViewModel, isRequestVM, isResponseVM, isWelcomeVM } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel';
import { getNWords } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionWordCounter';
const $ = dom.$;
export type InteractiveTreeItem = IInteractiveRequestViewModel | IInteractiveResponseViewModel | IInteractiveWelcomeMessageViewModel;
interface IInteractiveListItemTemplate {
rowContainer: HTMLElement;
titleToolbar: MenuWorkbenchToolBar;
avatar: HTMLElement;
username: HTMLElement;
value: HTMLElement;
contextKeyService: IContextKeyService;
templateDisposables: IDisposable;
elementDisposables: DisposableStore;
}
interface IItemHeightChangeParams {
element: InteractiveTreeItem;
height: number;
}
const forceVerboseLayoutTracing = false;
export interface IInteractiveSessionRendererDelegate {
getListLength(): number;
getSlashCommands(): IInteractiveSlashCommand[];
}
export class InteractiveListItemRenderer extends Disposable implements ITreeRenderer<InteractiveTreeItem, FuzzyScore, IInteractiveListItemTemplate> {
static readonly cursorCharacter = '\u258c';
static readonly ID = 'item';
private readonly renderer: MarkdownRenderer;
protected readonly _onDidClickFollowup = this._register(new Emitter<IInteractiveSessionReplyFollowup>());
readonly onDidClickFollowup: Event<IInteractiveSessionReplyFollowup> = this._onDidClickFollowup.event;
protected readonly _onDidChangeItemHeight = this._register(new Emitter<IItemHeightChangeParams>());
readonly onDidChangeItemHeight: Event<IItemHeightChangeParams> = this._onDidChangeItemHeight.event;
private readonly _editorPool: EditorPool;
private _currentLayoutWidth: number = 0;
constructor(
private readonly editorOptions: InteractiveSessionEditorOptions,
private readonly delegate: IInteractiveSessionRendererDelegate,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IConfigurationService private readonly configService: IConfigurationService,
@ILogService private readonly logService: ILogService,
@ICommandService private readonly commandService: ICommandService,
@IContextKeyService private readonly contextKeyService: IContextKeyService,
@IInteractiveSessionService private readonly interactiveSessionService: IInteractiveSessionService,
) {
super();
this.renderer = this.instantiationService.createInstance(MarkdownRenderer, {});
this._editorPool = this._register(this.instantiationService.createInstance(EditorPool, this.editorOptions));
}
get templateId(): string {
return InteractiveListItemRenderer.ID;
}
private traceLayout(method: string, message: string) {
if (forceVerboseLayoutTracing) {
this.logService.info(`InteractiveListItemRenderer#${method}: ${message}`);
} else {
this.logService.trace(`InteractiveListItemRenderer#${method}: ${message}`);
}
}
private shouldRenderProgressively(element: IInteractiveResponseViewModel): boolean {
return !this.configService.getValue('interactive.experimental.disableProgressiveRendering') && element.progressiveResponseRenderingEnabled;
}
private getProgressiveRenderRate(element: IInteractiveResponseViewModel): number {
const configuredRate = this.configService.getValue('interactive.experimental.progressiveRenderingRate');
if (typeof configuredRate === 'number') {
return configuredRate;
}
if (element.isComplete) {
return 60;
}
if (element.contentUpdateTimings && element.contentUpdateTimings.impliedWordLoadRate) {
// This doesn't account for dead time after the last update. When the previous update is the final one and the model is only waiting for followupQuestions, that's good.
// When there was one quick update and then you are waiting longer for the next one, that's not good since the rate should be decreasing.
// If it's an issue, we can change this to be based on the total time from now to the beginning.
const rateBoost = 1.5;
return element.contentUpdateTimings.impliedWordLoadRate * rateBoost;
}
return 8;
}
layout(width: number): void {
this._currentLayoutWidth = width - 40; // TODO Padding
this._editorPool.inUse.forEach(editor => {
editor.layout(this._currentLayoutWidth);
});
}
renderTemplate(container: HTMLElement): IInteractiveListItemTemplate {
const templateDisposables = new DisposableStore();
const rowContainer = dom.append(container, $('.interactive-item-container'));
const header = dom.append(rowContainer, $('.header'));
const user = dom.append(header, $('.user'));
const avatar = dom.append(user, $('.avatar'));
const username = dom.append(user, $('h3.username'));
const value = dom.append(rowContainer, $('.value'));
const elementDisposables = new DisposableStore();
const contextKeyService = templateDisposables.add(this.contextKeyService.createScoped(rowContainer));
const scopedInstantiationService = this.instantiationService.createChild(new ServiceCollection([IContextKeyService, contextKeyService]));
const titleToolbar = templateDisposables.add(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, header, MenuId.InteractiveSessionTitle, {
menuOptions: {
shouldForwardArgs: true
}
}));
const template: IInteractiveListItemTemplate = { avatar, username, value, rowContainer, elementDisposables, titleToolbar, templateDisposables, contextKeyService };
return template;
}
renderElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void {
const { element } = node;
const kind = isRequestVM(element) ? 'request' :
isResponseVM(element) ? 'response' :
'welcome';
this.traceLayout('renderElement', `${kind}, index=${index}`);
CONTEXT_RESPONSE_HAS_PROVIDER_ID.bindTo(templateData.contextKeyService).set(isResponseVM(element) && !!element.providerResponseId && !element.isPlaceholder);
if (isResponseVM(element)) {
CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set(element.vote === InteractiveSessionVoteDirection.Up ? 'up' : element.vote === InteractiveSessionVoteDirection.Down ? 'down' : '');
} else {
CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set('');
}
templateData.titleToolbar.context = element;
templateData.rowContainer.classList.toggle('interactive-request', isRequestVM(element));
templateData.rowContainer.classList.toggle('interactive-response', isResponseVM(element));
templateData.rowContainer.classList.toggle('interactive-welcome', isWelcomeVM(element));
templateData.rowContainer.classList.toggle('filtered-response', !!(isResponseVM(element) && element.errorDetails?.responseIsFiltered));
templateData.username.textContent = element.username;
if (element.avatarIconUri) {
const avatarIcon = dom.$<HTMLImageElement>('img.icon');
avatarIcon.src = FileAccess.uriToBrowserUri(element.avatarIconUri).toString(true);
templateData.avatar.replaceChildren(avatarIcon);
} else {
const defaultIcon = isRequestVM(element) ? Codicon.account : Codicon.hubot;
const avatarIcon = dom.$(ThemeIcon.asCSSSelector(defaultIcon));
templateData.avatar.replaceChildren(avatarIcon);
}
// Do a progressive render if
// - This the last response in the list
// - And the response is not complete
// - Or, we previously started a progressive rendering of this element (if the element is complete, we will finish progressive rendering with a very fast rate)
// - And, the feature is not disabled in configuration
if (isResponseVM(element) && index === this.delegate.getListLength() - 1 && (!element.isComplete || element.renderData) && this.shouldRenderProgressively(element)) {
this.traceLayout('renderElement', `start progressive render ${kind}, index=${index}`);
const progressiveRenderingDisposables = templateData.elementDisposables.add(new DisposableStore());
const timer = templateData.elementDisposables.add(new IntervalTimer());
const runProgressiveRender = (initial?: boolean) => {
try {
if (this.doNextProgressiveRender(element, index, templateData, !!initial, progressiveRenderingDisposables)) {
timer.cancel();
}
} catch (err) {
// Kill the timer if anything went wrong, avoid getting stuck in a nasty rendering loop.
timer.cancel();
throw err;
}
};
runProgressiveRender(true);
timer.cancelAndSet(runProgressiveRender, 50);
} else if (isResponseVM(element)) {
this.basicRenderElement(element.response.value, element, index, templateData);
} else if (isRequestVM(element)) {
this.basicRenderElement(element.messageText, element, index, templateData);
} else {
this.renderWelcomeMessage(element, templateData);
}
}
private basicRenderElement(markdownValue: string, element: InteractiveTreeItem, index: number, templateData: IInteractiveListItemTemplate) {
const fillInIncompleteTokens = isResponseVM(element) && (!element.isComplete || element.isCanceled || element.errorDetails?.responseIsFiltered || element.errorDetails?.responseIsIncomplete);
const result = this.renderMarkdown(new MarkdownString(markdownValue), element, templateData.elementDisposables, templateData, fillInIncompleteTokens);
dom.clearNode(templateData.value);
templateData.value.appendChild(result.element);
templateData.elementDisposables.add(result);
if (isResponseVM(element) && element.errorDetails?.message) {
const errorDetails = dom.append(templateData.value, $('.interactive-response-error-details', undefined, renderIcon(Codicon.error)));
errorDetails.appendChild($('span', undefined, element.errorDetails.message));
}
if (isResponseVM(element) && element.commandFollowups?.length) {
const followupsContainer = dom.append(templateData.value, $('.interactive-response-followups'));
templateData.elementDisposables.add(new InteractiveSessionFollowups(
followupsContainer,
element.commandFollowups,
defaultButtonStyles,
followup => {
this.interactiveSessionService.notifyUserAction({
providerId: element.providerId,
action: {
kind: 'command',
command: followup
}
});
return this.commandService.executeCommand(followup.commandId, ...(followup.args ?? []));
}));
}
}
private renderWelcomeMessage(element: IInteractiveWelcomeMessageViewModel, templateData: IInteractiveListItemTemplate) {
dom.clearNode(templateData.value);
const slashCommands = this.delegate.getSlashCommands();
for (const item of element.content) {
if (Array.isArray(item)) {
templateData.elementDisposables.add(new InteractiveSessionFollowups(
templateData.value,
item,
undefined,
followup => this._onDidClickFollowup.fire(followup)));
} else {
const result = this.renderMarkdown(item as IMarkdownString, element, templateData.elementDisposables, templateData);
for (const codeElement of result.element.querySelectorAll('code')) {
if (codeElement.textContent && slashCommands.find(command => codeElement.textContent === `/${command.command}`)) {
codeElement.classList.add('interactive-slash-command');
}
}
templateData.value.appendChild(result.element);
templateData.elementDisposables.add(result);
}
}
}
private doNextProgressiveRender(element: IInteractiveResponseViewModel, index: number, templateData: IInteractiveListItemTemplate, isInRenderElement: boolean, disposables: DisposableStore): boolean {
disposables.clear();
let isFullyRendered = false;
if (element.isCanceled) {
this.traceLayout('runProgressiveRender', `canceled, index=${index}`);
element.renderData = undefined;
this.basicRenderElement(element.response.value, element, index, templateData);
isFullyRendered = true;
} else {
// TODO- this method has the side effect of updating element.renderData
const toRender = this.getProgressiveMarkdownToRender(element);
isFullyRendered = !!element.renderData?.isFullyRendered;
if (isFullyRendered) {
// We've reached the end of the available content, so do a normal render
this.traceLayout('runProgressiveRender', `end progressive render, index=${index}`);
if (element.isComplete) {
this.traceLayout('runProgressiveRender', `and disposing renderData, response is complete, index=${index}`);
element.renderData = undefined;
} else {
this.traceLayout('runProgressiveRender', `Rendered all available words, but model is not complete.`);
}
disposables.clear();
this.basicRenderElement(element.response.value, element, index, templateData);
} else if (toRender) {
// Doing the progressive render
const plusCursor = toRender.match(/```.*$/) ? toRender + `\n${InteractiveListItemRenderer.cursorCharacter}` : toRender + ` ${InteractiveListItemRenderer.cursorCharacter}`;
const result = this.renderMarkdown(new MarkdownString(plusCursor), element, disposables, templateData, true);
dom.clearNode(templateData.value);
templateData.value.appendChild(result.element);
disposables.add(result);
} else {
// Nothing new to render, not done, keep waiting
return false;
}
}
// Some render happened - update the height
const height = templateData.rowContainer.offsetHeight;
element.currentRenderedHeight = height;
if (!isInRenderElement) {
this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight });
}
return !!isFullyRendered;
}
private renderMarkdown(markdown: IMarkdownString, element: InteractiveTreeItem, disposables: DisposableStore, templateData: IInteractiveListItemTemplate, fillInIncompleteTokens = false): IMarkdownRenderResult {
const disposablesList: IDisposable[] = [];
let codeBlockIndex = 0;
// TODO if the slash commands stay completely dynamic, this isn't quite right
const slashCommands = this.delegate.getSlashCommands();
const usedSlashCommand = slashCommands.find(s => markdown.value.startsWith(`/${s.command} `));
const toRender = usedSlashCommand ? markdown.value.slice(usedSlashCommand.command.length + 2) : markdown.value;
markdown = new MarkdownString(toRender);
const result = this.renderer.render(markdown, {
fillInIncompleteTokens,
codeBlockRendererSync: (languageId, text) => {
const ref = this.renderCodeBlock({ languageId, text, codeBlockIndex: codeBlockIndex++, element, parentContextKeyService: templateData.contextKeyService }, disposables);
// Attach this after updating text/layout of the editor, so it should only be fired when the size updates later (horizontal scrollbar, wrapping)
// not during a renderElement OR a progressive render (when we will be firing this event anyway at the end of the render)
disposables.add(ref.object.onDidChangeContentHeight(() => {
ref.object.layout(this._currentLayoutWidth);
this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight });
}));
disposablesList.push(ref);
return ref.object.element;
}
});
if (usedSlashCommand) {
const slashCommandElement = $('span.interactive-slash-command', { title: usedSlashCommand.detail }, `/${usedSlashCommand.command} `);
if (result.element.firstChild?.nodeName.toLowerCase() === 'p') {
result.element.firstChild.insertBefore(slashCommandElement, result.element.firstChild.firstChild);
} else {
result.element.insertBefore($('p', undefined, slashCommandElement), result.element.firstChild);
}
}
disposablesList.reverse().forEach(d => disposables.add(d));
return result;
}
private renderCodeBlock(data: IInteractiveResultCodeBlockData, disposables: DisposableStore): IDisposableReference<IInteractiveResultCodeBlockPart> {
const ref = this._editorPool.get();
const editorInfo = ref.object;
editorInfo.render(data, this._currentLayoutWidth);
return ref;
}
private getProgressiveMarkdownToRender(element: IInteractiveResponseViewModel): string | undefined {
const renderData = element.renderData ?? { renderedWordCount: 0, lastRenderTime: 0 };
const rate = this.getProgressiveRenderRate(element);
const numWordsToRender = renderData.lastRenderTime === 0 ?
1 :
renderData.renderedWordCount +
// Additional words to render beyond what's already rendered
Math.floor((Date.now() - renderData.lastRenderTime) / 1000 * rate);
if (numWordsToRender === renderData.renderedWordCount) {
return undefined;
}
const result = getNWords(element.response.value, numWordsToRender);
element.renderData = {
renderedWordCount: result.actualWordCount,
lastRenderTime: Date.now(),
isFullyRendered: result.isFullString
};
return result.value;
}
disposeElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void {
templateData.elementDisposables.clear();
}
disposeTemplate(templateData: IInteractiveListItemTemplate): void {
templateData.templateDisposables.dispose();
}
}
export class InteractiveSessionListDelegate implements IListVirtualDelegate<InteractiveTreeItem> {
constructor(
@ILogService private readonly logService: ILogService
) { }
private _traceLayout(method: string, message: string) {
if (forceVerboseLayoutTracing) {
this.logService.info(`InteractiveSessionListDelegate#${method}: ${message}`);
} else {
this.logService.trace(`InteractiveSessionListDelegate#${method}: ${message}`);
}
}
getHeight(element: InteractiveTreeItem): number {
const kind = isRequestVM(element) ? 'request' : 'response';
const height = ('currentRenderedHeight' in element ? element.currentRenderedHeight : undefined) ?? 200;
this._traceLayout('getHeight', `${kind}, height=${height}`);
return height;
}
getTemplateId(element: InteractiveTreeItem): string {
return InteractiveListItemRenderer.ID;
}
hasDynamicHeight(element: InteractiveTreeItem): boolean {
return true;
}
}
export class InteractiveSessionAccessibilityProvider implements IListAccessibilityProvider<InteractiveTreeItem> {
getWidgetAriaLabel(): string {
return localize('interactiveSession', "Interactive Session");
}
getAriaLabel(element: InteractiveTreeItem): string {
if (isRequestVM(element)) {
return localize('interactiveRequest', "Request: {0}", element.messageText);
}
if (isResponseVM(element)) {
return localize('interactiveResponse', "Response: {0}", element.response.value);
}
return '';
}
}
interface IInteractiveResultCodeBlockData {
text: string;
languageId: string;
codeBlockIndex: number;
element: InteractiveTreeItem;
parentContextKeyService: IContextKeyService;
}
interface IInteractiveResultCodeBlockPart {
readonly onDidChangeContentHeight: Event<number>;
readonly element: HTMLElement;
readonly textModel: ITextModel;
layout(width: number): void;
render(data: IInteractiveResultCodeBlockData, width: number): void;
dispose(): void;
}
export interface IInteractiveResultCodeBlockInfo {
providerId: string;
responseId: string;
codeBlockIndex: number;
}
export const codeBlockInfosByModelUri = new ResourceMap<IInteractiveResultCodeBlockInfo>();
class CodeBlockPart extends Disposable implements IInteractiveResultCodeBlockPart {
private readonly _onDidChangeContentHeight = this._register(new Emitter<number>());
public readonly onDidChangeContentHeight = this._onDidChangeContentHeight.event;
private readonly editor: CodeEditorWidget;
private readonly toolbar: MenuWorkbenchToolBar;
private readonly contextKeyService: IContextKeyService;
public readonly textModel: ITextModel;
public readonly element: HTMLElement;
constructor(
private readonly options: InteractiveSessionEditorOptions,
@IInstantiationService instantiationService: IInstantiationService,
@IContextKeyService contextKeyService: IContextKeyService,
@ILanguageService private readonly languageService: ILanguageService,
@IModelService private readonly modelService: IModelService,
) {
super();
this.element = $('.interactive-result-editor-wrapper');
this.contextKeyService = this._register(contextKeyService.createScoped(this.element));
const scopedInstantiationService = instantiationService.createChild(new ServiceCollection([IContextKeyService, this.contextKeyService]));
this.toolbar = this._register(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, this.element, MenuId.InteractiveSessionCodeBlock, {
menuOptions: {
shouldForwardArgs: true
}
}));
const editorElement = dom.append(this.element, $('.interactive-result-editor'));
this.editor = this._register(scopedInstantiationService.createInstance(CodeEditorWidget, editorElement, {
...getSimpleEditorOptions(),
readOnly: true,
lineNumbers: 'off',
selectOnLineNumbers: true,
scrollBeyondLastLine: false,
lineDecorationsWidth: 8,
dragAndDrop: false,
padding: { top: 2, bottom: 2 },
mouseWheelZoom: false,
scrollbar: {
alwaysConsumeMouseWheel: false
},
...this.getEditorOptionsFromConfig()
}, {
isSimpleWidget: true,
contributions: EditorExtensionsRegistry.getSomeEditorContributions([
MenuPreventer.ID,
SelectionClipboardContributionID,
ContextMenuController.ID,
WordHighlighterContribution.ID,
ViewportSemanticTokensContribution.ID,
BracketMatchingController.ID,
SmartSelectController.ID,
])
}));
this._register(this.options.onDidChange(() => {
this.editor.updateOptions(this.getEditorOptionsFromConfig());
}));
this._register(this.editor.onDidContentSizeChange(e => {
if (e.contentHeightChanged) {
this._onDidChangeContentHeight.fire(e.contentHeight);
}
}));
this._register(this.editor.onDidBlurEditorWidget(() => {
WordHighlighterContribution.get(this.editor)?.stopHighlighting();
}));
this._register(this.editor.onDidFocusEditorWidget(() => {
WordHighlighterContribution.get(this.editor)?.restoreViewState(true);
}));
const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName('javascript');
this.textModel = this._register(this.modelService.createModel('', this.languageService.createById(vscodeLanguageId), undefined));
this.editor.setModel(this.textModel);
}
private getEditorOptionsFromConfig(): IEditorOptions {
return {
wordWrap: this.options.configuration.resultEditor.wordWrap,
fontLigatures: this.options.configuration.resultEditor.fontLigatures,
bracketPairColorization: this.options.configuration.resultEditor.bracketPairColorization,
fontFamily: this.options.configuration.resultEditor.fontFamily === 'default' ?
EDITOR_FONT_DEFAULTS.fontFamily :
this.options.configuration.resultEditor.fontFamily,
fontSize: this.options.configuration.resultEditor.fontSize,
fontWeight: this.options.configuration.resultEditor.fontWeight,
lineHeight: this.options.configuration.resultEditor.lineHeight,
};
}
layout(width: number): void {
const realContentHeight = this.editor.getContentHeight();
const editorBorder = 2;
this.editor.layout({ width: width - editorBorder, height: realContentHeight });
}
render(data: IInteractiveResultCodeBlockData, width: number): void {
this.contextKeyService.updateParent(data.parentContextKeyService);
if (this.options.configuration.resultEditor.wordWrap === 'on') {
// Intialize the editor with the new proper width so that getContentHeight
// will be computed correctly in the next call to layout()
this.layout(width);
}
this.setText(data.text);
this.setLanguage(data.languageId);
this.layout(width);
if (isResponseVM(data.element) && data.element.providerResponseId) {
// For telemetry reporting
codeBlockInfosByModelUri.set(this.textModel.uri, {
providerId: data.element.providerId,
responseId: data.element.providerResponseId,
codeBlockIndex: data.codeBlockIndex
});
} else {
codeBlockInfosByModelUri.delete(this.textModel.uri);
}
this.toolbar.context = <IInteractiveSessionCodeBlockActionContext>{
code: data.text,
codeBlockIndex: data.codeBlockIndex,
element: data.element
};
}
private setText(newText: string): void {
let currentText = this.textModel.getLinesContent().join('\n');
if (newText === currentText) {
return;
}
let removedChars = 0;
if (currentText.endsWith(` ${InteractiveListItemRenderer.cursorCharacter}`)) {
removedChars = 2;
} else if (currentText.endsWith(InteractiveListItemRenderer.cursorCharacter)) {
removedChars = 1;
}
if (removedChars > 0) {
currentText = currentText.slice(0, currentText.length - removedChars);
}
if (newText.startsWith(currentText)) {
const text = newText.slice(currentText.length);
const lastLine = this.textModel.getLineCount();
const lastCol = this.textModel.getLineMaxColumn(lastLine);
const insertAtCol = lastCol - removedChars;
this.textModel.applyEdits([{ range: new Range(lastLine, insertAtCol, lastLine, lastCol), text }]);
} else {
// console.log(`Failed to optimize setText`);
this.textModel.setValue(newText);
}
}
private setLanguage(languageId: string): void {
const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName(languageId);
if (vscodeLanguageId) {
this.textModel.setLanguage(vscodeLanguageId);
}
}
}
interface IDisposableReference<T> extends IDisposable {
object: T;
}
class EditorPool extends Disposable {
private _pool: ResourcePool<IInteractiveResultCodeBlockPart>;
public get inUse(): ReadonlySet<IInteractiveResultCodeBlockPart> {
return this._pool.inUse;
}
constructor(
private readonly options: InteractiveSessionEditorOptions,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
this._pool = this._register(new ResourcePool(() => this.editorFactory()));
// TODO listen to changes on options
}
private editorFactory(): IInteractiveResultCodeBlockPart {
return this.instantiationService.createInstance(CodeBlockPart, this.options);
}
get(): IDisposableReference<IInteractiveResultCodeBlockPart> {
const object = this._pool.get();
return {
object,
dispose: () => this._pool.release(object)
};
}
}
// TODO does something in lifecycle.ts cover this?
class ResourcePool<T extends IDisposable> extends Disposable {
private readonly pool: T[] = [];
private _inUse = new Set<T>;
public get inUse(): ReadonlySet<T> {
return this._inUse;
}
constructor(
private readonly _itemFactory: () => T,
) {
super();
}
get(): T {
if (this.pool.length > 0) {
const item = this.pool.pop()!;
this._inUse.add(item);
return item;
}
const item = this._register(this._itemFactory());
this._inUse.add(item);
return item;
}
release(item: T): void {
this._inUse.delete(item);
this.pool.push(item);
}
}
| src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts | 1 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.333566814661026,
0.0050612254999578,
0.0001637283421587199,
0.00017176840628962964,
0.03851606324315071
] |
{
"id": 1,
"code_window": [
"import { INTERACTIVE_SESSION_CATEGORY } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionActions';\n",
"import { CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys';\n",
"import { IInteractiveSessionService, IInteractiveSessionUserActionEvent, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n",
"import { isResponseVM } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel';\n",
"\n",
"export function registerInteractiveSessionTitleActions() {\n",
"\tregisterAction2(class VoteUpAction extends Action2 {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys';\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts",
"type": "replace",
"edit_start_line_idx": 11
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { CancellationToken } from 'vs/base/common/cancellation';
import { basename } from 'vs/base/common/path';
import { URI, UriComponents } from 'vs/base/common/uri';
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
import { ILogService, NullLogService } from 'vs/platform/log/common/log';
import { IWorkspaceFolderData } from 'vs/platform/workspace/common/workspace';
import { MainThreadWorkspace } from 'vs/workbench/api/browser/mainThreadWorkspace';
import { IMainContext, IWorkspaceData, MainContext, ITextSearchComplete } from 'vs/workbench/api/common/extHost.protocol';
import { RelativePattern } from 'vs/workbench/api/common/extHostTypes';
import { ExtHostWorkspace } from 'vs/workbench/api/common/extHostWorkspace';
import { mock } from 'vs/base/test/common/mock';
import { TestRPCProtocol } from 'vs/workbench/api/test/common/testRPCProtocol';
import { ExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
import { IExtHostInitDataService } from 'vs/workbench/api/common/extHostInitDataService';
import { ITextQueryBuilderOptions } from 'vs/workbench/services/search/common/queryBuilder';
import { IPatternInfo } from 'vs/workbench/services/search/common/search';
import { isLinux, isWindows } from 'vs/base/common/platform';
import { IExtHostFileSystemInfo } from 'vs/workbench/api/common/extHostFileSystemInfo';
import { FileSystemProviderCapabilities } from 'vs/platform/files/common/files';
import { nullExtensionDescription as extensionDescriptor } from 'vs/workbench/services/extensions/common/extensions';
import { IURITransformerService } from 'vs/workbench/api/common/extHostUriTransformerService';
function createExtHostWorkspace(mainContext: IMainContext, data: IWorkspaceData, logService: ILogService): ExtHostWorkspace {
const result = new ExtHostWorkspace(
new ExtHostRpcService(mainContext),
new class extends mock<IExtHostInitDataService>() { override workspace = data; },
new class extends mock<IExtHostFileSystemInfo>() { override getCapabilities() { return isLinux ? FileSystemProviderCapabilities.PathCaseSensitive : undefined; } },
logService,
new class extends mock<IURITransformerService>() { }
);
result.$initializeWorkspace(data, true);
return result;
}
suite('ExtHostWorkspace', function () {
function assertAsRelativePath(workspace: ExtHostWorkspace, input: string, expected: string, includeWorkspace?: boolean) {
const actual = workspace.getRelativePath(input, includeWorkspace);
assert.strictEqual(actual, expected);
}
test('asRelativePath', () => {
const ws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', folders: [aWorkspaceFolderData(URI.file('/Coding/Applications/NewsWoWBot'), 0)], name: 'Test' }, new NullLogService());
assertAsRelativePath(ws, '/Coding/Applications/NewsWoWBot/bernd/das/brot', 'bernd/das/brot');
assertAsRelativePath(ws, '/Apps/DartPubCache/hosted/pub.dartlang.org/convert-2.0.1/lib/src/hex.dart',
'/Apps/DartPubCache/hosted/pub.dartlang.org/convert-2.0.1/lib/src/hex.dart');
assertAsRelativePath(ws, '', '');
assertAsRelativePath(ws, '/foo/bar', '/foo/bar');
assertAsRelativePath(ws, 'in/out', 'in/out');
});
test('asRelativePath, same paths, #11402', function () {
const root = '/home/aeschli/workspaces/samples/docker';
const input = '/home/aeschli/workspaces/samples/docker';
const ws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', folders: [aWorkspaceFolderData(URI.file(root), 0)], name: 'Test' }, new NullLogService());
assertAsRelativePath(ws, input, input);
const input2 = '/home/aeschli/workspaces/samples/docker/a.file';
assertAsRelativePath(ws, input2, 'a.file');
});
test('asRelativePath, no workspace', function () {
const ws = createExtHostWorkspace(new TestRPCProtocol(), null!, new NullLogService());
assertAsRelativePath(ws, '', '');
assertAsRelativePath(ws, '/foo/bar', '/foo/bar');
});
test('asRelativePath, multiple folders', function () {
const ws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', folders: [aWorkspaceFolderData(URI.file('/Coding/One'), 0), aWorkspaceFolderData(URI.file('/Coding/Two'), 1)], name: 'Test' }, new NullLogService());
assertAsRelativePath(ws, '/Coding/One/file.txt', 'One/file.txt');
assertAsRelativePath(ws, '/Coding/Two/files/out.txt', 'Two/files/out.txt');
assertAsRelativePath(ws, '/Coding/Two2/files/out.txt', '/Coding/Two2/files/out.txt');
});
test('slightly inconsistent behaviour of asRelativePath and getWorkspaceFolder, #31553', function () {
const mrws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', folders: [aWorkspaceFolderData(URI.file('/Coding/One'), 0), aWorkspaceFolderData(URI.file('/Coding/Two'), 1)], name: 'Test' }, new NullLogService());
assertAsRelativePath(mrws, '/Coding/One/file.txt', 'One/file.txt');
assertAsRelativePath(mrws, '/Coding/One/file.txt', 'One/file.txt', true);
assertAsRelativePath(mrws, '/Coding/One/file.txt', 'file.txt', false);
assertAsRelativePath(mrws, '/Coding/Two/files/out.txt', 'Two/files/out.txt');
assertAsRelativePath(mrws, '/Coding/Two/files/out.txt', 'Two/files/out.txt', true);
assertAsRelativePath(mrws, '/Coding/Two/files/out.txt', 'files/out.txt', false);
assertAsRelativePath(mrws, '/Coding/Two2/files/out.txt', '/Coding/Two2/files/out.txt');
assertAsRelativePath(mrws, '/Coding/Two2/files/out.txt', '/Coding/Two2/files/out.txt', true);
assertAsRelativePath(mrws, '/Coding/Two2/files/out.txt', '/Coding/Two2/files/out.txt', false);
const srws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', folders: [aWorkspaceFolderData(URI.file('/Coding/One'), 0)], name: 'Test' }, new NullLogService());
assertAsRelativePath(srws, '/Coding/One/file.txt', 'file.txt');
assertAsRelativePath(srws, '/Coding/One/file.txt', 'file.txt', false);
assertAsRelativePath(srws, '/Coding/One/file.txt', 'One/file.txt', true);
assertAsRelativePath(srws, '/Coding/Two2/files/out.txt', '/Coding/Two2/files/out.txt');
assertAsRelativePath(srws, '/Coding/Two2/files/out.txt', '/Coding/Two2/files/out.txt', true);
assertAsRelativePath(srws, '/Coding/Two2/files/out.txt', '/Coding/Two2/files/out.txt', false);
});
test('getPath, legacy', function () {
let ws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', name: 'Test', folders: [] }, new NullLogService());
assert.strictEqual(ws.getPath(), undefined);
ws = createExtHostWorkspace(new TestRPCProtocol(), null!, new NullLogService());
assert.strictEqual(ws.getPath(), undefined);
ws = createExtHostWorkspace(new TestRPCProtocol(), undefined!, new NullLogService());
assert.strictEqual(ws.getPath(), undefined);
ws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.file('Folder'), 0), aWorkspaceFolderData(URI.file('Another/Folder'), 1)] }, new NullLogService());
assert.strictEqual(ws.getPath()!.replace(/\\/g, '/'), '/Folder');
ws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.file('/Folder'), 0)] }, new NullLogService());
assert.strictEqual(ws.getPath()!.replace(/\\/g, '/'), '/Folder');
});
test('WorkspaceFolder has name and index', function () {
const ws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', folders: [aWorkspaceFolderData(URI.file('/Coding/One'), 0), aWorkspaceFolderData(URI.file('/Coding/Two'), 1)], name: 'Test' }, new NullLogService());
const [one, two] = ws.getWorkspaceFolders()!;
assert.strictEqual(one.name, 'One');
assert.strictEqual(one.index, 0);
assert.strictEqual(two.name, 'Two');
assert.strictEqual(two.index, 1);
});
test('getContainingWorkspaceFolder', () => {
const ws = createExtHostWorkspace(new TestRPCProtocol(), {
id: 'foo',
name: 'Test',
folders: [
aWorkspaceFolderData(URI.file('/Coding/One'), 0),
aWorkspaceFolderData(URI.file('/Coding/Two'), 1),
aWorkspaceFolderData(URI.file('/Coding/Two/Nested'), 2)
]
}, new NullLogService());
let folder = ws.getWorkspaceFolder(URI.file('/foo/bar'));
assert.strictEqual(folder, undefined);
folder = ws.getWorkspaceFolder(URI.file('/Coding/One/file/path.txt'))!;
assert.strictEqual(folder.name, 'One');
folder = ws.getWorkspaceFolder(URI.file('/Coding/Two/file/path.txt'))!;
assert.strictEqual(folder.name, 'Two');
folder = ws.getWorkspaceFolder(URI.file('/Coding/Two/Nest'))!;
assert.strictEqual(folder.name, 'Two');
folder = ws.getWorkspaceFolder(URI.file('/Coding/Two/Nested/file'))!;
assert.strictEqual(folder.name, 'Nested');
folder = ws.getWorkspaceFolder(URI.file('/Coding/Two/Nested/f'))!;
assert.strictEqual(folder.name, 'Nested');
folder = ws.getWorkspaceFolder(URI.file('/Coding/Two/Nested'), true)!;
assert.strictEqual(folder.name, 'Two');
folder = ws.getWorkspaceFolder(URI.file('/Coding/Two/Nested/'), true)!;
assert.strictEqual(folder.name, 'Two');
folder = ws.getWorkspaceFolder(URI.file('/Coding/Two/Nested'))!;
assert.strictEqual(folder.name, 'Nested');
folder = ws.getWorkspaceFolder(URI.file('/Coding/Two/Nested/'))!;
assert.strictEqual(folder.name, 'Nested');
folder = ws.getWorkspaceFolder(URI.file('/Coding/Two'), true)!;
assert.strictEqual(folder, undefined);
folder = ws.getWorkspaceFolder(URI.file('/Coding/Two'), false)!;
assert.strictEqual(folder.name, 'Two');
});
test('Multiroot change event should have a delta, #29641', function (done) {
const ws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', name: 'Test', folders: [] }, new NullLogService());
let finished = false;
const finish = (error?: any) => {
if (!finished) {
finished = true;
done(error);
}
};
let sub = ws.onDidChangeWorkspace(e => {
try {
assert.deepStrictEqual(e.added, []);
assert.deepStrictEqual(e.removed, []);
} catch (error) {
finish(error);
}
});
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [] });
sub.dispose();
sub = ws.onDidChangeWorkspace(e => {
try {
assert.deepStrictEqual(e.removed, []);
assert.strictEqual(e.added.length, 1);
assert.strictEqual(e.added[0].uri.toString(), 'foo:bar');
} catch (error) {
finish(error);
}
});
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar'), 0)] });
sub.dispose();
sub = ws.onDidChangeWorkspace(e => {
try {
assert.deepStrictEqual(e.removed, []);
assert.strictEqual(e.added.length, 1);
assert.strictEqual(e.added[0].uri.toString(), 'foo:bar2');
} catch (error) {
finish(error);
}
});
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar'), 0), aWorkspaceFolderData(URI.parse('foo:bar2'), 1)] });
sub.dispose();
sub = ws.onDidChangeWorkspace(e => {
try {
assert.strictEqual(e.removed.length, 2);
assert.strictEqual(e.removed[0].uri.toString(), 'foo:bar');
assert.strictEqual(e.removed[1].uri.toString(), 'foo:bar2');
assert.strictEqual(e.added.length, 1);
assert.strictEqual(e.added[0].uri.toString(), 'foo:bar3');
} catch (error) {
finish(error);
}
});
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar3'), 0)] });
sub.dispose();
finish();
});
test('Multiroot change keeps existing workspaces live', function () {
const ws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar'), 0)] }, new NullLogService());
const firstFolder = ws.getWorkspaceFolders()![0];
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar2'), 0), aWorkspaceFolderData(URI.parse('foo:bar'), 1, 'renamed')] });
assert.strictEqual(ws.getWorkspaceFolders()![1], firstFolder);
assert.strictEqual(firstFolder.index, 1);
assert.strictEqual(firstFolder.name, 'renamed');
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar3'), 0), aWorkspaceFolderData(URI.parse('foo:bar2'), 1), aWorkspaceFolderData(URI.parse('foo:bar'), 2)] });
assert.strictEqual(ws.getWorkspaceFolders()![2], firstFolder);
assert.strictEqual(firstFolder.index, 2);
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar3'), 0)] });
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar3'), 0), aWorkspaceFolderData(URI.parse('foo:bar'), 1)] });
assert.notStrictEqual(firstFolder, ws.workspace!.folders[0]);
});
test('updateWorkspaceFolders - invalid arguments', function () {
let ws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', name: 'Test', folders: [] }, new NullLogService());
assert.strictEqual(false, ws.updateWorkspaceFolders(extensionDescriptor, null!, null!));
assert.strictEqual(false, ws.updateWorkspaceFolders(extensionDescriptor, 0, 0));
assert.strictEqual(false, ws.updateWorkspaceFolders(extensionDescriptor, 0, 1));
assert.strictEqual(false, ws.updateWorkspaceFolders(extensionDescriptor, 1, 0));
assert.strictEqual(false, ws.updateWorkspaceFolders(extensionDescriptor, -1, 0));
assert.strictEqual(false, ws.updateWorkspaceFolders(extensionDescriptor, -1, -1));
ws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar'), 0)] }, new NullLogService());
assert.strictEqual(false, ws.updateWorkspaceFolders(extensionDescriptor, 1, 1));
assert.strictEqual(false, ws.updateWorkspaceFolders(extensionDescriptor, 0, 2));
assert.strictEqual(false, ws.updateWorkspaceFolders(extensionDescriptor, 0, 1, asUpdateWorkspaceFolderData(URI.parse('foo:bar'))));
});
test('updateWorkspaceFolders - valid arguments', function (done) {
let finished = false;
const finish = (error?: any) => {
if (!finished) {
finished = true;
done(error);
}
};
const protocol: IMainContext = {
getProxy: () => { return undefined!; },
set: () => { return undefined!; },
dispose: () => { },
assertRegistered: () => { },
drain: () => { return undefined!; },
};
const ws = createExtHostWorkspace(protocol, { id: 'foo', name: 'Test', folders: [] }, new NullLogService());
//
// Add one folder
//
assert.strictEqual(true, ws.updateWorkspaceFolders(extensionDescriptor, 0, 0, asUpdateWorkspaceFolderData(URI.parse('foo:bar'))));
assert.strictEqual(1, ws.workspace!.folders.length);
assert.strictEqual(ws.workspace!.folders[0].uri.toString(), URI.parse('foo:bar').toString());
const firstAddedFolder = ws.getWorkspaceFolders()![0];
let gotEvent = false;
let sub = ws.onDidChangeWorkspace(e => {
try {
assert.deepStrictEqual(e.removed, []);
assert.strictEqual(e.added.length, 1);
assert.strictEqual(e.added[0].uri.toString(), 'foo:bar');
assert.strictEqual(e.added[0], firstAddedFolder); // verify object is still live
gotEvent = true;
} catch (error) {
finish(error);
}
});
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar'), 0)] }); // simulate acknowledgement from main side
assert.strictEqual(gotEvent, true);
sub.dispose();
assert.strictEqual(ws.getWorkspaceFolders()![0], firstAddedFolder); // verify object is still live
//
// Add two more folders
//
assert.strictEqual(true, ws.updateWorkspaceFolders(extensionDescriptor, 1, 0, asUpdateWorkspaceFolderData(URI.parse('foo:bar1')), asUpdateWorkspaceFolderData(URI.parse('foo:bar2'))));
assert.strictEqual(3, ws.workspace!.folders.length);
assert.strictEqual(ws.workspace!.folders[0].uri.toString(), URI.parse('foo:bar').toString());
assert.strictEqual(ws.workspace!.folders[1].uri.toString(), URI.parse('foo:bar1').toString());
assert.strictEqual(ws.workspace!.folders[2].uri.toString(), URI.parse('foo:bar2').toString());
const secondAddedFolder = ws.getWorkspaceFolders()![1];
const thirdAddedFolder = ws.getWorkspaceFolders()![2];
gotEvent = false;
sub = ws.onDidChangeWorkspace(e => {
try {
assert.deepStrictEqual(e.removed, []);
assert.strictEqual(e.added.length, 2);
assert.strictEqual(e.added[0].uri.toString(), 'foo:bar1');
assert.strictEqual(e.added[1].uri.toString(), 'foo:bar2');
assert.strictEqual(e.added[0], secondAddedFolder);
assert.strictEqual(e.added[1], thirdAddedFolder);
gotEvent = true;
} catch (error) {
finish(error);
}
});
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar'), 0), aWorkspaceFolderData(URI.parse('foo:bar1'), 1), aWorkspaceFolderData(URI.parse('foo:bar2'), 2)] }); // simulate acknowledgement from main side
assert.strictEqual(gotEvent, true);
sub.dispose();
assert.strictEqual(ws.getWorkspaceFolders()![0], firstAddedFolder); // verify object is still live
assert.strictEqual(ws.getWorkspaceFolders()![1], secondAddedFolder); // verify object is still live
assert.strictEqual(ws.getWorkspaceFolders()![2], thirdAddedFolder); // verify object is still live
//
// Remove one folder
//
assert.strictEqual(true, ws.updateWorkspaceFolders(extensionDescriptor, 2, 1));
assert.strictEqual(2, ws.workspace!.folders.length);
assert.strictEqual(ws.workspace!.folders[0].uri.toString(), URI.parse('foo:bar').toString());
assert.strictEqual(ws.workspace!.folders[1].uri.toString(), URI.parse('foo:bar1').toString());
gotEvent = false;
sub = ws.onDidChangeWorkspace(e => {
try {
assert.deepStrictEqual(e.added, []);
assert.strictEqual(e.removed.length, 1);
assert.strictEqual(e.removed[0], thirdAddedFolder);
gotEvent = true;
} catch (error) {
finish(error);
}
});
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar'), 0), aWorkspaceFolderData(URI.parse('foo:bar1'), 1)] }); // simulate acknowledgement from main side
assert.strictEqual(gotEvent, true);
sub.dispose();
assert.strictEqual(ws.getWorkspaceFolders()![0], firstAddedFolder); // verify object is still live
assert.strictEqual(ws.getWorkspaceFolders()![1], secondAddedFolder); // verify object is still live
//
// Rename folder
//
assert.strictEqual(true, ws.updateWorkspaceFolders(extensionDescriptor, 0, 2, asUpdateWorkspaceFolderData(URI.parse('foo:bar'), 'renamed 1'), asUpdateWorkspaceFolderData(URI.parse('foo:bar1'), 'renamed 2')));
assert.strictEqual(2, ws.workspace!.folders.length);
assert.strictEqual(ws.workspace!.folders[0].uri.toString(), URI.parse('foo:bar').toString());
assert.strictEqual(ws.workspace!.folders[1].uri.toString(), URI.parse('foo:bar1').toString());
assert.strictEqual(ws.workspace!.folders[0].name, 'renamed 1');
assert.strictEqual(ws.workspace!.folders[1].name, 'renamed 2');
assert.strictEqual(ws.getWorkspaceFolders()![0].name, 'renamed 1');
assert.strictEqual(ws.getWorkspaceFolders()![1].name, 'renamed 2');
gotEvent = false;
sub = ws.onDidChangeWorkspace(e => {
try {
assert.deepStrictEqual(e.added, []);
assert.strictEqual(e.removed.length, 0);
gotEvent = true;
} catch (error) {
finish(error);
}
});
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar'), 0, 'renamed 1'), aWorkspaceFolderData(URI.parse('foo:bar1'), 1, 'renamed 2')] }); // simulate acknowledgement from main side
assert.strictEqual(gotEvent, true);
sub.dispose();
assert.strictEqual(ws.getWorkspaceFolders()![0], firstAddedFolder); // verify object is still live
assert.strictEqual(ws.getWorkspaceFolders()![1], secondAddedFolder); // verify object is still live
assert.strictEqual(ws.workspace!.folders[0].name, 'renamed 1');
assert.strictEqual(ws.workspace!.folders[1].name, 'renamed 2');
assert.strictEqual(ws.getWorkspaceFolders()![0].name, 'renamed 1');
assert.strictEqual(ws.getWorkspaceFolders()![1].name, 'renamed 2');
//
// Add and remove folders
//
assert.strictEqual(true, ws.updateWorkspaceFolders(extensionDescriptor, 0, 2, asUpdateWorkspaceFolderData(URI.parse('foo:bar3')), asUpdateWorkspaceFolderData(URI.parse('foo:bar4'))));
assert.strictEqual(2, ws.workspace!.folders.length);
assert.strictEqual(ws.workspace!.folders[0].uri.toString(), URI.parse('foo:bar3').toString());
assert.strictEqual(ws.workspace!.folders[1].uri.toString(), URI.parse('foo:bar4').toString());
const fourthAddedFolder = ws.getWorkspaceFolders()![0];
const fifthAddedFolder = ws.getWorkspaceFolders()![1];
gotEvent = false;
sub = ws.onDidChangeWorkspace(e => {
try {
assert.strictEqual(e.added.length, 2);
assert.strictEqual(e.added[0], fourthAddedFolder);
assert.strictEqual(e.added[1], fifthAddedFolder);
assert.strictEqual(e.removed.length, 2);
assert.strictEqual(e.removed[0], firstAddedFolder);
assert.strictEqual(e.removed[1], secondAddedFolder);
gotEvent = true;
} catch (error) {
finish(error);
}
});
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar3'), 0), aWorkspaceFolderData(URI.parse('foo:bar4'), 1)] }); // simulate acknowledgement from main side
assert.strictEqual(gotEvent, true);
sub.dispose();
assert.strictEqual(ws.getWorkspaceFolders()![0], fourthAddedFolder); // verify object is still live
assert.strictEqual(ws.getWorkspaceFolders()![1], fifthAddedFolder); // verify object is still live
//
// Swap folders
//
assert.strictEqual(true, ws.updateWorkspaceFolders(extensionDescriptor, 0, 2, asUpdateWorkspaceFolderData(URI.parse('foo:bar4')), asUpdateWorkspaceFolderData(URI.parse('foo:bar3'))));
assert.strictEqual(2, ws.workspace!.folders.length);
assert.strictEqual(ws.workspace!.folders[0].uri.toString(), URI.parse('foo:bar4').toString());
assert.strictEqual(ws.workspace!.folders[1].uri.toString(), URI.parse('foo:bar3').toString());
assert.strictEqual(ws.getWorkspaceFolders()![0], fifthAddedFolder); // verify object is still live
assert.strictEqual(ws.getWorkspaceFolders()![1], fourthAddedFolder); // verify object is still live
gotEvent = false;
sub = ws.onDidChangeWorkspace(e => {
try {
assert.strictEqual(e.added.length, 0);
assert.strictEqual(e.removed.length, 0);
gotEvent = true;
} catch (error) {
finish(error);
}
});
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [aWorkspaceFolderData(URI.parse('foo:bar4'), 0), aWorkspaceFolderData(URI.parse('foo:bar3'), 1)] }); // simulate acknowledgement from main side
assert.strictEqual(gotEvent, true);
sub.dispose();
assert.strictEqual(ws.getWorkspaceFolders()![0], fifthAddedFolder); // verify object is still live
assert.strictEqual(ws.getWorkspaceFolders()![1], fourthAddedFolder); // verify object is still live
assert.strictEqual(fifthAddedFolder.index, 0);
assert.strictEqual(fourthAddedFolder.index, 1);
//
// Add one folder after the other without waiting for confirmation (not supported currently)
//
assert.strictEqual(true, ws.updateWorkspaceFolders(extensionDescriptor, 2, 0, asUpdateWorkspaceFolderData(URI.parse('foo:bar5'))));
assert.strictEqual(3, ws.workspace!.folders.length);
assert.strictEqual(ws.workspace!.folders[0].uri.toString(), URI.parse('foo:bar4').toString());
assert.strictEqual(ws.workspace!.folders[1].uri.toString(), URI.parse('foo:bar3').toString());
assert.strictEqual(ws.workspace!.folders[2].uri.toString(), URI.parse('foo:bar5').toString());
const sixthAddedFolder = ws.getWorkspaceFolders()![2];
gotEvent = false;
sub = ws.onDidChangeWorkspace(e => {
try {
assert.strictEqual(e.added.length, 1);
assert.strictEqual(e.added[0], sixthAddedFolder);
gotEvent = true;
} catch (error) {
finish(error);
}
});
ws.$acceptWorkspaceData({
id: 'foo', name: 'Test', folders: [
aWorkspaceFolderData(URI.parse('foo:bar4'), 0),
aWorkspaceFolderData(URI.parse('foo:bar3'), 1),
aWorkspaceFolderData(URI.parse('foo:bar5'), 2)
]
}); // simulate acknowledgement from main side
assert.strictEqual(gotEvent, true);
sub.dispose();
assert.strictEqual(ws.getWorkspaceFolders()![0], fifthAddedFolder); // verify object is still live
assert.strictEqual(ws.getWorkspaceFolders()![1], fourthAddedFolder); // verify object is still live
assert.strictEqual(ws.getWorkspaceFolders()![2], sixthAddedFolder); // verify object is still live
finish();
});
test('Multiroot change event is immutable', function (done) {
let finished = false;
const finish = (error?: any) => {
if (!finished) {
finished = true;
done(error);
}
};
const ws = createExtHostWorkspace(new TestRPCProtocol(), { id: 'foo', name: 'Test', folders: [] }, new NullLogService());
const sub = ws.onDidChangeWorkspace(e => {
try {
assert.throws(() => {
(<any>e).added = [];
});
// assert.throws(() => {
// (<any>e.added)[0] = null;
// });
} catch (error) {
finish(error);
}
});
ws.$acceptWorkspaceData({ id: 'foo', name: 'Test', folders: [] });
sub.dispose();
finish();
});
test('`vscode.workspace.getWorkspaceFolder(file)` don\'t return workspace folder when file open from command line. #36221', function () {
if (isWindows) {
const ws = createExtHostWorkspace(new TestRPCProtocol(), {
id: 'foo', name: 'Test', folders: [
aWorkspaceFolderData(URI.file('c:/Users/marek/Desktop/vsc_test/'), 0)
]
}, new NullLogService());
assert.ok(ws.getWorkspaceFolder(URI.file('c:/Users/marek/Desktop/vsc_test/a.txt')));
assert.ok(ws.getWorkspaceFolder(URI.file('C:/Users/marek/Desktop/vsc_test/b.txt')));
}
});
function aWorkspaceFolderData(uri: URI, index: number, name: string = ''): IWorkspaceFolderData {
return {
uri,
index,
name: name || basename(uri.path)
};
}
function asUpdateWorkspaceFolderData(uri: URI, name?: string): { uri: URI; name?: string } {
return { uri, name };
}
test('findFiles - string include', () => {
const root = '/project/foo';
const rpcProtocol = new TestRPCProtocol();
let mainThreadCalled = false;
rpcProtocol.set(MainContext.MainThreadWorkspace, new class extends mock<MainThreadWorkspace>() {
override $startFileSearch(includePattern: string, _includeFolder: UriComponents | null, excludePatternOrDisregardExcludes: string | false, maxResults: number, token: CancellationToken): Promise<URI[] | null> {
mainThreadCalled = true;
assert.strictEqual(includePattern, 'foo');
assert.strictEqual(_includeFolder, null);
assert.strictEqual(excludePatternOrDisregardExcludes, null);
assert.strictEqual(maxResults, 10);
return Promise.resolve(null);
}
});
const ws = createExtHostWorkspace(rpcProtocol, { id: 'foo', folders: [aWorkspaceFolderData(URI.file(root), 0)], name: 'Test' }, new NullLogService());
return ws.findFiles('foo', undefined, 10, new ExtensionIdentifier('test')).then(() => {
assert(mainThreadCalled, 'mainThreadCalled');
});
});
function testFindFilesInclude(pattern: RelativePattern) {
const root = '/project/foo';
const rpcProtocol = new TestRPCProtocol();
let mainThreadCalled = false;
rpcProtocol.set(MainContext.MainThreadWorkspace, new class extends mock<MainThreadWorkspace>() {
override $startFileSearch(includePattern: string, _includeFolder: UriComponents | null, excludePatternOrDisregardExcludes: string | false, maxResults: number, token: CancellationToken): Promise<URI[] | null> {
mainThreadCalled = true;
assert.strictEqual(includePattern, 'glob/**');
assert.deepStrictEqual(_includeFolder ? URI.from(_includeFolder).toJSON() : null, URI.file('/other/folder').toJSON());
assert.strictEqual(excludePatternOrDisregardExcludes, null);
return Promise.resolve(null);
}
});
const ws = createExtHostWorkspace(rpcProtocol, { id: 'foo', folders: [aWorkspaceFolderData(URI.file(root), 0)], name: 'Test' }, new NullLogService());
return ws.findFiles(pattern, undefined, 10, new ExtensionIdentifier('test')).then(() => {
assert(mainThreadCalled, 'mainThreadCalled');
});
}
test('findFiles - RelativePattern include (string)', () => {
return testFindFilesInclude(new RelativePattern('/other/folder', 'glob/**'));
});
test('findFiles - RelativePattern include (URI)', () => {
return testFindFilesInclude(new RelativePattern(URI.file('/other/folder'), 'glob/**'));
});
test('findFiles - no excludes', () => {
const root = '/project/foo';
const rpcProtocol = new TestRPCProtocol();
let mainThreadCalled = false;
rpcProtocol.set(MainContext.MainThreadWorkspace, new class extends mock<MainThreadWorkspace>() {
override $startFileSearch(includePattern: string, _includeFolder: UriComponents | null, excludePatternOrDisregardExcludes: string | false, maxResults: number, token: CancellationToken): Promise<URI[] | null> {
mainThreadCalled = true;
assert.strictEqual(includePattern, 'glob/**');
assert.deepStrictEqual(URI.revive(_includeFolder!).toString(), URI.file('/other/folder').toString());
assert.strictEqual(excludePatternOrDisregardExcludes, false);
return Promise.resolve(null);
}
});
const ws = createExtHostWorkspace(rpcProtocol, { id: 'foo', folders: [aWorkspaceFolderData(URI.file(root), 0)], name: 'Test' }, new NullLogService());
return ws.findFiles(new RelativePattern('/other/folder', 'glob/**'), null!, 10, new ExtensionIdentifier('test')).then(() => {
assert(mainThreadCalled, 'mainThreadCalled');
});
});
test('findFiles - with cancelled token', () => {
const root = '/project/foo';
const rpcProtocol = new TestRPCProtocol();
let mainThreadCalled = false;
rpcProtocol.set(MainContext.MainThreadWorkspace, new class extends mock<MainThreadWorkspace>() {
override $startFileSearch(includePattern: string, _includeFolder: UriComponents | null, excludePatternOrDisregardExcludes: string | false, maxResults: number, token: CancellationToken): Promise<URI[] | null> {
mainThreadCalled = true;
return Promise.resolve(null);
}
});
const ws = createExtHostWorkspace(rpcProtocol, { id: 'foo', folders: [aWorkspaceFolderData(URI.file(root), 0)], name: 'Test' }, new NullLogService());
const token = CancellationToken.Cancelled;
return ws.findFiles(new RelativePattern('/other/folder', 'glob/**'), null!, 10, new ExtensionIdentifier('test'), token).then(() => {
assert(!mainThreadCalled, '!mainThreadCalled');
});
});
test('findFiles - RelativePattern exclude', () => {
const root = '/project/foo';
const rpcProtocol = new TestRPCProtocol();
let mainThreadCalled = false;
rpcProtocol.set(MainContext.MainThreadWorkspace, new class extends mock<MainThreadWorkspace>() {
override $startFileSearch(includePattern: string, _includeFolder: UriComponents | null, excludePatternOrDisregardExcludes: string | false, maxResults: number, token: CancellationToken): Promise<URI[] | null> {
mainThreadCalled = true;
assert(excludePatternOrDisregardExcludes, 'glob/**'); // Note that the base portion is ignored, see #52651
return Promise.resolve(null);
}
});
const ws = createExtHostWorkspace(rpcProtocol, { id: 'foo', folders: [aWorkspaceFolderData(URI.file(root), 0)], name: 'Test' }, new NullLogService());
return ws.findFiles('', new RelativePattern(root, 'glob/**'), 10, new ExtensionIdentifier('test')).then(() => {
assert(mainThreadCalled, 'mainThreadCalled');
});
});
test('findTextInFiles - no include', async () => {
const root = '/project/foo';
const rpcProtocol = new TestRPCProtocol();
let mainThreadCalled = false;
rpcProtocol.set(MainContext.MainThreadWorkspace, new class extends mock<MainThreadWorkspace>() {
override async $startTextSearch(query: IPatternInfo, folder: UriComponents | null, options: ITextQueryBuilderOptions, requestId: number, token: CancellationToken): Promise<ITextSearchComplete | null> {
mainThreadCalled = true;
assert.strictEqual(query.pattern, 'foo');
assert.strictEqual(folder, null);
assert.strictEqual(options.includePattern, undefined);
assert.strictEqual(options.excludePattern, undefined);
return null;
}
});
const ws = createExtHostWorkspace(rpcProtocol, { id: 'foo', folders: [aWorkspaceFolderData(URI.file(root), 0)], name: 'Test' }, new NullLogService());
await ws.findTextInFiles({ pattern: 'foo' }, {}, () => { }, new ExtensionIdentifier('test'));
assert(mainThreadCalled, 'mainThreadCalled');
});
test('findTextInFiles - string include', async () => {
const root = '/project/foo';
const rpcProtocol = new TestRPCProtocol();
let mainThreadCalled = false;
rpcProtocol.set(MainContext.MainThreadWorkspace, new class extends mock<MainThreadWorkspace>() {
override async $startTextSearch(query: IPatternInfo, folder: UriComponents | null, options: ITextQueryBuilderOptions, requestId: number, token: CancellationToken): Promise<ITextSearchComplete | null> {
mainThreadCalled = true;
assert.strictEqual(query.pattern, 'foo');
assert.strictEqual(folder, null);
assert.strictEqual(options.includePattern, '**/files');
assert.strictEqual(options.excludePattern, undefined);
return null;
}
});
const ws = createExtHostWorkspace(rpcProtocol, { id: 'foo', folders: [aWorkspaceFolderData(URI.file(root), 0)], name: 'Test' }, new NullLogService());
await ws.findTextInFiles({ pattern: 'foo' }, { include: '**/files' }, () => { }, new ExtensionIdentifier('test'));
assert(mainThreadCalled, 'mainThreadCalled');
});
test('findTextInFiles - RelativePattern include', async () => {
const root = '/project/foo';
const rpcProtocol = new TestRPCProtocol();
let mainThreadCalled = false;
rpcProtocol.set(MainContext.MainThreadWorkspace, new class extends mock<MainThreadWorkspace>() {
override async $startTextSearch(query: IPatternInfo, folder: UriComponents | null, options: ITextQueryBuilderOptions, requestId: number, token: CancellationToken): Promise<ITextSearchComplete | null> {
mainThreadCalled = true;
assert.strictEqual(query.pattern, 'foo');
assert.deepStrictEqual(URI.revive(folder!).toString(), URI.file('/other/folder').toString());
assert.strictEqual(options.includePattern, 'glob/**');
assert.strictEqual(options.excludePattern, undefined);
return null;
}
});
const ws = createExtHostWorkspace(rpcProtocol, { id: 'foo', folders: [aWorkspaceFolderData(URI.file(root), 0)], name: 'Test' }, new NullLogService());
await ws.findTextInFiles({ pattern: 'foo' }, { include: new RelativePattern('/other/folder', 'glob/**') }, () => { }, new ExtensionIdentifier('test'));
assert(mainThreadCalled, 'mainThreadCalled');
});
test('findTextInFiles - with cancelled token', async () => {
const root = '/project/foo';
const rpcProtocol = new TestRPCProtocol();
let mainThreadCalled = false;
rpcProtocol.set(MainContext.MainThreadWorkspace, new class extends mock<MainThreadWorkspace>() {
override async $startTextSearch(query: IPatternInfo, folder: UriComponents | null, options: ITextQueryBuilderOptions, requestId: number, token: CancellationToken): Promise<ITextSearchComplete | null> {
mainThreadCalled = true;
return null;
}
});
const ws = createExtHostWorkspace(rpcProtocol, { id: 'foo', folders: [aWorkspaceFolderData(URI.file(root), 0)], name: 'Test' }, new NullLogService());
const token = CancellationToken.Cancelled;
await ws.findTextInFiles({ pattern: 'foo' }, {}, () => { }, new ExtensionIdentifier('test'), token);
assert(!mainThreadCalled, '!mainThreadCalled');
});
test('findTextInFiles - RelativePattern exclude', async () => {
const root = '/project/foo';
const rpcProtocol = new TestRPCProtocol();
let mainThreadCalled = false;
rpcProtocol.set(MainContext.MainThreadWorkspace, new class extends mock<MainThreadWorkspace>() {
override async $startTextSearch(query: IPatternInfo, folder: UriComponents | null, options: ITextQueryBuilderOptions, requestId: number, token: CancellationToken): Promise<ITextSearchComplete | null> {
mainThreadCalled = true;
assert.strictEqual(query.pattern, 'foo');
assert.deepStrictEqual(folder, null);
assert.strictEqual(options.includePattern, undefined);
assert.strictEqual(options.excludePattern, 'glob/**'); // exclude folder is ignored...
return null;
}
});
const ws = createExtHostWorkspace(rpcProtocol, { id: 'foo', folders: [aWorkspaceFolderData(URI.file(root), 0)], name: 'Test' }, new NullLogService());
await ws.findTextInFiles({ pattern: 'foo' }, { exclude: new RelativePattern('/other/folder', 'glob/**') }, () => { }, new ExtensionIdentifier('test'));
assert(mainThreadCalled, 'mainThreadCalled');
});
});
| src/vs/workbench/api/test/browser/extHostWorkspace.test.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017804196977522224,
0.00017382425721734762,
0.00016598307411186397,
0.0001738208666210994,
0.0000022787608031649143
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.