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": 4,
"code_window": [
" this._channel.on(Events.SET_CURRENT_STORY, ({ storyId, viewMode }) =>\n",
" this.setSelection({ storyId, viewMode })\n",
" );\n",
"\n",
" this._channel.on(Events.UPDATE_STORY_ARGS, (id: string, newArgs: Args) =>\n",
" this.updateStoryArgs(id, newArgs)\n",
" );\n",
"\n",
" this._channel.on(Events.UPDATE_GLOBALS, (newGlobals: Args) => this.updateGlobals(newGlobals));\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this._channel.on(\n",
" Events.UPDATE_STORY_ARGS,\n",
" ({ storyId, updatedArgs }: { storyId: string; updatedArgs: Args }) =>\n",
" this.updateStoryArgs(storyId, updatedArgs)\n"
],
"file_path": "lib/client-api/src/story_store.ts",
"type": "replace",
"edit_start_line_idx": 157
} | # See http://help.github.com/ignore-files/ for more about ignoring files.
# dependencies
node_modules
# testing
coverage
# production
build
# misc
.DS_Store
npm-debug.log
tmp
.env
.storybook/preview-head.html
| examples/ember-cli/.gitignore | 0 | https://github.com/storybookjs/storybook/commit/962ab44d1155bfc8707695757726149be8713760 | [
0.00017031629977282137,
0.00016758234414737672,
0.00016484838852193207,
0.00016758234414737672,
0.0000027339556254446507
] |
{
"id": 4,
"code_window": [
" this._channel.on(Events.SET_CURRENT_STORY, ({ storyId, viewMode }) =>\n",
" this.setSelection({ storyId, viewMode })\n",
" );\n",
"\n",
" this._channel.on(Events.UPDATE_STORY_ARGS, (id: string, newArgs: Args) =>\n",
" this.updateStoryArgs(id, newArgs)\n",
" );\n",
"\n",
" this._channel.on(Events.UPDATE_GLOBALS, (newGlobals: Args) => this.updateGlobals(newGlobals));\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this._channel.on(\n",
" Events.UPDATE_STORY_ARGS,\n",
" ({ storyId, updatedArgs }: { storyId: string; updatedArgs: Args }) =>\n",
" this.updateStoryArgs(storyId, updatedArgs)\n"
],
"file_path": "lib/client-api/src/story_store.ts",
"type": "replace",
"edit_start_line_idx": 157
} | {
"name": "@storybook/addon-storyshots",
"version": "6.0.0-beta.39",
"description": "StoryShots is a Jest Snapshot Testing Addon for Storybook.",
"keywords": [
"addon",
"storybook"
],
"homepage": "https://github.com/storybookjs/storybook/tree/master/addons/storyshots/storyshots-core",
"bugs": {
"url": "https://github.com/storybookjs/storybook/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/storybookjs/storybook.git",
"directory": "addons/storyshots/storyshots-core"
},
"license": "MIT",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist/**/*",
"README.md",
"*.js",
"*.d.ts",
"ts3.5/**/*"
],
"scripts": {
"build-storybook": "build-storybook",
"example": "jest storyshot.test",
"prepare": "node ../../../scripts/prepare.js",
"storybook": "start-storybook -p 6006"
},
"dependencies": {
"@jest/transform": "^26.0.0",
"@storybook/addons": "6.0.0-beta.39",
"@storybook/client-api": "6.0.0-beta.39",
"@storybook/core": "6.0.0-beta.39",
"@types/glob": "^7.1.1",
"@types/jest": "^25.1.1",
"@types/jest-specific-snapshot": "^0.5.3",
"babel-plugin-require-context-hook": "^1.0.0",
"core-js": "^3.0.1",
"glob": "^7.1.3",
"global": "^4.3.2",
"jest-specific-snapshot": "^3.0.0",
"pretty-format": "^25.5.0",
"read-pkg-up": "^7.0.0",
"regenerator-runtime": "^0.13.3",
"ts-dedent": "^1.1.1"
},
"devDependencies": {
"@storybook/addon-docs": "6.0.0-beta.39",
"@storybook/react": "6.0.0-beta.39",
"babel-loader": "^8.0.6",
"enzyme": "^3.11.0",
"enzyme-to-json": "^3.4.1",
"jest-emotion": "^10.0.17",
"react": "^16.8.3"
},
"peerDependencies": {
"react-dom": "*"
},
"publishConfig": {
"access": "public"
},
"gitHead": "4b9d901add9452525135caae98ae5f78dd8da9ff",
"typesVersions": {
"<=3.5": {
"*": [
"ts3.5/*"
]
}
}
}
| addons/storyshots/storyshots-core/package.json | 0 | https://github.com/storybookjs/storybook/commit/962ab44d1155bfc8707695757726149be8713760 | [
0.00017215099069289863,
0.00017072659102268517,
0.00016775411495473236,
0.00017094286158680916,
0.0000014721160823683022
] |
{
"id": 0,
"code_window": [
"\n",
" &-size-changer.@{ant-prefix}-select {\n",
" display: inline-block;\n",
" width: auto;\n",
" margin-right: 8px;\n",
" }\n",
"\n",
" &-quick-jumper {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "components/pagination/style/index.less",
"type": "replace",
"edit_start_line_idx": 232
} | @import '../../style/themes/index';
@import '../../style/mixins/index';
@import '../../input/style/mixin';
@pagination-prefix-cls: ~'@{ant-prefix}-pagination';
.@{pagination-prefix-cls} {
.reset-component;
ul,
ol {
margin: 0;
padding: 0;
list-style: none;
}
&::after {
display: block;
clear: both;
height: 0;
overflow: hidden;
visibility: hidden;
content: ' ';
}
&-total-text {
display: inline-block;
height: @pagination-item-size;
margin-right: 8px;
line-height: @pagination-item-size - 2px;
vertical-align: middle;
}
&-item {
display: inline-block;
min-width: @pagination-item-size;
height: @pagination-item-size;
margin-right: 8px;
font-family: @pagination-font-family;
line-height: @pagination-item-size - 2px;
text-align: center;
vertical-align: middle;
list-style: none;
background-color: @pagination-item-bg;
border: @border-width-base @border-style-base @border-color-base;
border-radius: @border-radius-base;
outline: 0;
cursor: pointer;
user-select: none;
a {
display: block;
padding: 0 6px;
color: @text-color;
transition: none;
&:hover {
text-decoration: none;
}
}
&:focus,
&:hover {
border-color: @primary-color;
transition: all 0.3s;
a {
color: @primary-color;
}
}
&-active {
font-weight: @pagination-font-weight-active;
background: @pagination-item-bg-active;
border-color: @primary-color;
a {
color: @primary-color;
}
&:focus,
&:hover {
border-color: @primary-5;
}
&:focus a,
&:hover a {
color: @primary-5;
}
}
}
&-jump-prev,
&-jump-next {
outline: 0;
.@{pagination-prefix-cls}-item-container {
position: relative;
.@{pagination-prefix-cls}-item-link-icon {
color: @primary-color;
font-size: @font-size-sm;
letter-spacing: -1px;
opacity: 0;
transition: all 0.2s;
&-svg {
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
}
.@{pagination-prefix-cls}-item-ellipsis {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
display: block;
margin: auto;
color: @disabled-color;
font-family: Arial, Helvetica, sans-serif;
letter-spacing: 2px;
text-align: center;
text-indent: 0.13em;
opacity: 1;
transition: all 0.2s;
}
}
&:focus,
&:hover {
.@{pagination-prefix-cls}-item-link-icon {
opacity: 1;
}
.@{pagination-prefix-cls}-item-ellipsis {
opacity: 0;
}
}
}
&-prev,
&-jump-prev,
&-jump-next {
margin-right: 8px;
}
&-prev,
&-next,
&-jump-prev,
&-jump-next {
display: inline-block;
min-width: @pagination-item-size;
height: @pagination-item-size;
color: @text-color;
font-family: @pagination-font-family;
line-height: @pagination-item-size;
text-align: center;
vertical-align: middle;
list-style: none;
border-radius: @border-radius-base;
cursor: pointer;
transition: all 0.3s;
}
&-prev,
&-next {
font-family: Arial, Helvetica, sans-serif;
outline: 0;
button {
color: @text-color;
cursor: pointer;
user-select: none;
}
&:hover button {
border-color: @primary-5;
}
.@{pagination-prefix-cls}-item-link {
display: block;
width: 100%;
height: 100%;
font-size: 12px;
text-align: center;
background-color: @pagination-item-link-bg;
border: @border-width-base @border-style-base @border-color-base;
border-radius: @border-radius-base;
outline: none;
transition: all 0.3s;
}
&:focus .@{pagination-prefix-cls}-item-link,
&:hover .@{pagination-prefix-cls}-item-link {
color: @primary-color;
border-color: @primary-color;
}
}
&-disabled {
&,
&:hover,
&:focus {
cursor: not-allowed;
.@{pagination-prefix-cls}-item-link {
color: @disabled-color;
border-color: @border-color-base;
cursor: not-allowed;
}
}
}
&-slash {
margin: 0 10px 0 5px;
}
&-options {
display: inline-block;
margin-left: 16px;
vertical-align: middle;
// IE11 css hack. `*::-ms-backdrop,` is a must have
@media all and (-ms-high-contrast: none) {
*::-ms-backdrop,
& {
vertical-align: top;
}
}
&-size-changer.@{ant-prefix}-select {
display: inline-block;
width: auto;
margin-right: 8px;
}
&-quick-jumper {
display: inline-block;
height: @input-height-base;
line-height: @input-height-base;
vertical-align: top;
input {
.input;
width: 50px;
margin: 0 8px;
}
}
}
&-simple &-prev,
&-simple &-next {
height: @pagination-item-size-sm;
line-height: @pagination-item-size-sm;
vertical-align: top;
.@{pagination-prefix-cls}-item-link {
height: @pagination-item-size-sm;
background-color: transparent;
border: 0;
&::after {
height: @pagination-item-size-sm;
line-height: @pagination-item-size-sm;
}
}
}
&-simple &-simple-pager {
display: inline-block;
height: @pagination-item-size-sm;
margin-right: 8px;
input {
box-sizing: border-box;
height: 100%;
margin-right: 8px;
padding: 0 6px;
text-align: center;
background-color: @pagination-item-input-bg;
border: @border-width-base @border-style-base @border-color-base;
border-radius: @border-radius-base;
outline: none;
transition: border-color 0.3s;
&:hover {
border-color: @primary-color;
}
&[disabled] {
color: @disabled-color;
background: @disabled-bg;
border-color: @border-color-base;
cursor: not-allowed;
}
}
}
&.mini &-total-text,
&.mini &-simple-pager {
height: @pagination-item-size-sm;
line-height: @pagination-item-size-sm;
}
&.mini &-item {
min-width: @pagination-item-size-sm;
height: @pagination-item-size-sm;
margin: 0;
line-height: @pagination-item-size-sm - 2px;
}
&.mini &-item:not(&-item-active) {
background: transparent;
border-color: transparent;
}
&.mini &-prev,
&.mini &-next {
min-width: @pagination-item-size-sm;
height: @pagination-item-size-sm;
margin: 0;
line-height: @pagination-item-size-sm;
}
&.mini &-prev &-item-link,
&.mini &-next &-item-link {
background: transparent;
border-color: transparent;
&::after {
height: @pagination-item-size-sm;
line-height: @pagination-item-size-sm;
}
}
&.mini &-jump-prev,
&.mini &-jump-next {
height: @pagination-item-size-sm;
margin-right: 0;
line-height: @pagination-item-size-sm;
}
&.mini &-options {
margin-left: 2px;
&-size-changer {
top: @pagination-mini-options-size-changer-top;
}
&-quick-jumper {
height: @pagination-item-size-sm;
line-height: @pagination-item-size-sm;
input {
.input-sm;
width: 44px;
}
}
}
// ============================ Disabled ============================
&&-disabled {
cursor: not-allowed;
.@{pagination-prefix-cls}-item {
background: @disabled-bg;
border-color: @border-color-base;
cursor: not-allowed;
a {
color: @disabled-color;
background: transparent;
border: none;
cursor: not-allowed;
}
&-active {
background: @pagination-item-disabled-bg-active;
border-color: transparent;
a {
color: @pagination-item-disabled-color-active;
}
}
}
.@{pagination-prefix-cls}-item-link {
color: @disabled-color;
background: @disabled-bg;
border-color: @border-color-base;
cursor: not-allowed;
.@{pagination-prefix-cls}-simple& {
background: transparent;
}
}
.@{pagination-prefix-cls}-item-link-icon {
opacity: 0;
}
.@{pagination-prefix-cls}-item-ellipsis {
opacity: 1;
}
.@{pagination-prefix-cls}-simple-pager {
color: @disabled-color;
}
}
}
@media only screen and (max-width: @screen-lg) {
.@{pagination-prefix-cls}-item {
&-after-jump-prev,
&-before-jump-next {
display: none;
}
}
}
@media only screen and (max-width: @screen-sm) {
.@{pagination-prefix-cls}-options {
display: none;
}
}
@import './rtl';
| components/pagination/style/index.less | 1 | https://github.com/ant-design/ant-design/commit/684248c52a648faf572640e881cea00127d67101 | [
0.9400532841682434,
0.02256101369857788,
0.00016531084838788956,
0.00017219399160239846,
0.1415928155183792
] |
{
"id": 0,
"code_window": [
"\n",
" &-size-changer.@{ant-prefix}-select {\n",
" display: inline-block;\n",
" width: auto;\n",
" margin-right: 8px;\n",
" }\n",
"\n",
" &-quick-jumper {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "components/pagination/style/index.less",
"type": "replace",
"edit_start_line_idx": 232
} | ---
order: 999
title:
zh-CN: 4.0 Debug
en-US: 4.0 Debug
debug: true
---
## zh-CN
基本使用。
## en-US
Basic Usage.
```jsx
import { Select, Input, Button } from 'antd';
const { Option } = Select;
function handleChange(value) {
console.log(`selected ${value}`);
}
ReactDOM.render(
<div
style={{
width: 500,
position: 'relative',
zIndex: 1,
border: '1px solid red',
background: '#FFF',
}}
>
<Input style={{ width: 100 }} value="222" />
<Select style={{ width: 120 }} onChange={handleChange} showSearch placeholder="233">
<Option value="jack">Jack</Option>
<Option value="lucy">Lucy</Option>
<Option value="disabled" disabled>
Disabled
</Option>
<Option value="Yiminghe">yiminghe</Option>
<Option value="long">I am super super long!</Option>
</Select>
<Select
mode="multiple"
style={{ width: 120 }}
defaultValue={['lucy']}
onChange={handleChange}
showSearch
placeholder="233"
>
<Option value="jack">Jack</Option>
<Option value="lucy">Lucy</Option>
<Option value="disabled" disabled>
Disabled
</Option>
<Option value="Yiminghe">yiminghe</Option>
<Option value="long">I am super super long!</Option>
</Select>
<span className="debug-align">AntDesign</span>
<Button>222</Button>
</div>,
mountNode,
);
```
<style>
#components-select-demo-debug .debug-align {
position: relative;
display: inline-block;
line-height: 32px;
height: 32px;
background: rgba(255, 0, 0, 0.1);
box-sizing: border-box;
}
#components-select-demo-debug .debug-align:after {
position: absolute;
content: '';
border: 1px solid green;
left: 0;
right: 0;
top: 0;
bottom: 0;
pointer-events: none;
}
</style>
| components/select/demo/debug.md | 0 | https://github.com/ant-design/ant-design/commit/684248c52a648faf572640e881cea00127d67101 | [
0.00081146031152457,
0.00025022405316121876,
0.00016564597899559885,
0.000175523673533462,
0.0001992531178984791
] |
{
"id": 0,
"code_window": [
"\n",
" &-size-changer.@{ant-prefix}-select {\n",
" display: inline-block;\n",
" width: auto;\n",
" margin-right: 8px;\n",
" }\n",
"\n",
" &-quick-jumper {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "components/pagination/style/index.less",
"type": "replace",
"edit_start_line_idx": 232
} | import React from 'react';
import { render, mount } from 'enzyme';
import { Col, Row } from '..';
import mountTest from '../../../tests/shared/mountTest';
import rtlTest from '../../../tests/shared/rtlTest';
import useBreakpoint from '../hooks/useBreakpoint';
import ResponsiveObserve from '../../_util/responsiveObserve';
describe('Grid', () => {
mountTest(Row);
mountTest(Col);
rtlTest(Row);
rtlTest(Col);
it('should render Col', () => {
const wrapper = render(<Col span={2} />);
expect(wrapper).toMatchSnapshot();
});
it('should render Row', () => {
const wrapper = render(<Row />);
expect(wrapper).toMatchSnapshot();
});
it('when typeof gutter is object', () => {
const wrapper = mount(<Row gutter={{ xs: 8, sm: 16, md: 24 }} />);
expect(wrapper.find('div').first().props().style).toEqual(
expect.objectContaining({
marginLeft: -4,
marginRight: -4,
}),
);
});
it('when typeof gutter is object array', () => {
const wrapper = mount(
<Row
gutter={[
{ xs: 8, sm: 16, md: 24, lg: 32, xl: 40 },
{ xs: 8, sm: 16, md: 24, lg: 32, xl: 40 },
]}
/>,
);
expect(wrapper.find('div').first().props().style).toEqual(
expect.objectContaining({
marginLeft: -4,
marginRight: -4,
}),
);
});
it('when typeof gutter is object array in large screen', () => {
const wrapper = render(
<Row
gutter={[
{ xs: 8, sm: 16, md: 24, lg: 32, xl: 40 },
{ xs: 8, sm: 16, md: 24, lg: 100, xl: 400 },
]}
/>,
);
expect(wrapper).toMatchSnapshot();
});
it('renders wrapped Col correctly', () => {
const MyCol = () => <Col span={12} />;
const wrapper = render(
<Row gutter={20}>
<div>
<Col span={12} />
</div>
<MyCol />
</Row>,
);
expect(wrapper).toMatchSnapshot();
});
it('when component has been unmounted, componentWillUnmount should be called', () => {
const Unmount = jest.spyOn(ResponsiveObserve, 'unsubscribe');
const wrapper = mount(<Row gutter={{ xs: 20 }} />);
wrapper.unmount();
expect(Unmount).toHaveBeenCalled();
});
it('should work correct when gutter is object', () => {
const wrapper = mount(<Row gutter={{ xs: 20 }} />);
expect(wrapper.find('div').prop('style')).toEqual({
marginLeft: -10,
marginRight: -10,
});
});
it('should work currect when gutter is array', () => {
const wrapper = mount(<Row gutter={[16, 20]} />);
expect(wrapper.find('div').prop('style')).toEqual({
marginLeft: -8,
marginRight: -8,
marginTop: -10,
marginBottom: 10,
});
});
// By jsdom mock, actual jsdom not implemented matchMedia
// https://jestjs.io/docs/en/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom
it('should work with useBreakpoint', () => {
function Demo() {
const screens = useBreakpoint();
return JSON.stringify(screens);
}
const wrapper = mount(<Demo />);
expect(wrapper.text()).toEqual(
JSON.stringify({
xs: true,
sm: false,
md: false,
lg: false,
xl: false,
xxl: false,
}),
);
});
});
| components/grid/__tests__/index.test.js | 0 | https://github.com/ant-design/ant-design/commit/684248c52a648faf572640e881cea00127d67101 | [
0.00018607986567076296,
0.00017474421474616975,
0.00016633303312119097,
0.00017522936104796827,
0.000005577098363573896
] |
{
"id": 0,
"code_window": [
"\n",
" &-size-changer.@{ant-prefix}-select {\n",
" display: inline-block;\n",
" width: auto;\n",
" margin-right: 8px;\n",
" }\n",
"\n",
" &-quick-jumper {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "components/pagination/style/index.less",
"type": "replace",
"edit_start_line_idx": 232
} | ---
order: 1
title:
zh-CN: 不可用
en-US: Disabled
---
## zh-CN
Switch 失效状态。
## en-US
Disabled state of `Switch`.
```jsx
import { Switch, Button } from 'antd';
class App extends React.Component {
state = {
disabled: true,
};
toggle = () => {
this.setState({
disabled: !this.state.disabled,
});
};
render() {
return (
<>
<Switch disabled={this.state.disabled} defaultChecked />
<br />
<Button type="primary" onClick={this.toggle}>
Toggle disabled
</Button>
</>
);
}
}
ReactDOM.render(<App />, mountNode);
```
| components/switch/demo/disabled.md | 0 | https://github.com/ant-design/ant-design/commit/684248c52a648faf572640e881cea00127d67101 | [
0.0008419841760769486,
0.0003060503804590553,
0.00016746643814258277,
0.00017313193529844284,
0.0002679784083738923
] |
{
"id": 1,
"code_window": [
"\n",
" &-quick-jumper {\n",
" display: inline-block;\n",
" height: @input-height-base;\n",
" line-height: @input-height-base;\n",
" vertical-align: top;\n",
"\n",
" input {\n",
" .input;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" margin-left: @margin-xs;\n"
],
"file_path": "components/pagination/style/index.less",
"type": "add",
"edit_start_line_idx": 238
} | @import '../../style/themes/index';
@import '../../style/mixins/index';
@import '../../input/style/mixin';
@pagination-prefix-cls: ~'@{ant-prefix}-pagination';
.@{pagination-prefix-cls} {
&-rtl {
direction: rtl;
}
&-total-text {
.@{pagination-prefix-cls}-rtl & {
margin-right: 0;
margin-left: 8px;
}
}
&-item {
.@{pagination-prefix-cls}-rtl & {
margin-right: 0;
margin-left: 8px;
}
}
&-prev,
&-jump-prev,
&-jump-next {
.@{pagination-prefix-cls}-rtl & {
margin-right: 0;
margin-left: 8px;
}
}
&-slash {
.@{pagination-prefix-cls}-rtl & {
margin: 0 5px 0 10px;
}
}
&-options {
.@{pagination-prefix-cls}-rtl & {
margin-right: 16px;
margin-left: 0;
}
&-size-changer.@{ant-prefix}-select {
.@{pagination-prefix-cls}-rtl & {
margin-right: 0;
margin-left: 8px;
}
}
}
&-simple &-simple-pager {
.@{pagination-prefix-cls}-rtl& {
margin-right: 0;
margin-left: 8px;
}
input {
.@{pagination-prefix-cls}-rtl& {
margin-right: 0;
margin-left: 8px;
}
}
}
&.mini &-options {
.@{pagination-prefix-cls}-rtl& {
margin-right: 2px;
margin-left: 0;
}
}
}
| components/pagination/style/rtl.less | 1 | https://github.com/ant-design/ant-design/commit/684248c52a648faf572640e881cea00127d67101 | [
0.00027553722611628473,
0.00018436607206240296,
0.00016961811343207955,
0.00017181310977321118,
0.000034482200135244057
] |
{
"id": 1,
"code_window": [
"\n",
" &-quick-jumper {\n",
" display: inline-block;\n",
" height: @input-height-base;\n",
" line-height: @input-height-base;\n",
" vertical-align: top;\n",
"\n",
" input {\n",
" .input;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" margin-left: @margin-xs;\n"
],
"file_path": "components/pagination/style/index.less",
"type": "add",
"edit_start_line_idx": 238
} | import deDE from '../../date-picker/locale/de_DE';
export default deDE;
| components/calendar/locale/de_DE.tsx | 0 | https://github.com/ant-design/ant-design/commit/684248c52a648faf572640e881cea00127d67101 | [
0.00017699928139336407,
0.00017699928139336407,
0.00017699928139336407,
0.00017699928139336407,
0
] |
{
"id": 1,
"code_window": [
"\n",
" &-quick-jumper {\n",
" display: inline-block;\n",
" height: @input-height-base;\n",
" line-height: @input-height-base;\n",
" vertical-align: top;\n",
"\n",
" input {\n",
" .input;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" margin-left: @margin-xs;\n"
],
"file_path": "components/pagination/style/index.less",
"type": "add",
"edit_start_line_idx": 238
} | import * as React from 'react';
import classNames from 'classnames';
import toArray from 'rc-util/lib/Children/toArray';
import copy from 'copy-to-clipboard';
import omit from 'omit.js';
import EditOutlined from '@ant-design/icons/EditOutlined';
import CheckOutlined from '@ant-design/icons/CheckOutlined';
import CopyOutlined from '@ant-design/icons/CopyOutlined';
import ResizeObserver from 'rc-resize-observer';
import { AutoSizeType } from 'rc-textarea/lib/ResizableTextArea';
import { ConfigConsumerProps, configConsumerProps, ConfigContext } from '../config-provider';
import LocaleReceiver from '../locale-provider/LocaleReceiver';
import devWarning from '../_util/devWarning';
import TransButton from '../_util/transButton';
import raf from '../_util/raf';
import { isStyleSupport } from '../_util/styleChecker';
import Tooltip from '../tooltip';
import Typography, { TypographyProps } from './Typography';
import Editable from './Editable';
import measure from './util';
export type BaseType = 'secondary' | 'success' | 'warning' | 'danger';
const isLineClampSupport = isStyleSupport('webkitLineClamp');
const isTextOverflowSupport = isStyleSupport('textOverflow');
interface CopyConfig {
text?: string;
onCopy?: () => void;
icon?: React.ReactNode;
tooltips?: boolean | React.ReactNode;
}
interface EditConfig {
editing?: boolean;
icon?: React.ReactNode;
tooltip?: boolean | React.ReactNode;
onStart?: () => void;
onChange?: (value: string) => void;
maxLength?: number;
autoSize?: boolean | AutoSizeType;
}
interface EllipsisConfig {
rows?: number;
expandable?: boolean;
suffix?: string;
symbol?: React.ReactNode;
onExpand?: React.MouseEventHandler<HTMLElement>;
onEllipsis?: (ellipsis: boolean) => void;
}
export interface BlockProps extends TypographyProps {
title?: string;
editable?: boolean | EditConfig;
copyable?: boolean | CopyConfig;
type?: BaseType;
disabled?: boolean;
ellipsis?: boolean | EllipsisConfig;
// decorations
code?: boolean;
mark?: boolean;
underline?: boolean;
delete?: boolean;
strong?: boolean;
keyboard?: boolean;
}
function wrapperDecorations(
{ mark, code, underline, delete: del, strong, keyboard }: BlockProps,
content: React.ReactNode,
) {
let currentContent = content;
function wrap(needed: boolean | undefined, tag: string) {
if (!needed) return;
currentContent = React.createElement(tag, {}, currentContent);
}
wrap(strong, 'strong');
wrap(underline, 'u');
wrap(del, 'del');
wrap(code, 'code');
wrap(mark, 'mark');
wrap(keyboard, 'kbd');
return currentContent;
}
interface InternalBlockProps extends BlockProps {
component: string;
}
interface BaseState {
edit: boolean;
copied: boolean;
ellipsisText: string;
ellipsisContent: React.ReactNode;
isEllipsis: boolean;
expanded: boolean;
clientRendered: boolean;
}
interface Locale {
edit?: string;
copy?: string;
copied?: string;
expand?: string;
}
const ELLIPSIS_STR = '...';
class Base extends React.Component<InternalBlockProps, BaseState> {
static contextType = ConfigContext;
static defaultProps = {
children: '',
};
static getDerivedStateFromProps(nextProps: BlockProps) {
const { children, editable } = nextProps;
devWarning(
!editable || typeof children === 'string',
'Typography',
'When `editable` is enabled, the `children` should use string.',
);
return {};
}
context: ConfigConsumerProps;
editIcon?: TransButton;
contentRef = React.createRef<HTMLElement>();
copyId?: number;
rafId?: number;
// Locale
expandStr?: string;
copyStr?: string;
copiedStr?: string;
editStr?: string;
state: BaseState = {
edit: false,
copied: false,
ellipsisText: '',
ellipsisContent: null,
isEllipsis: false,
expanded: false,
clientRendered: false,
};
componentDidMount() {
this.setState({ clientRendered: true });
this.resizeOnNextFrame();
}
componentDidUpdate(prevProps: BlockProps) {
const { children } = this.props;
const ellipsis = this.getEllipsis();
const prevEllipsis = this.getEllipsis(prevProps);
if (children !== prevProps.children || ellipsis.rows !== prevEllipsis.rows) {
this.resizeOnNextFrame();
}
}
componentWillUnmount() {
window.clearTimeout(this.copyId);
raf.cancel(this.rafId);
}
getPrefixCls = () => {
const { prefixCls: customizePrefixCls } = this.props;
const { getPrefixCls } = this.context;
return getPrefixCls('typography', customizePrefixCls);
};
// =============== Expand ===============
onExpandClick: React.MouseEventHandler<HTMLElement> = e => {
const { onExpand } = this.getEllipsis();
this.setState({ expanded: true });
if (onExpand) {
(onExpand as React.MouseEventHandler<HTMLElement>)(e);
}
};
// ================ Edit ================
onEditClick = () => {
this.triggerEdit(true);
};
onEditChange = (value: string) => {
const { onChange } = this.getEditable();
if (onChange) {
onChange(value);
}
this.triggerEdit(false);
};
onEditCancel = () => {
this.triggerEdit(false);
};
// ================ Copy ================
onCopyClick = () => {
const { children, copyable } = this.props;
const copyConfig: CopyConfig = {
...(typeof copyable === 'object' ? copyable : null),
};
if (copyConfig.text === undefined) {
copyConfig.text = String(children);
}
copy(copyConfig.text || '');
this.setState({ copied: true }, () => {
if (copyConfig.onCopy) {
copyConfig.onCopy();
}
this.copyId = window.setTimeout(() => {
this.setState({ copied: false });
}, 3000);
});
};
getEditable(props?: BlockProps): EditConfig {
const { edit } = this.state;
const { editable } = props || this.props;
if (!editable) return { editing: edit };
return {
editing: edit,
...(typeof editable === 'object' ? editable : null),
};
}
getEllipsis(props?: BlockProps): EllipsisConfig {
const { ellipsis } = props || this.props;
if (!ellipsis) return {};
return {
rows: 1,
expandable: false,
...(typeof ellipsis === 'object' ? ellipsis : null),
};
}
setEditRef = (node: TransButton) => {
this.editIcon = node;
};
triggerEdit = (edit: boolean) => {
const { onStart } = this.getEditable();
if (edit && onStart) {
onStart();
}
this.setState({ edit }, () => {
if (!edit && this.editIcon) {
this.editIcon.focus();
}
});
};
// ============== Ellipsis ==============
resizeOnNextFrame = () => {
raf.cancel(this.rafId);
this.rafId = raf(() => {
// Do not bind `syncEllipsis`. It need for test usage on prototype
this.syncEllipsis();
});
};
canUseCSSEllipsis(): boolean {
const { clientRendered } = this.state;
const { editable, copyable } = this.props;
const { rows, expandable, suffix, onEllipsis } = this.getEllipsis();
if (suffix) return false;
// Can't use css ellipsis since we need to provide the place for button
if (editable || copyable || expandable || !clientRendered || onEllipsis) {
return false;
}
if (rows === 1) {
return isTextOverflowSupport;
}
return isLineClampSupport;
}
syncEllipsis() {
const { ellipsisText, isEllipsis, expanded } = this.state;
const { rows, suffix, onEllipsis } = this.getEllipsis();
const { children } = this.props;
if (!rows || rows < 0 || !this.contentRef.current || expanded) return;
// Do not measure if css already support ellipsis
if (this.canUseCSSEllipsis()) return;
devWarning(
toArray(children).every((child: React.ReactNode) => typeof child === 'string'),
'Typography',
'`ellipsis` should use string as children only.',
);
const { content, text, ellipsis } = measure(
this.contentRef.current,
{ rows, suffix },
children,
this.renderOperations(true),
ELLIPSIS_STR,
);
if (ellipsisText !== text || isEllipsis !== ellipsis) {
this.setState({ ellipsisText: text, ellipsisContent: content, isEllipsis: ellipsis });
if (isEllipsis !== ellipsis && onEllipsis) {
onEllipsis(ellipsis);
}
}
}
renderExpand(forceRender?: boolean) {
const { expandable, symbol } = this.getEllipsis();
const { expanded, isEllipsis } = this.state;
if (!expandable) return null;
// force render expand icon for measure usage or it will cause dead loop
if (!forceRender && (expanded || !isEllipsis)) return null;
let expandContent: React.ReactNode;
if (symbol) {
expandContent = symbol;
} else {
expandContent = this.expandStr;
}
return (
<a
key="expand"
className={`${this.getPrefixCls()}-expand`}
onClick={this.onExpandClick}
aria-label={this.expandStr}
>
{expandContent}
</a>
);
}
renderEdit() {
const { editable } = this.props;
if (!editable) return;
const { icon, tooltip } = editable as EditConfig;
const title = toArray(tooltip)[0] || this.editStr;
const ariaLabel = typeof title === 'string' ? title : '';
return (
<Tooltip key="edit" title={tooltip === false ? '' : title}>
<TransButton
ref={this.setEditRef}
className={`${this.getPrefixCls()}-edit`}
onClick={this.onEditClick}
aria-label={ariaLabel}
>
{icon || <EditOutlined role="button" />}
</TransButton>
</Tooltip>
);
}
renderCopy() {
const { copied } = this.state;
const { copyable } = this.props;
if (!copyable) return;
const prefixCls = this.getPrefixCls();
const { tooltips } = copyable as CopyConfig;
let tooltipNodes = toArray(tooltips) as React.ReactNode[];
if (tooltipNodes.length === 0) {
tooltipNodes = [this.copyStr, this.copiedStr];
}
const title = copied ? tooltipNodes[1] : tooltipNodes[0];
const ariaLabel = typeof title === 'string' ? title : '';
const icons = toArray((copyable as CopyConfig).icon);
return (
<Tooltip key="copy" title={tooltips === false ? '' : title}>
<TransButton
className={classNames(`${prefixCls}-copy`, copied && `${prefixCls}-copy-success`)}
onClick={this.onCopyClick}
aria-label={ariaLabel}
>
{copied ? icons[1] || <CheckOutlined /> : icons[0] || <CopyOutlined />}
</TransButton>
</Tooltip>
);
}
renderEditInput() {
const { children, className, style } = this.props;
const { direction } = this.context;
const { maxLength, autoSize } = this.getEditable();
return (
<Editable
value={typeof children === 'string' ? children : ''}
onSave={this.onEditChange}
onCancel={this.onEditCancel}
prefixCls={this.getPrefixCls()}
className={className}
style={style}
direction={direction}
maxLength={maxLength}
autoSize={autoSize}
/>
);
}
renderOperations(forceRenderExpanded?: boolean) {
return [this.renderExpand(forceRenderExpanded), this.renderEdit(), this.renderCopy()].filter(
node => node,
);
}
renderContent() {
const { ellipsisContent, isEllipsis, expanded } = this.state;
const { component, children, className, type, disabled, style, ...restProps } = this.props;
const { direction } = this.context;
const { rows, suffix } = this.getEllipsis();
const prefixCls = this.getPrefixCls();
const textProps = omit(restProps, [
'prefixCls',
'editable',
'copyable',
'ellipsis',
'mark',
'code',
'delete',
'underline',
'strong',
'keyboard',
...configConsumerProps,
]);
const cssEllipsis = this.canUseCSSEllipsis();
const cssTextOverflow = rows === 1 && cssEllipsis;
const cssLineClamp = rows && rows > 1 && cssEllipsis;
let textNode: React.ReactNode = children;
// Only use js ellipsis when css ellipsis not support
if (rows && isEllipsis && !expanded && !cssEllipsis) {
const { title } = restProps;
let restContent = title || '';
if (!title && (typeof children === 'string' || typeof children === 'number')) {
restContent = String(children);
}
// show rest content as title on symbol
restContent = restContent?.slice(String(ellipsisContent || '').length);
// We move full content to outer element to avoid repeat read the content by accessibility
textNode = (
<>
{ellipsisContent}
<span title={restContent} aria-hidden="true">
{ELLIPSIS_STR}
</span>
{suffix}
</>
);
} else {
textNode = (
<>
{children}
{suffix}
</>
);
}
textNode = wrapperDecorations(this.props, textNode);
return (
<LocaleReceiver componentName="Text">
{({ edit, copy: copyStr, copied, expand }: Locale) => {
this.editStr = edit;
this.copyStr = copyStr;
this.copiedStr = copied;
this.expandStr = expand;
return (
<ResizeObserver onResize={this.resizeOnNextFrame} disabled={!rows}>
<Typography
className={classNames(
{
[`${prefixCls}-${type}`]: type,
[`${prefixCls}-disabled`]: disabled,
[`${prefixCls}-ellipsis`]: rows,
[`${prefixCls}-ellipsis-single-line`]: cssTextOverflow,
[`${prefixCls}-ellipsis-multiple-line`]: cssLineClamp,
},
className,
)}
style={{
...style,
WebkitLineClamp: cssLineClamp ? rows : null,
}}
component={component}
ref={this.contentRef}
direction={direction}
{...textProps}
>
{textNode}
{this.renderOperations()}
</Typography>
</ResizeObserver>
);
}}
</LocaleReceiver>
);
}
render() {
const { editing } = this.getEditable();
if (editing) {
return this.renderEditInput();
}
return this.renderContent();
}
}
export default Base;
| components/typography/Base.tsx | 0 | https://github.com/ant-design/ant-design/commit/684248c52a648faf572640e881cea00127d67101 | [
0.0004975209594704211,
0.00017827303963713348,
0.00016467762179672718,
0.00017214557738043368,
0.00004404039282235317
] |
{
"id": 1,
"code_window": [
"\n",
" &-quick-jumper {\n",
" display: inline-block;\n",
" height: @input-height-base;\n",
" line-height: @input-height-base;\n",
" vertical-align: top;\n",
"\n",
" input {\n",
" .input;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" margin-left: @margin-xs;\n"
],
"file_path": "components/pagination/style/index.less",
"type": "add",
"edit_start_line_idx": 238
} | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Descriptions Descriptions support colon 1`] = `
<div
class="ant-descriptions"
>
<div
class="ant-descriptions-view"
>
<table>
<tbody>
<tr
class="ant-descriptions-row"
>
<td
class="ant-descriptions-item"
colspan="1"
>
<div
class="ant-descriptions-item-container"
>
<span
class="ant-descriptions-item-label ant-descriptions-item-no-colon"
>
Product
</span>
<span
class="ant-descriptions-item-content"
>
Cloud Database
</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
`;
exports[`Descriptions Descriptions support style 1`] = `
<div
class="ant-descriptions"
style="background-color: rgb(232, 232, 232);"
>
<div
class="ant-descriptions-view"
>
<table>
<tbody>
<tr
class="ant-descriptions-row"
>
<td
class="ant-descriptions-item"
colspan="1"
>
<div
class="ant-descriptions-item-container"
>
<span
class="ant-descriptions-item-content"
>
Cloud Database
</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
`;
exports[`Descriptions Descriptions.Item support className 1`] = `
<div
class="ant-descriptions"
>
<div
class="ant-descriptions-view"
>
<table>
<tbody>
<tr
class="ant-descriptions-row"
>
<td
class="ant-descriptions-item my-class"
colspan="1"
>
<div
class="ant-descriptions-item-container"
>
<span
class="ant-descriptions-item-label"
>
Product
</span>
<span
class="ant-descriptions-item-content"
>
Cloud Database
</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
`;
exports[`Descriptions column is number 1`] = `
<div
class="ant-descriptions"
>
<div
class="ant-descriptions-view"
>
<table>
<tbody>
<tr
class="ant-descriptions-row"
>
<td
class="ant-descriptions-item"
colspan="1"
>
<div
class="ant-descriptions-item-container"
>
<span
class="ant-descriptions-item-label"
>
Product
</span>
<span
class="ant-descriptions-item-content"
>
Cloud Database
</span>
</div>
</td>
<td
class="ant-descriptions-item"
colspan="1"
>
<div
class="ant-descriptions-item-container"
>
<span
class="ant-descriptions-item-label"
>
Billing
</span>
<span
class="ant-descriptions-item-content"
>
Prepaid
</span>
</div>
</td>
<td
class="ant-descriptions-item"
colspan="1"
>
<div
class="ant-descriptions-item-container"
>
<span
class="ant-descriptions-item-label"
>
time
</span>
<span
class="ant-descriptions-item-content"
>
18:00:00
</span>
</div>
</td>
</tr>
<tr
class="ant-descriptions-row"
>
<td
class="ant-descriptions-item"
colspan="3"
>
<div
class="ant-descriptions-item-container"
>
<span
class="ant-descriptions-item-label"
>
Amount
</span>
<span
class="ant-descriptions-item-content"
>
$80.00
</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
`;
exports[`Descriptions should work with React Fragment 1`] = `
<div
class="ant-descriptions"
>
<div
class="ant-descriptions-view"
>
<table>
<tbody>
<tr
class="ant-descriptions-row"
>
<td
class="ant-descriptions-item"
colspan="1"
>
<div
class="ant-descriptions-item-container"
>
<span
class="ant-descriptions-item-label"
>
bamboo
</span>
<span
class="ant-descriptions-item-content"
>
bamboo
</span>
</div>
</td>
</tr>
<tr
class="ant-descriptions-row"
>
<td
class="ant-descriptions-item"
colspan="1"
>
<div
class="ant-descriptions-item-container"
>
<span
class="ant-descriptions-item-label"
>
bamboo
</span>
<span
class="ant-descriptions-item-content"
>
bamboo
</span>
</div>
</td>
</tr>
<tr
class="ant-descriptions-row"
>
<td
class="ant-descriptions-item"
colspan="1"
>
<div
class="ant-descriptions-item-container"
>
<span
class="ant-descriptions-item-label"
>
bamboo
</span>
<span
class="ant-descriptions-item-content"
>
bamboo
</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
`;
exports[`Descriptions vertical layout 1`] = `
<div
class="ant-descriptions"
>
<div
class="ant-descriptions-view"
>
<table>
<tbody>
<tr
class="ant-descriptions-row"
>
<th
class="ant-descriptions-item"
colspan="1"
>
<div
class="ant-descriptions-item-container"
>
<span
class="ant-descriptions-item-label"
>
Product
</span>
</div>
</th>
</tr>
<tr
class="ant-descriptions-row"
>
<td
class="ant-descriptions-item"
colspan="1"
>
<div
class="ant-descriptions-item-container"
>
<span
class="ant-descriptions-item-content"
>
Cloud Database
</span>
</div>
</td>
</tr>
<tr
class="ant-descriptions-row"
>
<th
class="ant-descriptions-item"
colspan="1"
>
<div
class="ant-descriptions-item-container"
>
<span
class="ant-descriptions-item-label"
>
Billing
</span>
</div>
</th>
</tr>
<tr
class="ant-descriptions-row"
>
<td
class="ant-descriptions-item"
colspan="1"
>
<div
class="ant-descriptions-item-container"
>
<span
class="ant-descriptions-item-content"
>
Prepaid
</span>
</div>
</td>
</tr>
<tr
class="ant-descriptions-row"
>
<th
class="ant-descriptions-item"
colspan="1"
>
<div
class="ant-descriptions-item-container"
>
<span
class="ant-descriptions-item-label"
>
time
</span>
</div>
</th>
</tr>
<tr
class="ant-descriptions-row"
>
<td
class="ant-descriptions-item"
colspan="1"
>
<div
class="ant-descriptions-item-container"
>
<span
class="ant-descriptions-item-content"
>
18:00:00
</span>
</div>
</td>
</tr>
<tr
class="ant-descriptions-row"
>
<th
class="ant-descriptions-item"
colspan="1"
>
<div
class="ant-descriptions-item-container"
>
<span
class="ant-descriptions-item-label"
>
Amount
</span>
</div>
</th>
</tr>
<tr
class="ant-descriptions-row"
>
<td
class="ant-descriptions-item"
colspan="1"
>
<div
class="ant-descriptions-item-container"
>
<span
class="ant-descriptions-item-content"
>
$80.00
</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
`;
exports[`Descriptions when item is rendered conditionally 1`] = `
<div
class="ant-descriptions"
>
<div
class="ant-descriptions-view"
>
<table>
<tbody>
<tr
class="ant-descriptions-row"
>
<td
class="ant-descriptions-item"
colspan="1"
>
<div
class="ant-descriptions-item-container"
>
<span
class="ant-descriptions-item-label"
>
Product
</span>
<span
class="ant-descriptions-item-content"
>
Cloud Database
</span>
</div>
</td>
</tr>
<tr
class="ant-descriptions-row"
>
<td
class="ant-descriptions-item"
colspan="1"
>
<div
class="ant-descriptions-item-container"
>
<span
class="ant-descriptions-item-label"
>
Billing
</span>
<span
class="ant-descriptions-item-content"
>
Prepaid
</span>
</div>
</td>
</tr>
<tr
class="ant-descriptions-row"
>
<td
class="ant-descriptions-item"
colspan="1"
>
<div
class="ant-descriptions-item-container"
>
<span
class="ant-descriptions-item-label"
>
time
</span>
<span
class="ant-descriptions-item-content"
>
18:00:00
</span>
</div>
</td>
</tr>
<tr
class="ant-descriptions-row"
>
<td
class="ant-descriptions-item"
colspan="1"
>
<div
class="ant-descriptions-item-container"
>
<span
class="ant-descriptions-item-label"
>
Amount
</span>
<span
class="ant-descriptions-item-content"
>
$80.00
</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
`;
| components/descriptions/__tests__/__snapshots__/index.test.js.snap | 0 | https://github.com/ant-design/ant-design/commit/684248c52a648faf572640e881cea00127d67101 | [
0.00017543851572554559,
0.00017083623970393091,
0.00016600046365056187,
0.0001712170778773725,
0.00000219342791751842
] |
{
"id": 2,
"code_window": [
" .@{pagination-prefix-cls}-rtl & {\n",
" margin-right: 0;\n",
" margin-left: 8px;\n",
" }\n",
" }\n",
" }\n",
"\n",
" &-simple &-simple-pager {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" &-quick-jumper {\n",
" margin-left: 0;\n",
" }\n"
],
"file_path": "components/pagination/style/rtl.less",
"type": "add",
"edit_start_line_idx": 52
} | @import '../../style/themes/index';
@import '../../style/mixins/index';
@import '../../input/style/mixin';
@pagination-prefix-cls: ~'@{ant-prefix}-pagination';
.@{pagination-prefix-cls} {
&-rtl {
direction: rtl;
}
&-total-text {
.@{pagination-prefix-cls}-rtl & {
margin-right: 0;
margin-left: 8px;
}
}
&-item {
.@{pagination-prefix-cls}-rtl & {
margin-right: 0;
margin-left: 8px;
}
}
&-prev,
&-jump-prev,
&-jump-next {
.@{pagination-prefix-cls}-rtl & {
margin-right: 0;
margin-left: 8px;
}
}
&-slash {
.@{pagination-prefix-cls}-rtl & {
margin: 0 5px 0 10px;
}
}
&-options {
.@{pagination-prefix-cls}-rtl & {
margin-right: 16px;
margin-left: 0;
}
&-size-changer.@{ant-prefix}-select {
.@{pagination-prefix-cls}-rtl & {
margin-right: 0;
margin-left: 8px;
}
}
}
&-simple &-simple-pager {
.@{pagination-prefix-cls}-rtl& {
margin-right: 0;
margin-left: 8px;
}
input {
.@{pagination-prefix-cls}-rtl& {
margin-right: 0;
margin-left: 8px;
}
}
}
&.mini &-options {
.@{pagination-prefix-cls}-rtl& {
margin-right: 2px;
margin-left: 0;
}
}
}
| components/pagination/style/rtl.less | 1 | https://github.com/ant-design/ant-design/commit/684248c52a648faf572640e881cea00127d67101 | [
0.9971641898155212,
0.15764576196670532,
0.000751483952626586,
0.033707987517118454,
0.3189477324485779
] |
{
"id": 2,
"code_window": [
" .@{pagination-prefix-cls}-rtl & {\n",
" margin-right: 0;\n",
" margin-left: 8px;\n",
" }\n",
" }\n",
" }\n",
"\n",
" &-simple &-simple-pager {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" &-quick-jumper {\n",
" margin-left: 0;\n",
" }\n"
],
"file_path": "components/pagination/style/rtl.less",
"type": "add",
"edit_start_line_idx": 52
} | import * as React from 'react';
import { GenerateConfig } from 'rc-picker/lib/generate';
import { Locale } from 'rc-picker/lib/interface';
import Select from '../select';
import { Group, Button } from '../radio';
import { CalendarMode } from './generateCalendar';
const YearSelectOffset = 10;
const YearSelectTotal = 20;
interface SharedProps<DateType> {
prefixCls: string;
value: DateType;
validRange?: [DateType, DateType];
generateConfig: GenerateConfig<DateType>;
locale: Locale;
fullscreen: boolean;
divRef: React.RefObject<HTMLDivElement>;
onChange: (year: DateType) => void;
}
function YearSelect<DateType>(props: SharedProps<DateType>) {
const {
fullscreen,
validRange,
generateConfig,
locale,
prefixCls,
value,
onChange,
divRef,
} = props;
const year = generateConfig.getYear(value);
let start = year - YearSelectOffset;
let end = start + YearSelectTotal;
if (validRange) {
start = generateConfig.getYear(validRange[0]);
end = generateConfig.getYear(validRange[1]) + 1;
}
const suffix = locale && locale.year === '年' ? '年' : '';
const options: { label: string; value: number }[] = [];
for (let index = start; index < end; index++) {
options.push({ label: `${index}${suffix}`, value: index });
}
return (
<Select
size={fullscreen ? undefined : 'small'}
options={options}
value={year}
className={`${prefixCls}-year-select`}
onChange={numYear => {
let newDate = generateConfig.setYear(value, numYear);
if (validRange) {
const [startDate, endDate] = validRange;
const newYear = generateConfig.getYear(newDate);
const newMonth = generateConfig.getMonth(newDate);
if (
newYear === generateConfig.getYear(endDate) &&
newMonth > generateConfig.getMonth(endDate)
) {
newDate = generateConfig.setMonth(newDate, generateConfig.getMonth(endDate));
}
if (
newYear === generateConfig.getYear(startDate) &&
newMonth < generateConfig.getMonth(startDate)
) {
newDate = generateConfig.setMonth(newDate, generateConfig.getMonth(startDate));
}
}
onChange(newDate);
}}
getPopupContainer={() => divRef!.current!}
/>
);
}
function MonthSelect<DateType>(props: SharedProps<DateType>) {
const {
prefixCls,
fullscreen,
validRange,
value,
generateConfig,
locale,
onChange,
divRef,
} = props;
const month = generateConfig.getMonth(value);
let start = 0;
let end = 11;
if (validRange) {
const [rangeStart, rangeEnd] = validRange;
const currentYear = generateConfig.getYear(value);
if (generateConfig.getYear(rangeEnd) === currentYear) {
end = generateConfig.getMonth(rangeEnd);
}
if (generateConfig.getYear(rangeStart) === currentYear) {
start = generateConfig.getMonth(rangeStart);
}
}
const months = locale.shortMonths || generateConfig.locale.getShortMonths!(locale.locale);
const options: { label: string; value: number }[] = [];
for (let index = start; index <= end; index += 1) {
options.push({
label: months[index],
value: index,
});
}
return (
<Select
size={fullscreen ? undefined : 'small'}
className={`${prefixCls}-month-select`}
value={month}
options={options}
onChange={newMonth => {
onChange(generateConfig.setMonth(value, newMonth));
}}
getPopupContainer={() => divRef!.current!}
/>
);
}
interface ModeSwitchProps<DateType> extends Omit<SharedProps<DateType>, 'onChange'> {
mode: CalendarMode;
onModeChange: (type: CalendarMode) => void;
}
function ModeSwitch<DateType>(props: ModeSwitchProps<DateType>) {
const { prefixCls, locale, mode, fullscreen, onModeChange } = props;
return (
<Group
onChange={({ target: { value } }) => {
onModeChange(value);
}}
value={mode}
size={fullscreen ? undefined : 'small'}
className={`${prefixCls}-mode-switch`}
>
<Button value="month">{locale.month}</Button>
<Button value="year">{locale.year}</Button>
</Group>
);
}
export interface CalendarHeaderProps<DateType> {
prefixCls: string;
value: DateType;
validRange?: [DateType, DateType];
generateConfig: GenerateConfig<DateType>;
locale: Locale;
mode: CalendarMode;
fullscreen: boolean;
onChange: (date: DateType) => void;
onModeChange: (mode: CalendarMode) => void;
}
function CalendarHeader<DateType>(props: CalendarHeaderProps<DateType>) {
const { prefixCls, fullscreen, mode, onChange, onModeChange } = props;
const divRef = React.useRef<HTMLDivElement>(null);
const sharedProps = {
...props,
onChange,
fullscreen,
divRef,
};
return (
<div className={`${prefixCls}-header`} ref={divRef}>
<YearSelect {...sharedProps} />
{mode === 'month' && <MonthSelect {...sharedProps} />}
<ModeSwitch {...sharedProps} onModeChange={onModeChange} />
</div>
);
}
export default CalendarHeader;
| components/calendar/Header.tsx | 0 | https://github.com/ant-design/ant-design/commit/684248c52a648faf572640e881cea00127d67101 | [
0.00032854697201400995,
0.00019878719467669725,
0.0001630916667636484,
0.00017548637697473168,
0.0000468089638161473
] |
{
"id": 2,
"code_window": [
" .@{pagination-prefix-cls}-rtl & {\n",
" margin-right: 0;\n",
" margin-left: 8px;\n",
" }\n",
" }\n",
" }\n",
"\n",
" &-simple &-simple-pager {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" &-quick-jumper {\n",
" margin-left: 0;\n",
" }\n"
],
"file_path": "components/pagination/style/rtl.less",
"type": "add",
"edit_start_line_idx": 52
} | ---
order: 3
title:
zh-CN: 带徽标的头像
en-US: With Badge
---
## zh-CN
通常用于消息提示。
## en-US
Usually used for reminders and notifications.
```tsx
import { Avatar, Badge } from 'antd';
import { UserOutlined } from '@ant-design/icons';
ReactDOM.render(
<>
<span className="avatar-item">
<Badge count={1}>
<Avatar shape="square" icon={<UserOutlined />} />
</Badge>
</span>
<span>
<Badge dot>
<Avatar shape="square" icon={<UserOutlined />} />
</Badge>
</span>
</>,
mountNode,
);
```
```css
/* tile uploaded pictures */
.avatar-item {
margin-right: 24px;
}
[class*='-col-rtl'] .avatar-item {
margin-right: 0;
margin-left: 24px;
}
```
| components/avatar/demo/badge.md | 0 | https://github.com/ant-design/ant-design/commit/684248c52a648faf572640e881cea00127d67101 | [
0.00020558708638418466,
0.0001846841914812103,
0.00017338964971713722,
0.0001773934782249853,
0.000012172433343948796
] |
{
"id": 2,
"code_window": [
" .@{pagination-prefix-cls}-rtl & {\n",
" margin-right: 0;\n",
" margin-left: 8px;\n",
" }\n",
" }\n",
" }\n",
"\n",
" &-simple &-simple-pager {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" &-quick-jumper {\n",
" margin-left: 0;\n",
" }\n"
],
"file_path": "components/pagination/style/rtl.less",
"type": "add",
"edit_start_line_idx": 52
} | ---
category: Design Patterns
type: Principles
order: 8
title: Provide an Invitation
---
A common problem with many of these rich interactions (e.g. Drag and Drop, Inline Editing, and Contextual Tools) is their lack of discoverability. Providing an invitation to the user is one of the keys to successful interactive interfaces.
Invitations are the prompts and cues that lead users through an interaction. They often include just-in-time tips or visual affordances that hint at what will happen next in the interface.
> **Signifiers** are signals, communication devices. These signs tell you about the possible actions; what to do, and where to do it. Signifiers are often visible, audible or tangible, from the Design of Everyday Things.
> **Affordances** are the relationships (read: possible actions) between an object and an entity (most often a person). The presence of an affordance is determined by the properties of the object and of the abilities of the entity who's interacting with the object, from the Design of Everyday Things.
---
## Static Invitations
By providing cues for interaction directly on the page we can statically indicate to the user the expected interface behavior. Static Invitations provide cues directly on the page.
<br>
<img class="preview-img" align="right" alt="example of Text Invitation" src="https://gw.alipayobjects.com/zos/rmsportal/ZeMSbCHmvWETbssJHRvo.png">
<img class="preview-img" align="right" alt="example of Blank Slate Invitation" src="https://gw.alipayobjects.com/zos/rmsportal/PHxVAFKncyXDCFUJInbB.png">
<img class="preview-img" align="right" alt="example of Unfinished Invitation" src="https://gw.alipayobjects.com/zos/rmsportal/ChvxJAQTwWbqzBnUBLec.png">
Call to Action Invitations are generally provided as static instructions on the page. But visually they can be provided in many different ways such as Text Invitation, Blank Slate Invitation and Unfinished Invitation.
<br>
<img class="preview-img" align="right" alt="example 1 of Tour Invitation" description="A few of tour points are provided when the user first logs in. Clicking the 'Got It' button leads the user to the next tour step." src="https://gw.alipayobjects.com/zos/rmsportal/dMrVeJJiaCLzoYfJrJKe.png">
Tour invitation can be a nice way to explain design changes to a web application, especially for a well-designed interface. But providing tours will not solve the real problems an interface may have during interaction.
> Note that make Tour Invitations short and simple, easy to exit, and clear to restart.
<br>
---
## Dynamic Invitations
Dynamic Invitations engage users at the point of the interaction and guide them through the next step of interaction.
<br>
<img class="preview-img" align="right" alt="example 1 of Hover Invitation" description="During mouse hover on the whole card, the clickable parts turn to blue hypertext." src="https://gw.alipayobjects.com/zos/rmsportal/ejvYAogJXLPqoMUqyvIV.png">
<img class="preview-img" align="right" alt="example 2 of Hover Invitation" description="During mouse hover, the button of "Select this Template" appears." src="https://gw.alipayobjects.com/zos/rmsportal/umGVwLlIJSmxaQXcjlbh.png">
Hover Invitation: Provide an invitation during mouse hover.
<br>
<img class="preview-img" align="right" alt="example of Inference Invitation" description="The system predicts that the user's interest in an article extends to a type of articles, and it provides an invitation after the user click "like"." src="https://gw.alipayobjects.com/zos/rmsportal/iuLdCuNQWCvYuTxxQUuL.png">
Inference Invitation: Use visual inferences during interaction to cue users as to what the system has inferred about their intent.
<br>
<img class="preview-img" align="right" alt="example of More Content Invitation" description="Use the left or right arrows to switch more content around Modal." src="https://os.alipayobjects.com/rmsportal/sOqYOydwQjLHqph.png">
More Content Invitation: Indicate that there is more content on the page.
<br>
| docs/spec/invitation.en-US.md | 0 | https://github.com/ant-design/ant-design/commit/684248c52a648faf572640e881cea00127d67101 | [
0.00017526814190205187,
0.0001688387565081939,
0.00016253899957519025,
0.0001677680411376059,
0.000004225307293381775
] |
{
"id": 0,
"code_window": [
"# specific language governing permissions and limitations\n",
"# under the License.\n",
"-r base.in\n",
"flask-cors>=2.0.0\n",
"mysqlclient>=2.1.0\n",
"pillow>=8.3.2,<9\n",
"pydruid>=0.6.1,<0.7\n",
"pyhive[hive]>=0.6.1\n",
"psycopg2-binary==2.9.1\n",
"tableschema\n",
"thrift>=0.11.0,<1.0.0\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"pillow>=8.3.2,<10\n"
],
"file_path": "requirements/development.in",
"type": "replace",
"edit_start_line_idx": 20
} | # SHA1:7a8e256097b4758bdeda2529d3d4d31e421e1a3c
#
# This file is autogenerated by pip-compile-multi
# To update, run:
#
# pip-compile-multi
#
-r development.txt
-r integration.txt
-e file:.
# via
# -r requirements/base.in
# -r requirements/testing.in
astroid==2.6.6
# via pylint
backcall==0.2.0
# via ipython
cachetools==4.2.4
# via google-auth
coverage==5.5
# via pytest-cov
decorator==5.0.9
# via
# ipdb
# ipython
docker==5.0.0
# via -r requirements/testing.in
flask-testing==0.8.1
# via -r requirements/testing.in
freezegun==1.1.0
# via -r requirements/testing.in
google-api-core[grpc]==2.2.1
# via
# google-cloud-bigquery
# google-cloud-bigquery-storage
# google-cloud-core
# pybigquery
google-auth==2.2.1
# via
# google-api-core
# google-auth-oauthlib
# google-cloud-core
# pandas-gbq
# pybigquery
# pydata-google-auth
google-auth-oauthlib==0.4.6
# via
# pandas-gbq
# pydata-google-auth
google-cloud-bigquery[bqstorage,pandas]==2.29.0
# via
# -r requirements/testing.in
# apache-superset
# pandas-gbq
# pybigquery
google-cloud-bigquery-storage==2.9.1
# via google-cloud-bigquery
google-cloud-core==2.1.0
# via google-cloud-bigquery
google-crc32c==1.3.0
# via google-resumable-media
google-resumable-media==2.1.0
# via google-cloud-bigquery
googleapis-common-protos==1.53.0
# via
# google-api-core
# grpcio-status
grpcio==1.41.1
# via
# google-api-core
# google-cloud-bigquery
# grpcio-status
grpcio-status==1.41.1
# via google-api-core
iniconfig==1.1.1
# via pytest
ipdb==0.13.9
# via -r requirements/testing.in
ipython==7.26.0
# via
# -r requirements/testing.in
# ipdb
ipython-genutils==0.2.0
# via traitlets
isort==5.9.3
# via pylint
jedi==0.18.0
# via ipython
lazy-object-proxy==1.6.0
# via astroid
libcst==0.3.21
# via google-cloud-bigquery-storage
matplotlib-inline==0.1.2
# via ipython
mccabe==0.6.1
# via pylint
mypy-extensions==0.4.3
# via typing-inspect
oauthlib==3.1.1
# via requests-oauthlib
openapi-schema-validator==0.1.5
# via openapi-spec-validator
openapi-spec-validator==0.3.1
# via -r requirements/testing.in
pandas-gbq==0.15.0
# via
# -r requirements/testing.in
# apache-superset
parameterized==0.8.1
# via -r requirements/testing.in
parso==0.8.2
# via jedi
pexpect==4.8.0
# via ipython
pickleshare==0.7.5
# via ipython
prompt-toolkit==3.0.19
# via ipython
proto-plus==1.19.7
# via
# google-cloud-bigquery
# google-cloud-bigquery-storage
protobuf==3.19.1
# via
# google-api-core
# google-cloud-bigquery
# googleapis-common-protos
# grpcio-status
# proto-plus
ptyprocess==0.7.0
# via pexpect
pyasn1==0.4.8
# via
# pyasn1-modules
# rsa
pyasn1-modules==0.2.8
# via google-auth
pybigquery==0.10.2
# via
# -r requirements/testing.in
# apache-superset
pydata-google-auth==1.2.0
# via pandas-gbq
pyfakefs==4.5.0
# via -r requirements/testing.in
pygments==2.9.0
# via ipython
pyhive[hive,presto]==0.6.4
# via
# -r requirements/development.in
# -r requirements/testing.in
pylint==2.9.6
# via -r requirements/testing.in
pytest==6.2.4
# via
# -r requirements/testing.in
# pytest-cov
# pytest-mock
pytest-cov==2.12.1
# via -r requirements/testing.in
pytest-mock==3.6.1
# via -r requirements/testing.in
requests-oauthlib==1.3.0
# via google-auth-oauthlib
rsa==4.7.2
# via google-auth
sqlalchemy-trino==0.4.1
# via apache-superset
statsd==3.3.0
# via -r requirements/testing.in
traitlets==5.0.5
# via
# ipython
# matplotlib-inline
trino==0.306
# via sqlalchemy-trino
typing-inspect==0.7.1
# via libcst
wcwidth==0.2.5
# via prompt-toolkit
websocket-client==1.2.0
# via docker
# The following packages are considered to be unsafe in a requirements file:
# pip
# setuptools
| requirements/testing.txt | 1 | https://github.com/apache/superset/commit/60db35cb4d8462aeb4121e8a8b9eccee9c23621e | [
0.00022327431361190975,
0.0001712819212116301,
0.00016465358203276992,
0.00016858006711117923,
0.000012462051927286666
] |
{
"id": 0,
"code_window": [
"# specific language governing permissions and limitations\n",
"# under the License.\n",
"-r base.in\n",
"flask-cors>=2.0.0\n",
"mysqlclient>=2.1.0\n",
"pillow>=8.3.2,<9\n",
"pydruid>=0.6.1,<0.7\n",
"pyhive[hive]>=0.6.1\n",
"psycopg2-binary==2.9.1\n",
"tableschema\n",
"thrift>=0.11.0,<1.0.0\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"pillow>=8.3.2,<10\n"
],
"file_path": "requirements/development.in",
"type": "replace",
"edit_start_line_idx": 20
} | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/* eslint-disable sort-keys */
export default [
{
name: 'Michael',
sum__num: 2467129,
},
{
name: 'Christopher',
sum__num: 1725328,
},
{
name: 'David',
sum__num: 1570516,
},
{
name: 'James',
sum__num: 1506095,
},
{
name: 'John',
sum__num: 1426074,
},
{
name: 'Matthew',
sum__num: 1355877,
},
{
name: 'Jennifer',
sum__num: 1335587,
},
{
name: 'Robert',
sum__num: 1314800,
},
{
name: 'Daniel',
sum__num: 1159354,
},
{
name: 'Joseph',
sum__num: 1114167,
},
{
name: 'William',
sum__num: 1113793,
},
{
name: 'Joshua',
sum__num: 1073440,
},
{
name: 'Jessica',
sum__num: 997179,
},
{
name: 'Jason',
sum__num: 955817,
},
{
name: 'Andrew',
sum__num: 926315,
},
{
name: 'Anthony',
sum__num: 878978,
},
{
name: 'Brian',
sum__num: 874868,
},
{
name: 'Ryan',
sum__num: 816288,
},
{
name: 'Kevin',
sum__num: 791084,
},
{
name: 'Ashley',
sum__num: 789363,
},
{
name: 'Thomas',
sum__num: 746589,
},
{
name: 'Sarah',
sum__num: 744956,
},
{
name: 'Nicholas',
sum__num: 728617,
},
{
name: 'Amanda',
sum__num: 719676,
},
{
name: 'Elizabeth',
sum__num: 712676,
},
{
name: 'Justin',
sum__num: 704646,
},
{
name: 'Jacob',
sum__num: 700755,
},
{
name: 'Eric',
sum__num: 700518,
},
{
name: 'Jonathan',
sum__num: 691938,
},
{
name: 'Brandon',
sum__num: 682546,
},
{
name: 'Melissa',
sum__num: 664648,
},
{
name: 'Steven',
sum__num: 659750,
},
{
name: 'Michelle',
sum__num: 659302,
},
{
name: 'Richard',
sum__num: 652854,
},
{
name: 'Kimberly',
sum__num: 647609,
},
{
name: 'Timothy',
sum__num: 632770,
},
{
name: 'Stephanie',
sum__num: 628138,
},
{
name: 'Emily',
sum__num: 614741,
},
{
name: 'Lisa',
sum__num: 606540,
},
{
name: 'Mark',
sum__num: 589103,
},
{
name: 'Jeffrey',
sum__num: 557562,
},
{
name: 'Amy',
sum__num: 556835,
},
{
name: 'Charles',
sum__num: 556124,
},
{
name: 'Nicole',
sum__num: 545099,
},
{
name: 'Tyler',
sum__num: 499814,
},
{
name: 'Angela',
sum__num: 496228,
},
{
name: 'Samantha',
sum__num: 484266,
},
{
name: 'Benjamin',
sum__num: 482709,
},
{
name: 'Heather',
sum__num: 481474,
},
{
name: 'Scott',
sum__num: 469933,
},
{
name: 'Rebecca',
sum__num: 466847,
},
{
name: 'Adam',
sum__num: 459794,
},
{
name: 'Mary',
sum__num: 459471,
},
{
name: 'Zachary',
sum__num: 459381,
},
{
name: 'Aaron',
sum__num: 453035,
},
{
name: 'Rachel',
sum__num: 444351,
},
{
name: 'Alexander',
sum__num: 438239,
},
{
name: 'Paul',
sum__num: 411513,
},
{
name: 'Kyle',
sum__num: 409644,
},
{
name: 'Laura',
sum__num: 408963,
},
{
name: 'Lauren',
sum__num: 403946,
},
{
name: 'Megan',
sum__num: 402100,
},
{
name: 'Nathan',
sum__num: 393793,
},
{
name: 'Samuel',
sum__num: 390363,
},
{
name: 'Christina',
sum__num: 387580,
},
{
name: 'Kelly',
sum__num: 384611,
},
{
name: 'Jordan',
sum__num: 382963,
},
{
name: 'Patrick',
sum__num: 382673,
},
{
name: 'Jeremy',
sum__num: 381171,
},
{
name: 'Jose',
sum__num: 377759,
},
{
name: 'Stephen',
sum__num: 374269,
},
{
name: 'Sean',
sum__num: 366228,
},
{
name: 'Kenneth',
sum__num: 361043,
},
{
name: 'Gregory',
sum__num: 334166,
},
{
name: 'Brittany',
sum__num: 333252,
},
{
name: 'Amber',
sum__num: 331563,
},
{
name: 'Katherine',
sum__num: 329873,
},
{
name: 'Hannah',
sum__num: 329227,
},
{
name: 'Taylor',
sum__num: 327602,
},
{
name: 'Danielle',
sum__num: 322578,
},
{
name: 'Andrea',
sum__num: 318796,
},
{
name: 'Austin',
sum__num: 314059,
},
{
name: 'Tiffany',
sum__num: 301753,
},
{
name: 'Kayla',
sum__num: 291858,
},
{
name: 'Christian',
sum__num: 288189,
},
{
name: 'Maria',
sum__num: 287870,
},
{
name: 'Alexis',
sum__num: 286496,
},
{
name: 'Bryan',
sum__num: 282841,
},
{
name: 'Victoria',
sum__num: 277371,
},
{
name: 'Julie',
sum__num: 270542,
},
{
name: 'Shannon',
sum__num: 266886,
},
{
name: 'Christine',
sum__num: 264122,
},
{
name: 'Sara',
sum__num: 263050,
},
{
name: 'Erin',
sum__num: 262817,
},
{
name: 'Madison',
sum__num: 262812,
},
{
name: 'Crystal',
sum__num: 262697,
},
{
name: 'Karen',
sum__num: 257961,
},
{
name: 'Anna',
sum__num: 256136,
},
{
name: 'Dylan',
sum__num: 250778,
},
{
name: 'Edward',
sum__num: 248689,
},
];
| superset-frontend/packages/superset-ui-demo/storybook/stories/plugins/plugin-chart-word-cloud/data.ts | 0 | https://github.com/apache/superset/commit/60db35cb4d8462aeb4121e8a8b9eccee9c23621e | [
0.00017734357970766723,
0.00017583240696694702,
0.00016590268933214247,
0.0001763453328749165,
0.0000018337510709898197
] |
{
"id": 0,
"code_window": [
"# specific language governing permissions and limitations\n",
"# under the License.\n",
"-r base.in\n",
"flask-cors>=2.0.0\n",
"mysqlclient>=2.1.0\n",
"pillow>=8.3.2,<9\n",
"pydruid>=0.6.1,<0.7\n",
"pyhive[hive]>=0.6.1\n",
"psycopg2-binary==2.9.1\n",
"tableschema\n",
"thrift>=0.11.0,<1.0.0\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"pillow>=8.3.2,<10\n"
],
"file_path": "requirements/development.in",
"type": "replace",
"edit_start_line_idx": 20
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
| superset/databases/commands/__init__.py | 0 | https://github.com/apache/superset/commit/60db35cb4d8462aeb4121e8a8b9eccee9c23621e | [
0.00017030900926329195,
0.0001667477044975385,
0.00016318639973178506,
0.0001667477044975385,
0.000003561304765753448
] |
{
"id": 0,
"code_window": [
"# specific language governing permissions and limitations\n",
"# under the License.\n",
"-r base.in\n",
"flask-cors>=2.0.0\n",
"mysqlclient>=2.1.0\n",
"pillow>=8.3.2,<9\n",
"pydruid>=0.6.1,<0.7\n",
"pyhive[hive]>=0.6.1\n",
"psycopg2-binary==2.9.1\n",
"tableschema\n",
"thrift>=0.11.0,<1.0.0\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"pillow>=8.3.2,<10\n"
],
"file_path": "requirements/development.in",
"type": "replace",
"edit_start_line_idx": 20
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Unit tests for alerting in Superset"""
import json
import logging
from contextlib import contextmanager
from unittest.mock import patch
import pytest
from flask_appbuilder.security.sqla.models import Role
from superset.extensions import db, security_manager
from superset.migrations.shared.security_converge import (
add_pvms,
migrate_roles,
Pvm,
PvmMigrationMapType,
)
from tests.integration_tests.test_app import app
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@contextmanager
def create_old_role(pvm_map: PvmMigrationMapType, external_pvms):
with app.app_context():
pvms = []
for old_pvm, new_pvms in pvm_map.items():
pvms.append(
security_manager.add_permission_view_menu(
old_pvm.permission, old_pvm.view
)
)
for external_pvm in external_pvms:
pvms.append(
security_manager.find_permission_view_menu(
external_pvm.permission, external_pvm.view
)
)
new_role = Role(name="Dummy Role", permissions=pvms)
db.session.add(new_role)
db.session.commit()
yield new_role
new_role = (
db.session.query(Role).filter(Role.name == "Dummy Role").one_or_none()
)
new_role.permissions = []
db.session.merge(new_role)
for old_pvm, new_pvms in pvm_map.items():
security_manager.del_permission_view_menu(old_pvm.permission, old_pvm.view)
for new_pvm in new_pvms:
security_manager.del_permission_view_menu(
new_pvm.permission, new_pvm.view
)
db.session.delete(new_role)
db.session.commit()
@pytest.mark.parametrize(
"descriptiom, new_pvms, pvm_map, external_pvms, deleted_views, deleted_permissions",
[
(
"Many to one readonly",
{"NewDummy": ("can_read",)},
{
Pvm("DummyView", "can_list"): (Pvm("NewDummy", "can_read"),),
Pvm("DummyView", "can_show"): (Pvm("NewDummy", "can_read"),),
},
(),
("DummyView",),
(),
),
(
"Many to one with new permission",
{"NewDummy": ("can_new_perm", "can_write")},
{
Pvm("DummyView", "can_list"): (Pvm("NewDummy", "can_new_perm"),),
Pvm("DummyView", "can_show"): (Pvm("NewDummy", "can_write"),),
},
(),
("DummyView",),
(),
),
(
"Many to one with multiple permissions",
{"NewDummy": ("can_read", "can_write",)},
{
Pvm("DummyView", "can_list"): (Pvm("NewDummy", "can_read"),),
Pvm("DummyView", "can_show"): (Pvm("NewDummy", "can_read"),),
Pvm("DummyView", "can_add"): (Pvm("NewDummy", "can_write"),),
Pvm("DummyView", "can_delete"): (Pvm("NewDummy", "can_write"),),
},
(),
("DummyView",),
(),
),
(
"Many to one with multiple views",
{"NewDummy": ("can_read", "can_write",)},
{
Pvm("DummyView", "can_list"): (Pvm("NewDummy", "can_read"),),
Pvm("DummyView", "can_show"): (Pvm("NewDummy", "can_read"),),
Pvm("DummyView", "can_add"): (Pvm("NewDummy", "can_write"),),
Pvm("DummyView", "can_delete"): (Pvm("NewDummy", "can_write"),),
Pvm("DummySecondView", "can_list"): (Pvm("NewDummy", "can_read"),),
Pvm("DummySecondView", "can_show"): (Pvm("NewDummy", "can_read"),),
Pvm("DummySecondView", "can_add"): (Pvm("NewDummy", "can_write"),),
Pvm("DummySecondView", "can_delete"): (Pvm("NewDummy", "can_write"),),
},
(),
("DummyView", "DummySecondView"),
(),
),
(
"Many to one with existing permission-view (pvm)",
{"NewDummy": ("can_read", "can_write",)},
{
Pvm("DummyView", "can_list"): (Pvm("NewDummy", "can_read"),),
Pvm("DummyView", "can_add"): (Pvm("NewDummy", "can_write"),),
},
(Pvm("UserDBModelView", "can_list"),),
("DummyView",),
(),
),
(
"Many to one with existing multiple permission-view (pvm)",
{"NewDummy": ("can_read", "can_write",)},
{
Pvm("DummyView", "can_list"): (Pvm("NewDummy", "can_read"),),
Pvm("DummyView", "can_add"): (Pvm("NewDummy", "can_write"),),
Pvm("DummySecondView", "can_list"): (Pvm("NewDummy", "can_read"),),
Pvm("DummySecondView", "can_add"): (Pvm("NewDummy", "can_write"),),
},
(Pvm("UserDBModelView", "can_list"), Pvm("UserDBModelView", "can_add"),),
("DummyView",),
(),
),
(
"Many to one with with old permission that gets deleted",
{"NewDummy": ("can_read", "can_write",)},
{
Pvm("DummyView", "can_new_perm"): (Pvm("NewDummy", "can_read"),),
Pvm("DummyView", "can_add"): (Pvm("NewDummy", "can_write"),),
},
(),
("DummyView",),
("can_new_perm",),
),
(
"Many to Many (normally should be a downgrade)",
{"DummyView": ("can_list", "can_show", "can_add",)},
{
Pvm("NewDummy", "can_read"): (
Pvm("DummyView", "can_list"),
Pvm("DummyView", "can_show"),
),
Pvm("NewDummy", "can_write"): (Pvm("DummyView", "can_add"),),
},
(),
("NewDummy",),
(),
),
(
"Many to Many delete old permissions",
{"DummyView": ("can_list", "can_show", "can_add",)},
{
Pvm("NewDummy", "can_new_perm1"): (
Pvm("DummyView", "can_list"),
Pvm("DummyView", "can_show"),
),
Pvm("NewDummy", "can_new_perm2",): (Pvm("DummyView", "can_add"),),
},
(),
("NewDummy",),
("can_new_perm1", "can_new_perm2"),
),
],
)
def test_migrate_role(
descriptiom, new_pvms, pvm_map, external_pvms, deleted_views, deleted_permissions
):
"""
Permission migration: generic tests
"""
logger.info(descriptiom)
with create_old_role(pvm_map, external_pvms) as old_role:
role_name = old_role.name
session = db.session
# Run migrations
add_pvms(session, new_pvms)
migrate_roles(session, pvm_map)
role = db.session.query(Role).filter(Role.name == role_name).one_or_none()
for old_pvm, new_pvms in pvm_map.items():
old_pvm_model = security_manager.find_permission_view_menu(
old_pvm.permission, old_pvm.view
)
assert old_pvm_model is None
new_pvm_model = security_manager.find_permission_view_menu(
new_pvms[0].permission, new_pvms[0].view
)
assert new_pvm_model is not None
assert new_pvm_model in role.permissions
# assert deleted view menus
for deleted_view in deleted_views:
assert security_manager.find_view_menu(deleted_view) is None
# assert deleted permissions
for deleted_permission in deleted_permissions:
assert security_manager.find_permission(deleted_permission) is None
# assert externals are still there
for external_pvm in external_pvms:
assert (
security_manager.find_permission_view_menu(
external_pvm.permission, external_pvm.view
)
is not None
)
| tests/integration_tests/security/migrate_roles_tests.py | 0 | https://github.com/apache/superset/commit/60db35cb4d8462aeb4121e8a8b9eccee9c23621e | [
0.00017531779303681105,
0.0001707104966044426,
0.00016538651834707707,
0.00017014448530972004,
0.000002613110609672731
] |
{
"id": 1,
"code_window": [
"# SHA1:c835350e502151c63817980505ce50b9e5b78a54\n",
"#\n",
"# This file is autogenerated by pip-compile-multi\n",
"# To update, run:\n",
"#\n"
],
"labels": [
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"# SHA1:cb189e676baa2e397294abb48eaefba5bf408522\n"
],
"file_path": "requirements/development.txt",
"type": "replace",
"edit_start_line_idx": 0
} | # SHA1:c835350e502151c63817980505ce50b9e5b78a54
#
# This file is autogenerated by pip-compile-multi
# To update, run:
#
# pip-compile-multi
#
-r base.txt
-e file:.
# via -r requirements/base.in
boto3==1.18.19
# via tabulator
botocore==1.21.19
# via
# boto3
# s3transfer
cached-property==1.5.2
# via tableschema
certifi==2021.5.30
# via requests
charset-normalizer==2.0.4
# via requests
et-xmlfile==1.1.0
# via openpyxl
flask-cors==3.0.10
# via -r requirements/development.in
future==0.18.2
# via pyhive
ijson==3.1.4
# via tabulator
jmespath==0.10.0
# via
# boto3
# botocore
jsonlines==2.0.0
# via tabulator
linear-tsv==1.1.0
# via tabulator
mysqlclient==2.1.0
# via -r requirements/development.in
openpyxl==3.0.7
# via tabulator
pillow==8.4.0
# via -r requirements/development.in
progress==1.6
# via -r requirements/development.in
psycopg2-binary==2.9.1
# via -r requirements/development.in
pure-sasl==0.6.2
# via thrift-sasl
pydruid==0.6.2
# via -r requirements/development.in
pyhive[hive]==0.6.4
# via -r requirements/development.in
pyinstrument==4.0.2
# via -r requirements/development.in
requests==2.26.0
# via
# pydruid
# tableschema
# tabulator
rfc3986==1.5.0
# via tableschema
s3transfer==0.5.0
# via boto3
tableschema==1.20.2
# via -r requirements/development.in
tabulator==1.53.5
# via tableschema
thrift==0.13.0
# via
# -r requirements/development.in
# pyhive
# thrift-sasl
thrift-sasl==0.4.3
# via pyhive
unicodecsv==0.14.1
# via
# tableschema
# tabulator
xlrd==2.0.1
# via tabulator
# The following packages are considered to be unsafe in a requirements file:
# setuptools
| requirements/development.txt | 1 | https://github.com/apache/superset/commit/60db35cb4d8462aeb4121e8a8b9eccee9c23621e | [
0.29064705967903137,
0.03244735673069954,
0.00016505741223227233,
0.00016698568651918322,
0.09128737449645996
] |
{
"id": 1,
"code_window": [
"# SHA1:c835350e502151c63817980505ce50b9e5b78a54\n",
"#\n",
"# This file is autogenerated by pip-compile-multi\n",
"# To update, run:\n",
"#\n"
],
"labels": [
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"# SHA1:cb189e676baa2e397294abb48eaefba5bf408522\n"
],
"file_path": "requirements/development.txt",
"type": "replace",
"edit_start_line_idx": 0
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { SupersetClient, logging } from '@superset-ui/core';
import parseCookie from 'src/utils/parseCookie';
export default function setupClient() {
const csrfNode = document.querySelector<HTMLInputElement>('#csrf_token');
const csrfToken = csrfNode?.value;
// when using flask-jwt-extended csrf is set in cookies
const cookieCSRFToken = parseCookie().csrf_access_token || '';
SupersetClient.configure({
protocol: ['http:', 'https:'].includes(window?.location?.protocol)
? (window?.location?.protocol as 'http:' | 'https:')
: undefined,
host: (window.location && window.location.host) || '',
csrfToken: csrfToken || cookieCSRFToken,
})
.init()
.catch(error => {
logging.warn('Error initializing SupersetClient', error);
});
}
| superset-frontend/src/setup/setupClient.ts | 0 | https://github.com/apache/superset/commit/60db35cb4d8462aeb4121e8a8b9eccee9c23621e | [
0.0001729939685901627,
0.0001696347608231008,
0.00016512605361640453,
0.00016950623830780387,
0.000002917371830335469
] |
{
"id": 1,
"code_window": [
"# SHA1:c835350e502151c63817980505ce50b9e5b78a54\n",
"#\n",
"# This file is autogenerated by pip-compile-multi\n",
"# To update, run:\n",
"#\n"
],
"labels": [
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"# SHA1:cb189e676baa2e397294abb48eaefba5bf408522\n"
],
"file_path": "requirements/development.txt",
"type": "replace",
"edit_start_line_idx": 0
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import getInitialState from './getInitialState';
const apiData = {
defaultDbId: 1,
common: {
conf: {
DEFAULT_SQLLAB_LIMIT: 1,
},
},
active_tab: null,
tab_state_ids: [],
databases: [],
queries: [],
requested_query: null,
user: {
userId: 1,
username: 'some name',
},
};
const apiDataWithTabState = {
...apiData,
tab_state_ids: [{ id: 1 }],
active_tab: { id: 1, table_schemas: [] },
};
describe('getInitialState', () => {
it('should output the user that is passed in', () => {
expect(getInitialState(apiData).sqlLab.user.userId).toEqual(1);
});
it('should return undefined instead of null for templateParams', () => {
expect(
getInitialState(apiDataWithTabState).sqlLab.queryEditors[0]
.templateParams,
).toBeUndefined();
});
});
| superset-frontend/src/SqlLab/reducers/getInitialState.test.ts | 0 | https://github.com/apache/superset/commit/60db35cb4d8462aeb4121e8a8b9eccee9c23621e | [
0.00017316709272563457,
0.00017040770035237074,
0.00016790293739177287,
0.00016984608373604715,
0.000001775178816387779
] |
{
"id": 1,
"code_window": [
"# SHA1:c835350e502151c63817980505ce50b9e5b78a54\n",
"#\n",
"# This file is autogenerated by pip-compile-multi\n",
"# To update, run:\n",
"#\n"
],
"labels": [
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"# SHA1:cb189e676baa2e397294abb48eaefba5bf408522\n"
],
"file_path": "requirements/development.txt",
"type": "replace",
"edit_start_line_idx": 0
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import {
DTTM_ALIAS,
extractTimegrain,
getNumberFormatter,
NumberFormats,
QueryFormData,
GenericDataType,
getMetricLabel,
t,
smartDateVerboseFormatter,
NumberFormatter,
TimeFormatter,
} from '@superset-ui/core';
import { EChartsCoreOption, graphic } from 'echarts';
import {
BigNumberDatum,
BigNumberWithTrendlineChartProps,
TimeSeriesDatum,
} from '../types';
import { getDateFormatter, parseMetricValue } from '../utils';
const defaultNumberFormatter = getNumberFormatter();
export function renderTooltipFactory(
formatDate: TimeFormatter = smartDateVerboseFormatter,
formatValue: NumberFormatter | TimeFormatter = defaultNumberFormatter,
) {
return function renderTooltip(params: { data: TimeSeriesDatum }[]) {
return `
${formatDate(params[0].data[0])}
<br />
<strong>
${
params[0].data[1] === null ? t('N/A') : formatValue(params[0].data[1])
}
</strong>
`;
};
}
const formatPercentChange = getNumberFormatter(
NumberFormats.PERCENT_SIGNED_1_POINT,
);
export default function transformProps(
chartProps: BigNumberWithTrendlineChartProps,
) {
const { width, height, queriesData, formData, rawFormData } = chartProps;
const {
colorPicker,
compareLag: compareLag_,
compareSuffix = '',
timeFormat,
headerFontSize,
metric = 'value',
showTimestamp,
showTrendLine,
startYAxisAtZero,
subheader = '',
subheaderFontSize,
forceTimestampFormatting,
yAxisFormat,
timeRangeFixed,
} = formData;
const granularity = extractTimegrain(rawFormData as QueryFormData);
const {
data = [],
colnames = [],
coltypes = [],
from_dttm: fromDatetime,
to_dttm: toDatetime,
} = queriesData[0];
const metricName = getMetricLabel(metric);
const compareLag = Number(compareLag_) || 0;
let formattedSubheader = subheader;
const { r, g, b } = colorPicker;
const mainColor = `rgb(${r}, ${g}, ${b})`;
let trendLineData;
let percentChange = 0;
let bigNumber = data.length === 0 ? null : data[0][metricName];
let timestamp = data.length === 0 ? null : data[0][DTTM_ALIAS];
let bigNumberFallback;
const metricColtypeIndex = colnames.findIndex(name => name === metricName);
const metricColtype =
metricColtypeIndex > -1 ? coltypes[metricColtypeIndex] : null;
if (data.length > 0) {
const sortedData = (data as BigNumberDatum[])
.map(d => [d[DTTM_ALIAS], parseMetricValue(d[metricName])])
// sort in time descending order
.sort((a, b) => (a[0] !== null && b[0] !== null ? b[0] - a[0] : 0));
bigNumber = sortedData[0][1];
timestamp = sortedData[0][0];
if (bigNumber === null) {
bigNumberFallback = sortedData.find(d => d[1] !== null);
bigNumber = bigNumberFallback ? bigNumberFallback[1] : null;
timestamp = bigNumberFallback ? bigNumberFallback[0] : null;
}
if (compareLag > 0) {
const compareIndex = compareLag;
if (compareIndex < sortedData.length) {
const compareValue = sortedData[compareIndex][1];
// compare values must both be non-nulls
if (bigNumber !== null && compareValue !== null && compareValue !== 0) {
percentChange = (bigNumber - compareValue) / Math.abs(compareValue);
formattedSubheader = `${formatPercentChange(
percentChange,
)} ${compareSuffix}`;
}
}
}
sortedData.reverse();
trendLineData = showTrendLine ? sortedData : undefined;
}
let className = '';
if (percentChange > 0) {
className = 'positive';
} else if (percentChange < 0) {
className = 'negative';
}
let metricEntry;
if (chartProps.datasource && chartProps.datasource.metrics) {
metricEntry = chartProps.datasource.metrics.find(
metricEntry => metricEntry.metric_name === metric,
);
}
const formatTime = getDateFormatter(
timeFormat,
granularity,
metricEntry?.d3format,
);
const headerFormatter =
metricColtype === GenericDataType.TEMPORAL ||
metricColtype === GenericDataType.STRING ||
forceTimestampFormatting
? formatTime
: getNumberFormatter(yAxisFormat ?? metricEntry?.d3format ?? undefined);
if (trendLineData && timeRangeFixed && fromDatetime) {
const toDatetimeOrToday = toDatetime ?? Date.now();
if (!trendLineData[0][0] || trendLineData[0][0] > fromDatetime) {
trendLineData.unshift([fromDatetime, null]);
}
if (
!trendLineData[trendLineData.length - 1][0] ||
trendLineData[trendLineData.length - 1][0]! < toDatetimeOrToday
) {
trendLineData.push([toDatetimeOrToday, null]);
}
}
const echartOptions: EChartsCoreOption = trendLineData
? {
series: [
{
data: trendLineData,
type: 'line',
smooth: true,
symbol: 'circle',
showSymbol: false,
color: mainColor,
areaStyle: {
color: new graphic.LinearGradient(0, 0, 0, 1, [
{
offset: 0,
color: mainColor,
},
{
offset: 1,
color: 'white',
},
]),
},
},
],
xAxis: {
min: trendLineData[0][0],
max: trendLineData[trendLineData.length - 1][0],
show: false,
type: 'value',
},
yAxis: {
scale: !startYAxisAtZero,
show: false,
},
grid: {
left: 0,
right: 0,
top: 0,
bottom: 0,
},
tooltip: {
show: true,
trigger: 'axis',
confine: true,
formatter: renderTooltipFactory(formatTime, headerFormatter),
},
aria: {
enabled: true,
label: {
description: `Big number visualization ${subheader}`,
},
},
}
: {};
return {
width,
height,
bigNumber,
bigNumberFallback,
className,
headerFormatter,
formatTime,
headerFontSize,
subheaderFontSize,
mainColor,
showTimestamp,
showTrendLine,
startYAxisAtZero,
subheader: formattedSubheader,
timestamp,
trendLineData,
echartOptions,
};
}
| superset-frontend/plugins/plugin-chart-echarts/src/BigNumber/BigNumberWithTrendline/transformProps.ts | 0 | https://github.com/apache/superset/commit/60db35cb4d8462aeb4121e8a8b9eccee9c23621e | [
0.00017493254563305527,
0.00017027970170602202,
0.0001650733029237017,
0.0001700968132354319,
0.000002276283339597285
] |
{
"id": 2,
"code_window": [
" # via tabulator\n",
"mysqlclient==2.1.0\n",
" # via -r requirements/development.in\n",
"openpyxl==3.0.7\n",
" # via tabulator\n",
"pillow==8.4.0\n",
" # via -r requirements/development.in\n",
"progress==1.6\n",
" # via -r requirements/development.in\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"pillow==9.0.0\n"
],
"file_path": "requirements/development.txt",
"type": "replace",
"edit_start_line_idx": 42
} | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-r base.in
flask-cors>=2.0.0
mysqlclient>=2.1.0
pillow>=8.3.2,<9
pydruid>=0.6.1,<0.7
pyhive[hive]>=0.6.1
psycopg2-binary==2.9.1
tableschema
thrift>=0.11.0,<1.0.0
progress>=1.5,<2
pyinstrument>=4.0.2,<5
| requirements/development.in | 1 | https://github.com/apache/superset/commit/60db35cb4d8462aeb4121e8a8b9eccee9c23621e | [
0.00020828386186622083,
0.00018258998170495033,
0.00016385327035095543,
0.00017563282744958997,
0.000018793985873344354
] |
{
"id": 2,
"code_window": [
" # via tabulator\n",
"mysqlclient==2.1.0\n",
" # via -r requirements/development.in\n",
"openpyxl==3.0.7\n",
" # via tabulator\n",
"pillow==8.4.0\n",
" # via -r requirements/development.in\n",
"progress==1.6\n",
" # via -r requirements/development.in\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"pillow==9.0.0\n"
],
"file_path": "requirements/development.txt",
"type": "replace",
"edit_start_line_idx": 42
} | <!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
# [0.18.0](https://github.com/apache-superset/superset-ui/compare/v0.17.87...v0.18.0) (2021-08-30)
**Note:** Version bump only for package @superset-ui/legacy-plugin-chart-paired-t-test
## [0.17.61](https://github.com/apache-superset/superset-ui/compare/v0.17.60...v0.17.61) (2021-07-02)
**Note:** Version bump only for package @superset-ui/legacy-plugin-chart-paired-t-test
| superset-frontend/plugins/legacy-plugin-chart-paired-t-test/CHANGELOG.md | 0 | https://github.com/apache/superset/commit/60db35cb4d8462aeb4121e8a8b9eccee9c23621e | [
0.00017695069254841655,
0.0001720747968647629,
0.00016780626901891083,
0.00017177112749777734,
0.000003314700734335929
] |
{
"id": 2,
"code_window": [
" # via tabulator\n",
"mysqlclient==2.1.0\n",
" # via -r requirements/development.in\n",
"openpyxl==3.0.7\n",
" # via tabulator\n",
"pillow==8.4.0\n",
" # via -r requirements/development.in\n",
"progress==1.6\n",
" # via -r requirements/development.in\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"pillow==9.0.0\n"
],
"file_path": "requirements/development.txt",
"type": "replace",
"edit_start_line_idx": 42
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import rison from 'rison';
import React, { useCallback } from 'react';
import PropTypes from 'prop-types';
import { Row, Col } from 'src/common/components';
import { Radio } from 'src/components/Radio';
import Card from 'src/components/Card';
import Alert from 'src/components/Alert';
import Badge from 'src/components/Badge';
import shortid from 'shortid';
import { styled, SupersetClient, t, withTheme } from '@superset-ui/core';
import { Select } from 'src/components';
import { FormLabel } from 'src/components/Form';
import Button from 'src/components/Button';
import Tabs from 'src/components/Tabs';
import CertifiedBadge from 'src/components/CertifiedBadge';
import WarningIconWithTooltip from 'src/components/WarningIconWithTooltip';
import DatabaseSelector from 'src/components/DatabaseSelector';
import Label from 'src/components/Label';
import Loading from 'src/components/Loading';
import TableSelector from 'src/components/TableSelector';
import EditableTitle from 'src/components/EditableTitle';
import { getClientErrorObject } from 'src/utils/getClientErrorObject';
import CheckboxControl from 'src/explore/components/controls/CheckboxControl';
import TextControl from 'src/explore/components/controls/TextControl';
import TextAreaControl from 'src/explore/components/controls/TextAreaControl';
import SpatialControl from 'src/explore/components/controls/SpatialControl';
import CollectionTable from 'src/CRUD/CollectionTable';
import Fieldset from 'src/CRUD/Fieldset';
import Field from 'src/CRUD/Field';
import withToasts from 'src/components/MessageToasts/withToasts';
import { FeatureFlag, isFeatureEnabled } from 'src/featureFlags';
import Icons from 'src/components/Icons';
const DatasourceContainer = styled.div`
.change-warning {
margin: 16px 10px 0;
color: ${({ theme }) => theme.colors.warning.base};
}
.change-warning .bold {
font-weight: ${({ theme }) => theme.typography.weights.bold};
}
.form-group.has-feedback > .help-block {
margin-top: 8px;
}
.form-group.form-group-md {
margin-bottom: 8px;
}
`;
const FlexRowContainer = styled.div`
align-items: center;
display: flex;
svg {
margin-right: ${({ theme }) => theme.gridUnit}px;
}
`;
const StyledTableTabs = styled(Tabs)`
overflow: visible;
.ant-tabs-content-holder {
overflow: visible;
}
`;
const StyledBadge = styled(Badge)`
.ant-badge-count {
line-height: ${({ theme }) => theme.gridUnit * 4}px;
height: ${({ theme }) => theme.gridUnit * 4}px;
margin-left: ${({ theme }) => theme.gridUnit}px;
}
`;
const EditLockContainer = styled.div`
font-size: ${({ theme }) => theme.typography.sizes.s}px;
display: flex;
align-items: center;
a {
padding: 0 10px;
}
`;
const ColumnButtonWrapper = styled.div`
text-align: right;
${({ theme }) => `margin-bottom: ${theme.gridUnit * 2}px`}
`;
const StyledLabelWrapper = styled.div`
display: flex;
align-items: center;
span {
margin-right: ${({ theme }) => theme.gridUnit}px;
}
`;
const StyledColumnsTabWrapper = styled.div`
.table > tbody > tr > td {
vertical-align: middle;
}
.ant-tag {
margin-top: ${({ theme }) => theme.gridUnit}px;
}
`;
const checkboxGenerator = (d, onChange) => (
<CheckboxControl value={d} onChange={onChange} />
);
const DATA_TYPES = [
{ value: 'STRING', label: 'STRING' },
{ value: 'NUMERIC', label: 'NUMERIC' },
{ value: 'DATETIME', label: 'DATETIME' },
{ value: 'BOOLEAN', label: 'BOOLEAN' },
];
const DATASOURCE_TYPES_ARR = [
{ key: 'physical', label: t('Physical (table or view)') },
{ key: 'virtual', label: t('Virtual (SQL)') },
];
const DATASOURCE_TYPES = {};
DATASOURCE_TYPES_ARR.forEach(o => {
DATASOURCE_TYPES[o.key] = o;
});
function CollectionTabTitle({ title, collection }) {
return (
<div
css={{ display: 'flex', alignItems: 'center' }}
data-test={`collection-tab-${title}`}
>
{title}{' '}
<StyledBadge count={collection ? collection.length : 0} showZero />
</div>
);
}
CollectionTabTitle.propTypes = {
title: PropTypes.string,
collection: PropTypes.array,
};
function ColumnCollectionTable({
columns,
datasource,
onColumnsChange,
onDatasourceChange,
editableColumnName,
showExpression,
allowAddItem,
allowEditDataType,
itemGenerator,
}) {
return (
<CollectionTable
collection={columns}
tableColumns={[
'column_name',
'type',
'is_dttm',
'main_dttm_col',
'filterable',
'groupby',
]}
sortColumns={[
'column_name',
'type',
'is_dttm',
'main_dttm_col',
'filterable',
'groupby',
]}
allowDeletes
allowAddItem={allowAddItem}
itemGenerator={itemGenerator}
stickyHeader
expandFieldset={
<FormContainer>
<Fieldset compact>
{showExpression && (
<Field
fieldKey="expression"
label={t('SQL expression')}
control={
<TextAreaControl
language="markdown"
offerEditInModal={false}
/>
}
/>
)}
<Field
fieldKey="verbose_name"
label={t('Label')}
control={
<TextControl
controlId="verbose_name"
placeholder={t('Label')}
/>
}
/>
<Field
fieldKey="description"
label={t('Description')}
control={
<TextControl
controlId="description"
placeholder={t('Description')}
/>
}
/>
{allowEditDataType && (
<Field
fieldKey="type"
label={t('Data type')}
control={
<Select
ariaLabel={t('Data type')}
options={DATA_TYPES}
name="type"
allowNewOptions
allowClear
/>
}
/>
)}
<Field
fieldKey="python_date_format"
label={t('Datetime format')}
description={
/* Note the fragmented translations may not work. */
<div>
{t('The pattern of timestamp format. For strings use ')}
<a href="https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior">
{t('Python datetime string pattern')}
</a>
{t(' expression which needs to adhere to the ')}
<a href="https://en.wikipedia.org/wiki/ISO_8601">
{t('ISO 8601')}
</a>
{t(` standard to ensure that the lexicographical ordering
coincides with the chronological ordering. If the
timestamp format does not adhere to the ISO 8601 standard
you will need to define an expression and type for
transforming the string into a date or timestamp. Note
currently time zones are not supported. If time is stored
in epoch format, put \`epoch_s\` or \`epoch_ms\`. If no pattern
is specified we fall back to using the optional defaults on a per
database/column name level via the extra parameter.`)}
</div>
}
control={
<TextControl
controlId="python_date_format"
placeholder="%Y/%m/%d"
/>
}
/>
<Field
fieldKey="certified_by"
label={t('Certified By')}
description={t('Person or group that has certified this metric')}
control={
<TextControl
controlId="certified"
placeholder={t('Certified by')}
/>
}
/>
<Field
fieldKey="certification_details"
label={t('Certification details')}
description={t('Details of the certification')}
control={
<TextControl
controlId="certificationDetails"
placeholder={t('Certification details')}
/>
}
/>
</Fieldset>
</FormContainer>
}
columnLabels={{
column_name: t('Column'),
type: t('Data type'),
groupby: t('Is dimension'),
is_dttm: t('Is temporal'),
main_dttm_col: t('Default datetime'),
filterable: t('Is filterable'),
}}
onChange={onColumnsChange}
itemRenderers={{
column_name: (v, onItemChange, _, record) =>
editableColumnName ? (
<StyledLabelWrapper>
{record.is_certified && (
<CertifiedBadge
certifiedBy={record.certified_by}
details={record.certification_details}
/>
)}
<TextControl value={v} onChange={onItemChange} />
</StyledLabelWrapper>
) : (
<StyledLabelWrapper>
{record.is_certified && (
<CertifiedBadge
certifiedBy={record.certified_by}
details={record.certification_details}
/>
)}
{v}
</StyledLabelWrapper>
),
main_dttm_col: (value, _onItemChange, _label, record) => {
const checked = datasource.main_dttm_col === record.column_name;
const disabled = !columns.find(
column => column.column_name === record.column_name,
).is_dttm;
return (
<Radio
data-test={`radio-default-dttm-${record.column_name}`}
checked={checked}
disabled={disabled}
onChange={() =>
onDatasourceChange({
...datasource,
main_dttm_col: record.column_name,
})
}
/>
);
},
type: d => (d ? <Label>{d}</Label> : null),
is_dttm: checkboxGenerator,
filterable: checkboxGenerator,
groupby: checkboxGenerator,
}}
/>
);
}
ColumnCollectionTable.propTypes = {
columns: PropTypes.array.isRequired,
datasource: PropTypes.object.isRequired,
onColumnsChange: PropTypes.func.isRequired,
onDatasourceChange: PropTypes.func.isRequired,
editableColumnName: PropTypes.bool,
showExpression: PropTypes.bool,
allowAddItem: PropTypes.bool,
allowEditDataType: PropTypes.bool,
itemGenerator: PropTypes.func,
};
ColumnCollectionTable.defaultProps = {
editableColumnName: false,
showExpression: false,
allowAddItem: false,
allowEditDataType: false,
itemGenerator: () => ({
column_name: '<new column>',
filterable: true,
groupby: true,
}),
};
function StackedField({ label, formElement }) {
return (
<div>
<div>
<strong>{label}</strong>
</div>
<div>{formElement}</div>
</div>
);
}
StackedField.propTypes = {
label: PropTypes.string,
formElement: PropTypes.node,
};
function FormContainer({ children }) {
return <Card padded>{children}</Card>;
}
FormContainer.propTypes = {
children: PropTypes.node,
};
const propTypes = {
datasource: PropTypes.object.isRequired,
onChange: PropTypes.func,
addSuccessToast: PropTypes.func.isRequired,
addDangerToast: PropTypes.func.isRequired,
};
const defaultProps = {
onChange: () => {},
};
function OwnersSelector({ datasource, onChange }) {
const loadOptions = useCallback((search = '', page, pageSize) => {
const query = rison.encode({ filter: search, page, page_size: pageSize });
return SupersetClient.get({
endpoint: `/api/v1/dataset/related/owners?q=${query}`,
}).then(response => ({
data: response.json.result.map(item => ({
value: item.value,
label: item.text,
})),
totalCount: response.json.count,
}));
}, []);
return (
<Select
ariaLabel={t('Select owners')}
mode="multiple"
name="owners"
value={datasource.owners}
options={loadOptions}
onChange={onChange}
header={<FormLabel>{t('Owners')}</FormLabel>}
allowClear
/>
);
}
class DatasourceEditor extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
datasource: {
...props.datasource,
owners: props.datasource.owners.map(owner => ({
value: owner.value || owner.id,
label: owner.label || `${owner.first_name} ${owner.last_name}`,
})),
metrics: props.datasource.metrics?.map(metric => {
const {
certified_by: certifiedByMetric,
certification_details: certificationDetails,
} = metric;
const {
certification: { details, certified_by: certifiedBy } = {},
warning_markdown: warningMarkdown,
} = JSON.parse(metric.extra || '{}') || {};
return {
...metric,
certification_details: certificationDetails || details,
warning_markdown: warningMarkdown || '',
certified_by: certifiedBy || certifiedByMetric,
};
}),
},
errors: [],
isDruid:
props.datasource.type === 'druid' ||
props.datasource.datasource_type === 'druid',
isSqla:
props.datasource.datasource_type === 'table' ||
props.datasource.type === 'table',
isEditMode: false,
databaseColumns: props.datasource.columns.filter(col => !col.expression),
calculatedColumns: props.datasource.columns.filter(
col => !!col.expression,
),
metadataLoading: false,
activeTabKey: 0,
datasourceType: props.datasource.sql
? DATASOURCE_TYPES.virtual.key
: DATASOURCE_TYPES.physical.key,
};
this.onChange = this.onChange.bind(this);
this.onChangeEditMode = this.onChangeEditMode.bind(this);
this.onDatasourcePropChange = this.onDatasourcePropChange.bind(this);
this.onDatasourceChange = this.onDatasourceChange.bind(this);
this.tableChangeAndSyncMetadata =
this.tableChangeAndSyncMetadata.bind(this);
this.syncMetadata = this.syncMetadata.bind(this);
this.setColumns = this.setColumns.bind(this);
this.validateAndChange = this.validateAndChange.bind(this);
this.handleTabSelect = this.handleTabSelect.bind(this);
this.allowEditSource = !isFeatureEnabled(
FeatureFlag.DISABLE_DATASET_SOURCE_EDIT,
);
}
onChange() {
// Emptying SQL if "Physical" radio button is selected
// Currently the logic to know whether the source is
// physical or virtual is based on whether SQL is empty or not.
const { datasourceType, datasource } = this.state;
const sql =
datasourceType === DATASOURCE_TYPES.physical.key ? '' : datasource.sql;
const newDatasource = {
...this.state.datasource,
sql,
columns: [...this.state.databaseColumns, ...this.state.calculatedColumns],
};
this.props.onChange(newDatasource, this.state.errors);
}
onChangeEditMode() {
this.setState(prevState => ({ isEditMode: !prevState.isEditMode }));
}
onDatasourceChange(datasource, callback = this.validateAndChange) {
this.setState({ datasource }, callback);
}
onDatasourcePropChange(attr, value) {
if (value === undefined) return; // if value is undefined do not update state
const datasource = { ...this.state.datasource, [attr]: value };
this.setState(
prevState => ({
datasource: { ...prevState.datasource, [attr]: value },
}),
attr === 'table_name'
? this.onDatasourceChange(datasource, this.tableChangeAndSyncMetadata)
: this.onDatasourceChange(datasource, this.validateAndChange),
);
}
onDatasourceTypeChange(datasourceType) {
this.setState({ datasourceType });
}
setColumns(obj) {
// update calculatedColumns or databaseColumns
this.setState(obj, this.validateAndChange);
}
validateAndChange() {
this.validate(this.onChange);
}
tableChangeAndSyncMetadata() {
this.validate(() => {
this.syncMetadata();
this.onChange();
});
}
updateColumns(cols) {
const { databaseColumns } = this.state;
const databaseColumnNames = cols.map(col => col.name);
const currentCols = databaseColumns.reduce(
(agg, col) => ({
...agg,
[col.column_name]: col,
}),
{},
);
const finalColumns = [];
const results = {
added: [],
modified: [],
removed: databaseColumns
.map(col => col.column_name)
.filter(col => !databaseColumnNames.includes(col)),
};
cols.forEach(col => {
const currentCol = currentCols[col.name];
if (!currentCol) {
// new column
finalColumns.push({
id: shortid.generate(),
column_name: col.name,
type: col.type,
groupby: true,
filterable: true,
is_dttm: col.is_dttm,
});
results.added.push(col.name);
} else if (
currentCol.type !== col.type ||
(!currentCol.is_dttm && col.is_dttm)
) {
// modified column
finalColumns.push({
...currentCol,
type: col.type,
is_dttm: currentCol.is_dttm || col.is_dttm,
});
results.modified.push(col.name);
} else {
// unchanged
finalColumns.push(currentCol);
}
});
if (
results.added.length ||
results.modified.length ||
results.removed.length
) {
this.setColumns({ databaseColumns: finalColumns });
}
return results;
}
syncMetadata() {
const { datasource } = this.state;
const params = {
datasource_type: datasource.type || datasource.datasource_type,
database_name:
datasource.database.database_name || datasource.database.name,
schema_name: datasource.schema,
table_name: datasource.table_name,
};
Object.entries(params).forEach(([key, value]) => {
// rison can't encode the undefined value
if (value === undefined) {
params[key] = null;
}
});
const endpoint = `/datasource/external_metadata_by_name/?q=${rison.encode(
params,
)}`;
this.setState({ metadataLoading: true });
SupersetClient.get({ endpoint })
.then(({ json }) => {
const results = this.updateColumns(json);
if (results.modified.length) {
this.props.addSuccessToast(
t('Modified columns: %s', results.modified.join(', ')),
);
}
if (results.removed.length) {
this.props.addSuccessToast(
t('Removed columns: %s', results.removed.join(', ')),
);
}
if (results.added.length) {
this.props.addSuccessToast(
t('New columns added: %s', results.added.join(', ')),
);
}
this.props.addSuccessToast(t('Metadata has been synced'));
this.setState({ metadataLoading: false });
})
.catch(response =>
getClientErrorObject(response).then(({ error, statusText }) => {
this.props.addDangerToast(
error || statusText || t('An error has occurred'),
);
this.setState({ metadataLoading: false });
}),
);
}
findDuplicates(arr, accessor) {
const seen = {};
const dups = [];
arr.forEach(obj => {
const item = accessor(obj);
if (item in seen) {
dups.push(item);
} else {
seen[item] = null;
}
});
return dups;
}
validate(callback) {
let errors = [];
let dups;
const { datasource } = this.state;
// Looking for duplicate column_name
dups = this.findDuplicates(datasource.columns, obj => obj.column_name);
errors = errors.concat(
dups.map(name => t('Column name [%s] is duplicated', name)),
);
// Looking for duplicate metric_name
dups = this.findDuplicates(datasource.metrics, obj => obj.metric_name);
errors = errors.concat(
dups.map(name => t('Metric name [%s] is duplicated', name)),
);
// Making sure calculatedColumns have an expression defined
const noFilterCalcCols = this.state.calculatedColumns.filter(
col => !col.expression && !col.json,
);
errors = errors.concat(
noFilterCalcCols.map(col =>
t('Calculated column [%s] requires an expression', col.column_name),
),
);
this.setState({ errors }, callback);
}
handleTabSelect(activeTabKey) {
this.setState({ activeTabKey });
}
sortMetrics(metrics) {
return metrics.sort(({ id: a }, { id: b }) => b - a);
}
renderSettingsFieldset() {
const { datasource } = this.state;
return (
<Fieldset
title={t('Basic')}
item={datasource}
onChange={this.onDatasourceChange}
>
<Field
fieldKey="description"
label={t('Description')}
control={
<TextAreaControl language="markdown" offerEditInModal={false} />
}
/>
<Field
fieldKey="default_endpoint"
label={t('Default URL')}
description={t(
'Default URL to redirect to when accessing from the dataset list page',
)}
control={<TextControl controlId="default_endpoint" />}
/>
<Field
inline
fieldKey="filter_select_enabled"
label={t('Autocomplete filters')}
description={t('Whether to populate autocomplete filters options')}
control={<CheckboxControl />}
/>
{this.state.isSqla && (
<Field
fieldKey="fetch_values_predicate"
label={t('Autocomplete query predicate')}
description={t(
'When using "Autocomplete filters", this can be used to improve performance ' +
'of the query fetching the values. Use this option to apply a ' +
'predicate (WHERE clause) to the query selecting the distinct ' +
'values from the table. Typically the intent would be to limit the scan ' +
'by applying a relative time filter on a partitioned or indexed time-related field.',
)}
control={
<TextAreaControl
language="sql"
controlId="fetch_values_predicate"
minLines={5}
/>
}
/>
)}
{this.state.isSqla && (
<Field
fieldKey="extra"
label={t('Extra')}
description={t(
'Extra data to specify table metadata. Currently supports ' +
'metadata of the format: `{ "certification": { "certified_by": ' +
'"Data Platform Team", "details": "This table is the source of truth." ' +
'}, "warning_markdown": "This is a warning." }`.',
)}
control={
<TextAreaControl
controlId="extra"
language="json"
offerEditInModal={false}
/>
}
/>
)}
<OwnersSelector
datasource={datasource}
onChange={newOwners => {
this.onDatasourceChange({ ...datasource, owners: newOwners });
}}
/>
</Fieldset>
);
}
renderAdvancedFieldset() {
const { datasource } = this.state;
return (
<Fieldset
title={t('Advanced')}
item={datasource}
onChange={this.onDatasourceChange}
>
<Field
fieldKey="cache_timeout"
label={t('Cache timeout')}
description={t(
'The duration of time in seconds before the cache is invalidated',
)}
control={<TextControl controlId="cache_timeout" />}
/>
<Field
fieldKey="offset"
label={t('Hours offset')}
control={<TextControl controlId="offset" />}
description={t(
'The number of hours, negative or positive, to shift the time column. This can be used to move UTC time to local time.',
)}
/>
{this.state.isSqla && (
<Field
fieldKey="template_params"
label={t('Template parameters')}
description={t(
'A set of parameters that become available in the query using Jinja templating syntax',
)}
control={<TextControl controlId="template_params" />}
/>
)}
</Fieldset>
);
}
renderSpatialTab() {
const { datasource } = this.state;
const { spatials, all_cols: allCols } = datasource;
return (
<Tabs.TabPane
tab={<CollectionTabTitle collection={spatials} title={t('Spatial')} />}
key={4}
>
<CollectionTable
tableColumns={['name', 'config']}
onChange={this.onDatasourcePropChange.bind(this, 'spatials')}
itemGenerator={() => ({
name: '<new spatial>',
type: '<no type>',
config: null,
})}
collection={spatials}
allowDeletes
itemRenderers={{
name: (d, onChange) => (
<EditableTitle canEdit title={d} onSaveTitle={onChange} />
),
config: (v, onChange) => (
<SpatialControl value={v} onChange={onChange} choices={allCols} />
),
}}
/>
</Tabs.TabPane>
);
}
renderSourceFieldset(theme) {
const { datasource } = this.state;
return (
<div>
{this.allowEditSource && (
<EditLockContainer>
<span role="button" tabIndex={0} onClick={this.onChangeEditMode}>
{this.state.isEditMode ? (
<Icons.LockUnlocked iconColor={theme.colors.grayscale.base} />
) : (
<Icons.LockLocked iconColor={theme.colors.grayscale.base} />
)}
</span>
{!this.state.isEditMode && (
<div>{t('Click the lock to make changes.')}</div>
)}
{this.state.isEditMode && (
<div>{t('Click the lock to prevent further changes.')}</div>
)}
</EditLockContainer>
)}
<div className="m-l-10 m-t-20 m-b-10">
{DATASOURCE_TYPES_ARR.map(type => (
<Radio
key={type.key}
value={type.key}
inline
onChange={this.onDatasourceTypeChange.bind(this, type.key)}
checked={this.state.datasourceType === type.key}
disabled={!this.state.isEditMode}
>
{type.label}
</Radio>
))}
</div>
<hr />
<Fieldset item={datasource} onChange={this.onDatasourceChange} compact>
{this.state.datasourceType === DATASOURCE_TYPES.virtual.key && (
<div>
{this.state.isSqla && (
<>
<Col xs={24} md={12}>
<Field
fieldKey="databaseSelector"
label={t('virtual')}
control={
<div css={{ marginTop: 8 }}>
<DatabaseSelector
db={datasource?.database}
schema={datasource.schema}
onSchemaChange={schema =>
this.state.isEditMode &&
this.onDatasourcePropChange('schema', schema)
}
onDbChange={database =>
this.state.isEditMode &&
this.onDatasourcePropChange('database', database)
}
formMode={false}
handleError={this.props.addDangerToast}
readOnly={!this.state.isEditMode}
/>
</div>
}
/>
<div css={{ width: 'calc(100% - 34px)', marginTop: -16 }}>
<Field
fieldKey="table_name"
label={t('Dataset name')}
control={
<TextControl
controlId="table_name"
onChange={table => {
this.onDatasourcePropChange('table_name', table);
}}
placeholder={t('Dataset name')}
disabled={!this.state.isEditMode}
/>
}
/>
</div>
</Col>
<Field
fieldKey="sql"
label={t('SQL')}
description={t(
'When specifying SQL, the datasource acts as a view. ' +
'Superset will use this statement as a subquery while grouping and filtering ' +
'on the generated parent queries.',
)}
control={
<TextAreaControl
language="sql"
offerEditInModal={false}
minLines={20}
maxLines={20}
readOnly={!this.state.isEditMode}
/>
}
/>
</>
)}
{this.state.isDruid && (
<Field
fieldKey="json"
label={t('JSON')}
description={
<div>
{t('The JSON metric or post aggregation definition.')}
</div>
}
control={
<TextAreaControl language="json" offerEditInModal={false} />
}
/>
)}
</div>
)}
{this.state.datasourceType === DATASOURCE_TYPES.physical.key && (
<Col xs={24} md={12}>
{this.state.isSqla && (
<Field
fieldKey="tableSelector"
label={t('Physical')}
control={
<div css={{ marginTop: 8 }}>
<TableSelector
clearable={false}
database={{
...datasource.database,
database_name:
datasource.database.database_name ||
datasource.database.name,
}}
dbId={datasource.database.id}
handleError={this.props.addDangerToast}
schema={datasource.schema}
sqlLabMode={false}
tableName={datasource.table_name}
onSchemaChange={
this.state.isEditMode
? schema =>
this.onDatasourcePropChange('schema', schema)
: undefined
}
onDbChange={
this.state.isEditMode
? database =>
this.onDatasourcePropChange(
'database',
database,
)
: undefined
}
onTableChange={
this.state.isEditMode
? table =>
this.onDatasourcePropChange('table_name', table)
: undefined
}
readOnly={!this.state.isEditMode}
/>
</div>
}
description={t(
'The pointer to a physical table (or view). Keep in mind that the chart is ' +
'associated to this Superset logical table, and this logical table points ' +
'the physical table referenced here.',
)}
/>
)}
</Col>
)}
</Fieldset>
</div>
);
}
renderErrors() {
if (this.state.errors.length > 0) {
return (
<Alert
css={theme => ({ marginBottom: theme.gridUnit * 4 })}
type="error"
message={
<>
{this.state.errors.map(err => (
<div key={err}>{err}</div>
))}
</>
}
/>
);
}
return null;
}
renderMetricCollection() {
const { datasource } = this.state;
const { metrics } = datasource;
const sortedMetrics = metrics?.length ? this.sortMetrics(metrics) : [];
return (
<CollectionTable
tableColumns={['metric_name', 'verbose_name', 'expression']}
sortColumns={['metric_name', 'verbose_name', 'expression']}
columnLabels={{
metric_name: t('Metric'),
verbose_name: t('Label'),
expression: t('SQL expression'),
}}
expandFieldset={
<FormContainer>
<Fieldset compact>
<Field
fieldKey="description"
label={t('Description')}
control={
<TextControl
controlId="description"
placeholder={t('Description')}
/>
}
/>
<Field
fieldKey="d3format"
label={t('D3 format')}
control={
<TextControl controlId="d3format" placeholder="%y/%m/%d" />
}
/>
<Field
label={t('Certified by')}
fieldKey="certified_by"
description={t(
'Person or group that has certified this metric',
)}
control={
<TextControl
controlId="certified_by"
placeholder={t('Certified by')}
/>
}
/>
<Field
label={t('Certification details')}
fieldKey="certification_details"
description={t('Details of the certification')}
control={
<TextControl
controlId="certification_details"
placeholder={t('Certification details')}
/>
}
/>
<Field
label={t('Warning')}
fieldKey="warning_markdown"
description={t('Optional warning about use of this metric')}
control={
<TextAreaControl
controlId="warning_markdown"
language="markdown"
offerEditInModal={false}
/>
}
/>
</Fieldset>
</FormContainer>
}
collection={sortedMetrics}
allowAddItem
onChange={this.onDatasourcePropChange.bind(this, 'metrics')}
itemGenerator={() => ({
metric_name: '<new metric>',
verbose_name: '',
expression: '',
})}
itemRenderers={{
metric_name: (v, onChange, _, record) => (
<FlexRowContainer>
{record.is_certified && (
<CertifiedBadge
certifiedBy={record.certified_by}
details={record.certification_details}
/>
)}
{record.warning_markdown && (
<WarningIconWithTooltip
warningMarkdown={record.warning_markdown}
/>
)}
<EditableTitle canEdit title={v} onSaveTitle={onChange} />
</FlexRowContainer>
),
verbose_name: (v, onChange) => (
<TextControl canEdit value={v} onChange={onChange} />
),
expression: (v, onChange) => (
<TextAreaControl
canEdit
initialValue={v}
onChange={onChange}
extraClasses={['datasource-sql-expression']}
language="sql"
offerEditInModal={false}
minLines={5}
/>
),
description: (v, onChange, label) => (
<StackedField
label={label}
formElement={<TextControl value={v} onChange={onChange} />}
/>
),
d3format: (v, onChange, label) => (
<StackedField
label={label}
formElement={<TextControl value={v} onChange={onChange} />}
/>
),
}}
allowDeletes
stickyHeader
/>
);
}
render() {
const { datasource, activeTabKey } = this.state;
const { metrics } = datasource;
const sortedMetrics = metrics?.length ? this.sortMetrics(metrics) : [];
const { theme } = this.props;
return (
<DatasourceContainer>
{this.renderErrors()}
<Alert
css={theme => ({ marginBottom: theme.gridUnit * 4 })}
type="warning"
message={
<>
{' '}
<strong>{t('Be careful.')} </strong>
{t(
'Changing these settings will affect all charts using this dataset, including charts owned by other people.',
)}
</>
}
/>
<StyledTableTabs
fullWidth={false}
id="table-tabs"
data-test="edit-dataset-tabs"
onChange={this.handleTabSelect}
defaultActiveKey={activeTabKey}
>
<Tabs.TabPane key={0} tab={t('Source')}>
{this.renderSourceFieldset(theme)}
</Tabs.TabPane>
<Tabs.TabPane
tab={
<CollectionTabTitle
collection={sortedMetrics}
title={t('Metrics')}
/>
}
key={1}
>
{this.renderMetricCollection()}
</Tabs.TabPane>
<Tabs.TabPane
tab={
<CollectionTabTitle
collection={this.state.databaseColumns}
title={t('Columns')}
/>
}
key={2}
>
<StyledColumnsTabWrapper>
<ColumnButtonWrapper>
<span className="m-t-10 m-r-10">
<Button
buttonSize="small"
buttonStyle="tertiary"
onClick={this.syncMetadata}
className="sync-from-source"
disabled={this.state.isEditMode}
>
<i className="fa fa-database" />{' '}
{t('Sync columns from source')}
</Button>
</span>
</ColumnButtonWrapper>
<ColumnCollectionTable
className="columns-table"
editableColumnName
columns={this.state.databaseColumns}
datasource={datasource}
onColumnsChange={databaseColumns =>
this.setColumns({ databaseColumns })
}
onDatasourceChange={this.onDatasourceChange}
/>
{this.state.metadataLoading && <Loading />}
</StyledColumnsTabWrapper>
</Tabs.TabPane>
<Tabs.TabPane
tab={
<CollectionTabTitle
collection={this.state.calculatedColumns}
title={t('Calculated columns')}
/>
}
key={3}
>
<ColumnCollectionTable
columns={this.state.calculatedColumns}
onColumnsChange={calculatedColumns =>
this.setColumns({ calculatedColumns })
}
onDatasourceChange={this.onDatasourceChange}
datasource={datasource}
editableColumnName
showExpression
allowAddItem
allowEditDataType
itemGenerator={() => ({
column_name: '<new column>',
filterable: true,
groupby: true,
expression: '<enter SQL expression here>',
__expanded: true,
})}
/>
</Tabs.TabPane>
<Tabs.TabPane key={4} tab={t('Settings')}>
<Row gutter={16}>
<Col xs={24} md={12}>
<FormContainer>{this.renderSettingsFieldset()}</FormContainer>
</Col>
<Col xs={24} md={12}>
<FormContainer>{this.renderAdvancedFieldset()}</FormContainer>
</Col>
</Row>
</Tabs.TabPane>
</StyledTableTabs>
</DatasourceContainer>
);
}
}
DatasourceEditor.defaultProps = defaultProps;
DatasourceEditor.propTypes = propTypes;
const DataSourceComponent = withTheme(DatasourceEditor);
export default withToasts(DataSourceComponent);
| superset-frontend/src/components/Datasource/DatasourceEditor.jsx | 0 | https://github.com/apache/superset/commit/60db35cb4d8462aeb4121e8a8b9eccee9c23621e | [
0.00044102687388658524,
0.00017521789413876832,
0.00016390826203860343,
0.00017037380894180387,
0.00003260515586589463
] |
{
"id": 2,
"code_window": [
" # via tabulator\n",
"mysqlclient==2.1.0\n",
" # via -r requirements/development.in\n",
"openpyxl==3.0.7\n",
" # via tabulator\n",
"pillow==8.4.0\n",
" # via -r requirements/development.in\n",
"progress==1.6\n",
" # via -r requirements/development.in\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"pillow==9.0.0\n"
],
"file_path": "requirements/development.txt",
"type": "replace",
"edit_start_line_idx": 42
} | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
export type AnnotationLayerMetadata = {
name: string;
sourceType?: string;
};
| superset-frontend/packages/superset-ui-core/src/chart/types/Annotation.ts | 0 | https://github.com/apache/superset/commit/60db35cb4d8462aeb4121e8a8b9eccee9c23621e | [
0.0001739209983497858,
0.0001733729150146246,
0.0001728976785670966,
0.0001733000681269914,
4.2093216734429006e-7
] |
{
"id": 3,
"code_window": [
"-e file:.\n",
" # via\n",
" # -r requirements/base.in\n",
" # -r requirements/testing.in\n",
"astroid==2.6.6\n",
" # via pylint\n",
"backcall==0.2.0\n",
" # via ipython\n",
"cachetools==4.2.4\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"appnope==0.1.2\n",
" # via ipython\n"
],
"file_path": "requirements/testing.txt",
"type": "add",
"edit_start_line_idx": 13
} | # SHA1:c835350e502151c63817980505ce50b9e5b78a54
#
# This file is autogenerated by pip-compile-multi
# To update, run:
#
# pip-compile-multi
#
-r base.txt
-e file:.
# via -r requirements/base.in
boto3==1.18.19
# via tabulator
botocore==1.21.19
# via
# boto3
# s3transfer
cached-property==1.5.2
# via tableschema
certifi==2021.5.30
# via requests
charset-normalizer==2.0.4
# via requests
et-xmlfile==1.1.0
# via openpyxl
flask-cors==3.0.10
# via -r requirements/development.in
future==0.18.2
# via pyhive
ijson==3.1.4
# via tabulator
jmespath==0.10.0
# via
# boto3
# botocore
jsonlines==2.0.0
# via tabulator
linear-tsv==1.1.0
# via tabulator
mysqlclient==2.1.0
# via -r requirements/development.in
openpyxl==3.0.7
# via tabulator
pillow==8.4.0
# via -r requirements/development.in
progress==1.6
# via -r requirements/development.in
psycopg2-binary==2.9.1
# via -r requirements/development.in
pure-sasl==0.6.2
# via thrift-sasl
pydruid==0.6.2
# via -r requirements/development.in
pyhive[hive]==0.6.4
# via -r requirements/development.in
pyinstrument==4.0.2
# via -r requirements/development.in
requests==2.26.0
# via
# pydruid
# tableschema
# tabulator
rfc3986==1.5.0
# via tableschema
s3transfer==0.5.0
# via boto3
tableschema==1.20.2
# via -r requirements/development.in
tabulator==1.53.5
# via tableschema
thrift==0.13.0
# via
# -r requirements/development.in
# pyhive
# thrift-sasl
thrift-sasl==0.4.3
# via pyhive
unicodecsv==0.14.1
# via
# tableschema
# tabulator
xlrd==2.0.1
# via tabulator
# The following packages are considered to be unsafe in a requirements file:
# setuptools
| requirements/development.txt | 1 | https://github.com/apache/superset/commit/60db35cb4d8462aeb4121e8a8b9eccee9c23621e | [
0.011246172711253166,
0.0022816816344857216,
0.00016645918367430568,
0.0005989501951262355,
0.0034350755158811808
] |
{
"id": 3,
"code_window": [
"-e file:.\n",
" # via\n",
" # -r requirements/base.in\n",
" # -r requirements/testing.in\n",
"astroid==2.6.6\n",
" # via pylint\n",
"backcall==0.2.0\n",
" # via ipython\n",
"cachetools==4.2.4\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"appnope==0.1.2\n",
" # via ipython\n"
],
"file_path": "requirements/testing.txt",
"type": "add",
"edit_start_line_idx": 13
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Add verbose name to DruidCluster and Database
Revision ID: db527d8c4c78
Revises: b318dfe5fb6c
Create Date: 2017-03-16 18:10:57.193035
"""
# revision identifiers, used by Alembic.
revision = "db527d8c4c78"
down_revision = "b318dfe5fb6c"
import logging
import sqlalchemy as sa
from alembic import op
def upgrade():
op.add_column(
"clusters", sa.Column("verbose_name", sa.String(length=250), nullable=True)
)
op.add_column(
"dbs", sa.Column("verbose_name", sa.String(length=250), nullable=True)
)
try:
op.create_unique_constraint(None, "dbs", ["verbose_name"])
op.create_unique_constraint(None, "clusters", ["verbose_name"])
except Exception:
logging.info("Constraint not created, expected when using sqlite")
def downgrade():
try:
op.drop_column("dbs", "verbose_name")
op.drop_column("clusters", "verbose_name")
except Exception as ex:
logging.exception(ex)
| superset/migrations/versions/db527d8c4c78_add_db_verbose_name.py | 0 | https://github.com/apache/superset/commit/60db35cb4d8462aeb4121e8a8b9eccee9c23621e | [
0.0001739835279295221,
0.00017282967746723443,
0.0001722120650811121,
0.00017261065659113228,
6.084504207137797e-7
] |
{
"id": 3,
"code_window": [
"-e file:.\n",
" # via\n",
" # -r requirements/base.in\n",
" # -r requirements/testing.in\n",
"astroid==2.6.6\n",
" # via pylint\n",
"backcall==0.2.0\n",
" # via ipython\n",
"cachetools==4.2.4\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"appnope==0.1.2\n",
" # via ipython\n"
],
"file_path": "requirements/testing.txt",
"type": "add",
"edit_start_line_idx": 13
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
const dataTestLocator = (value: string) => `[data-test='${value}']`;
export const pageHeader = {
logo: '.navbar-brand > img',
headerNavigationItem: '.ant-menu-submenu-title',
headerNavigationDropdown: "[aria-label='triangle-down']",
headerNavigationItemMenu: '.ant-menu-item-group-list',
plusIcon: ':nth-child(2) > .ant-menu-submenu-title',
plusIconMenuOptions: {
sqlQueryOption: dataTestLocator('menu-item-SQL query'),
chartOption: dataTestLocator('menu-item-Chart'),
dashboardOption: dataTestLocator('menu-item-Dashboard'),
},
plusMenu: '.ant-menu-submenu-popup',
barButtons: '[role="presentation"]',
sqlLabMenu: '[id="item_3$Menu"]',
dataMenu: '[id="item_4$Menu"]',
};
export const profile = {
activeTab: '.ant-tabs-tab-active',
inactiveTab: '.ant-tabs-tab',
emptyFavoritedPlaceholder: '.ant-empty-normal',
tableRow: '.table-row',
favoritesSpace: '#rc-tabs-0-panel-2',
};
export const securityAccess = {
rolesBubble: '.ant-badge-count',
};
export const homePage = {
homeSection: {
sectionArea: '.ant-collapse-content-box',
sectionElement: '.ant-card-meta-title',
},
sections: {
expandedSection: '.ant-collapse-item-active',
expandedSectionHeader: '[aria-expanded="true"]',
collapseExpandButton: '.ant-collapse-arrow',
collapsedSection: '[class="ant-collapse-item"]',
collapsedSectionHeader: '[aria-expanded="false"]',
section: '[class^="ant-collapse-item"]',
sectionsMenuContainer: "[role='navigation']",
sectionsMenuItem: "[role='menuitem']",
card: dataTestLocator('styled-card'),
},
thumbnailsSection: {
container: "[class='switch']",
toggle: "[role ='switch']",
},
};
export const databasesPage = {
addDatabaseButton: dataTestLocator('btn-create-database'),
searchInput: dataTestLocator('search-input'),
table: {
tableRow: dataTestLocator('table-row'),
tableCell: dataTestLocator('table-row-cell'),
editButton: dataTestLocator('edit-alt'),
},
modal: {
header: '#rcDialogTitle0 > h4',
step: '.helper-top',
selectDbStepTitle: '.select-db > h4',
preferredBlockBigQuery: '.preferred > :nth-child(1)',
prefferedBlockPostgreSQL: '.preferred > :nth-child(2)',
prefferedBlockSnowflake: '.preferred > :nth-child(3)',
prefferedBlockMySQL: '.preferred > :nth-child(4)',
prefferedBlockAthena: '.preferred > :nth-child(5)',
prefferedBlockSheets: '.preferred > :nth-child(6)',
supportedDatabasesText: '.control-label',
orChoose: '.available-label',
dbDropdown: '[class="ant-select-selection-search-input"]',
dbDropdownMenu: '.rc-virtual-list-holder-inner',
dbDropdownMenuItem: '[class="ant-select-item-option-content"]',
infoAlert: '.ant-alert',
serviceAccountInput: '[name="credentials_info"]',
connectionStep: {
modal: '.ant-modal-content',
modalBody: '.ant-modal-body',
stepTitle: '.css-7x6kk > h4',
helperBottom: '.helper-bottom',
postgresDatabase: '[name="database"]',
dbInput: '[name="database_name"]',
alertMessage: '.ant-alert-message',
errorField: '[role="alert"]',
uploadJson: '[title="Upload JSON file"]',
chooseFile: '[class="ant-btn input-upload-btn"]',
additionalParameters: '[name="query_input"]',
sqlAlchemyUriInput: dataTestLocator('sqlalchemy-uri-input'),
advancedTab: '#rc-tabs-0-tab-2',
activeTab: '.ant-tabs-tab-active',
securitySubMenu:
':nth-child(3) > .ant-collapse-header > .anticon > svg > path',
aceTextInput: '.ace_text-input',
aceContent: '.ace_content',
connectButton: '.css-16i3wh7',
hostInput: '[name="host"]',
portInput: '[name="port"]',
usernameInput: '[name="username"]',
passwordInput: '[name="password"]',
switch: '.ant-switch',
},
},
};
export const sqlLabView = {
sqlEditorLeftBar: {
sqlEditorLeftBar: '[class="SqlEditorLeftBar"]',
databaseSchemaTableSection: '[class="SqlEditorLeftBar"] > :nth-child(1)',
tableSchemaSection:
'[class="SqlEditorLeftBar"] > :nth-child(1) > :nth-child(3) > :nth-child(1)',
tableSchemaInputEmpty: '[aria-label="Select table or type table name"]',
},
databaseInput: '[data-test=DatabaseSelector] > :nth-child(1)',
emptyMenuOptionsPlaceholder: '[class="ant-empty-img-simple"]',
removeTabButton: '.ant-tabs-tab-remove > .anticon > svg',
tabsNavList: "[class='ant-tabs-nav-list']",
tab: "[class='ant-tabs-tab-btn']",
addTabButton: dataTestLocator('add-tab-icon'),
tooltip: '.ant-tooltip-content',
tabName: '.css-1suejie',
schemaInput: '[data-test=DatabaseSelector] > :nth-child(2)',
loadingIndicator: '.Select__loading-indicator',
menuItem: '[class="ant-select-item-option-content"]',
examplesMenuItem: '[title="examples"]',
tableInput: ':nth-child(4) > .select > :nth-child(1)',
sqlEditor: '#brace-editor textarea',
saveAsButton: '.SaveQuery > .ant-btn',
saveAsModal: {
footer: '.ant-modal-footer',
queryNameInput: 'input[class^="ant-input"]',
},
sqlToolbar: {
toolbar: '#js-sql-toolbar',
runButton: '.css-d3dxop',
},
rowsLimit: {
dropdown: '.ant-dropdown-menu',
limitButton: '.ant-dropdown-menu-item',
limitButtonText: '.css-151uxnz',
limitTextWithValue: '[class="ant-dropdown-trigger"]',
},
renderedTableHeader: '.ReactVirtualized__Table__headerRow',
renderedTableRow: '.ReactVirtualized__Table__row',
errorBody: '.error-body',
alertMessage: '.ant-alert-message',
historyTable: {
header: '[role=columnheader]',
table: '.QueryTable',
row: dataTestLocator('table-row'),
failureMarkIcon: '[aria-label=x-small]',
successMarkIcon: '[aria-label=check]',
},
};
export const queryHistory = {
tableHeader: dataTestLocator('sort-header'),
row: dataTestLocator('table-row'),
cell: dataTestLocator('table-row-cell'),
action: '[aria-label=full]',
};
export const savedQuery = {
tableHeader: dataTestLocator('sort-header'),
row: dataTestLocator('table-row'),
cell: dataTestLocator('table-row-cell'),
trash: dataTestLocator('delete-action'),
deleteQueryIcon: '[data-test="delete-action"]',
deleteModal: {
deleteInput: dataTestLocator('delete-modal-input'),
deleteButton: dataTestLocator('modal-confirm-button'),
},
};
export const annotationLayersView = {
emptyDescription: {
description: '.ant-empty-description',
addAnnotationLayerButton: '.ant-empty-footer > .ant-btn',
},
modal: {
content: {
content: '.ant-modal-body',
title: '.ant-modal-body > :nth-child(2) > input',
description: "[name='descr']",
},
footer: {
footer: '.ant-modal-footer',
addButton: dataTestLocator('modal-confirm-button'),
cancelButton: dataTestLocator('modal-cancel-button'),
},
},
};
export const datasetsList = {
newDatasetButton: '.css-yff34v',
searchInput: dataTestLocator('filters-search'),
newDatasetModal: {
inputField: '[class="section"]',
addButton: dataTestLocator('modal-confirm-button'),
body: '.ant-modal-body',
},
table: {
tableRow: {
row: dataTestLocator('table-row'),
rowText: dataTestLocator('cell-text'),
rowCell: dataTestLocator('table-row-cell'),
},
tableRowHeader: {
header: dataTestLocator('sort-header'),
unsorted: '[aria-label="sort"]',
sortAsc: '[aria-label="sort-asc"]',
sortDesc: '[aria-label="sort-desc"]',
},
rowActionItems: dataTestLocator('table-row-cell'),
actionButton: '.action-button',
editButton: '[aria-label="edit-alt"]',
},
editDatasetModal: {
modal: dataTestLocator('edit-dataset-tabs'),
sourceNavigationTab: '#table-tabs-tab-0',
metricsNavigationTab: dataTestLocator('collection-tab-Metrics'),
columnsNavigationTab: dataTestLocator('collection-tab-Columns'),
calculatedColumnsNavigationTab: dataTestLocator(
'collection-tab-Calculated columns',
),
settingsNavigationTab: '#table-tabs-tab-4',
saveButton: dataTestLocator('datasource-modal-save'),
sourceContent: '#table-tabs-panel-0',
metricsContent: '#table-tabs-panel-1',
columnsContent: '#table-tabs-panel-2',
calculatedColumnsContent: '#table-tabs-panel-3',
settingsContent: '#table-tabs-panel-4',
aceTextInput: '.ace_text-input',
sourceSQLInput: '.ace_content',
sourceVirtualSQLRadio: ':nth-child(2) > .ant-radio > .ant-radio-inner',
sourcePadlock: '[aria-label=lock-locked]',
legacy: {
panel: '.panel-body',
sqlInput: '#sql',
save: '.well > .btn-primary',
description: '#description',
},
},
deleteDatasetModal: {
modal: '.ant-modal-content',
deleteInput: dataTestLocator('delete-modal-input'),
deleteButton: dataTestLocator('modal-confirm-button'),
text: '.css-kxmt87',
},
};
export const chartListView = {
filtersBar: {
searchField: dataTestLocator('filters-search'),
},
top: {
bulkSelect: dataTestLocator('bulk-select'),
},
header: {
cardView: '[aria-label="card-view"]',
listView: '[aria-label="list-view"]',
sort: '[class="ant-select-selection-search-input"][aria-label="Sort"]',
sortRecentlyModifiedMenuOption: '[label="Recently modified"]',
sortAlphabeticalMenuOption: '[label="Alphabetical"]',
sortDropdown: '.Select__menu',
},
card: {
card: dataTestLocator('styled-card'),
cardCover: '[class="ant-card-cover"]',
cardImage: '[class="gradient-container"]',
selectedStarIcon: "[aria-label='favorite-selected']",
unselectedStarIcon: "[aria-label='favorite-unselected']",
starIcon: dataTestLocator('fave-unfave-icon'),
},
deleteModal: {
deleteInput: dataTestLocator('delete-modal-input'),
deleteButton: dataTestLocator('modal-confirm-button'),
},
table: {
bulkSelect: {
checkboxOff: '[aria-label="checkbox-off"]',
checkboxOn: '[aria-label="checkbox-on"]',
action: dataTestLocator('bulk-select-action'),
},
tableList: dataTestLocator('listview-table'),
table: '[role="rowgroup"]',
tableRowHeader: {
header: dataTestLocator('sort-header'),
unsorted: '[aria-label="sort"]',
sortAsc: '[aria-label="sort-asc"]',
sortDesc: '[aria-label="sort-desc"]',
},
tableRow: {
row: dataTestLocator('table-row'),
rowText: dataTestLocator('cell-text'),
rowCell: dataTestLocator('table-row-cell'),
},
},
addChartButton: '.css-yff34v',
};
export const nativeFilters = {
modal: {
container: '.ant-modal',
footer: '.ant-modal-footer',
saveButton: dataTestLocator('native-filter-modal-save-button'),
cancelButton: dataTestLocator('native-filter-modal-cancel-button'),
yesCancelButton: '[type="button"]',
alertXUnsavedFilters: '.ant-alert-message',
tabsList: {
tabsContainer: '[class="ant-tabs-nav-list"]',
tab: '.ant-tabs-tab',
removeTab: '[aria-label="trash"]',
},
addFilter: dataTestLocator('add-filter-button'),
defaultValueCheck: '.ant-checkbox-checked',
},
filtersPanel: {
filterName: dataTestLocator('filters-config-modal__name-input'),
datasetName: dataTestLocator('filters-config-modal__datasource-input'),
filterInfoInput: '.ant-select-selection-search-input',
inputDropdown: '.ant-select-item-option-content',
columnEmptyInput: '.ant-select-selection-placeholder',
filterTypeInput: dataTestLocator('filters-config-modal__filter-type'),
fieldInput: dataTestLocator('field-input'),
},
filterFromDashboardView: {
expand: dataTestLocator('filter-bar__expand-button'),
collapse: dataTestLocator('filter-bar__collapse-button'),
filterName: dataTestLocator('filter-control-name'),
filterContent: '.ant-select-selection-item-content',
},
createFilterButton: dataTestLocator('filter-bar__create-filter'),
removeFilter: '[aria-label="remove"]',
filterConfigurationSections: {
collapseExpandButton: '.ant-collapse-arrow',
checkedCheckbox: '.ant-checkbox-wrapper-checked',
infoTooltip: '[aria-label="Show info tooltip"]',
parentFilterInput: dataTestLocator('parent-filter-input'),
},
filtersList: {
list: '.ant-tabs-nav-list',
listItemNotActive: '[class="ant-tabs-tab ant-tabs-tab-with-remove"]',
listItemActive:
'[class="ant-tabs-tab ant-tabs-tab-with-remove ant-tabs-tab-active"]',
removeIcon: '[aria-label="trash"]',
},
filterItem: dataTestLocator('form-item-value'),
filterItemDropdown: '.ant-select-selection-search',
applyFilter: dataTestLocator('filter-bar__apply-button'),
defaultInput: dataTestLocator('default-input'),
filterIcon: dataTestLocator('filter-icon'),
};
export const dashboardListView = {
dashboardListView: dataTestLocator('dashboard-list-view'),
editItemAction: dataTestLocator('edit-alt'),
filtersBar: {
searchField: dataTestLocator('filters-search'),
},
top: {
bulkSelect: dataTestLocator('bulk-select'),
},
card: {
card: dataTestLocator('styled-card'),
cardCover: '[class="ant-card-cover"]',
cardImage: '[class="gradient-container"]',
selectedStarIcon: "[aria-label='favorite-selected']",
unselectedStarIcon: "[aria-label='favorite-unselected']",
starIcon: dataTestLocator('fave-unfave-icon'),
},
deleteModal: {
deleteInput: dataTestLocator('delete-modal-input'),
deleteButton: dataTestLocator('modal-confirm-button'),
},
table: {
starIcon: dataTestLocator('fave-unfave-icon'),
selectedStarIcon: "[aria-label='favorite-selected']",
unselectedStarIcon: "[aria-label='favorite-unselected']",
bulkSelect: {
checkboxOff: '[aria-label="checkbox-off"]',
checkboxOn: '[aria-label="checkbox-on"]',
action: dataTestLocator('bulk-select-action'),
},
tableRow: {
sortHeader: dataTestLocator('sort-header'),
row: dataTestLocator('table-row'),
rowText: dataTestLocator('cell-text'),
rowCell: dataTestLocator('table-row-cell'),
},
tableRowList: '[role="rowgroup"]',
tableList: dataTestLocator('listview-table'),
trashIcon: dataTestLocator('dashboard-list-trash-icon'),
},
actions: {
importButton: dataTestLocator('import-button'),
newDashboardButton: '.css-yff34v',
},
importModal: {
selectFileButton: '.ant-upload > .ant-btn > span',
importButton: dataTestLocator('modal-confirm-button'),
},
header: {
cardView: '[aria-label="card-view"]',
listView: '[aria-label="list-view"]',
sort: dataTestLocator('sort-header'),
sortDropdown: '.Select__menu',
statusFilterInput: `${dataTestLocator(
'filters-select',
)}[aria-label='Status']`,
ownerFilterInput: `${dataTestLocator(
'filters-select',
)}[aria-label='Owner']`,
createdByFilterInput: `${dataTestLocator(
'filters-select',
)}[aria-label='Created by']`,
FavoriteFilterInput: `${dataTestLocator(
'filters-select',
)}[aria-label='Favorite']`,
searchFilterInput: `${dataTestLocator(
'filters-search',
)}[name='dashboard_title']`,
draftStatusFilterOption: "[title='Draft']",
},
};
export const exploreView = {
openDatasourceMenu: dataTestLocator('open-datasource-tab'),
sectionsHeader: '.ant-collapse-header',
datasourceMenuThreeDots: dataTestLocator('datasource-menu-trigger'),
threeDotsMenuDropdown: {
editDataset: dataTestLocator('edit-dataset'),
},
chartContainer: dataTestLocator('chart-container'),
chartHeading: {
queryMenu: '#query',
viewQueryButton: dataTestLocator('view-query-menu-item'),
shortLinkButton: dataTestLocator('short-link-button'),
embedCodeButton: dataTestLocator('embed-code-button'),
},
chartAreaItem: '.nv-legend-text',
viewQueryModal: {
container: '.ant-modal-content',
closeButton: 'button.ant-modal-close',
},
embedCodeModal: {
container: dataTestLocator('embed-code-popover'),
textfield: dataTestLocator('embed-code-textarea'),
},
saveModal: {
modal: '.ant-modal-content',
chartNameInput: dataTestLocator('new-chart-name'),
dashboardNameInput: '#dashboard-creatable-select',
addToDashboardInput: dataTestLocator(
'save-chart-modal-select-dashboard-form',
),
saveButton: dataTestLocator('btn-modal-save'),
saveAsCircle: dataTestLocator('saveas-radio'),
overwriteCircle: dataTestLocator('save-overwrite-radio'),
},
controlPanel: {
panel: dataTestLocator('control-tabs'),
categoryArea: '.ant-collapse-content-box',
dragField: dataTestLocator('datasource'),
metricsField: dataTestLocator('metrics'),
optionField: dataTestLocator('option-label'),
fieldInput: '.Select__control input',
removeFieldValue: dataTestLocator('remove-control-button'),
addFieldValue: '[aria-label="plus-small"]',
vizType: dataTestLocator('visualization-type'),
runButton: dataTestLocator('run-query-button'),
saveQuery: dataTestLocator('query-save-button'),
fieldValue: dataTestLocator('control-label'),
addMetricModal: {
container: dataTestLocator('metrics-edit-popover'),
metricNameEdit: {
editButton: dataTestLocator('AdhocMetricEditTitle#trigger'),
input: dataTestLocator('AdhocMetricEditTitle#input'),
},
simpleTab: {
tab: '#adhoc-metric-edit-tabs-tab-SIMPLE',
columnInput: '[name="select-column"]',
aggregateInput: '[name="select-aggregate"]',
},
customSQLTab: {
tab: '#adhoc-metric-edit-tabs-tab-SQL',
inputContainerField: '.ace_content',
input: '.ace_text-input',
},
saveButton: dataTestLocator('AdhocMetricEdit#save'),
},
querySection: {
groupByField: dataTestLocator('groupby'),
filtersField: dataTestLocator('adhoc_filters'),
filterValue: dataTestLocator('adhoc-filter-simple-value'),
filterModal: {
customSQL: {
tab: '#adhoc-filter-edit-tabs-tab-SQL',
inputArea: '.ace_content',
input: '.ace_text-input',
},
simple: {
tab: '#adhoc-filter-edit-tabs-tab-SIMPLE',
},
container: dataTestLocator('filter-edit-popover'),
saveButton: dataTestLocator('adhoc-filter-edit-popover-save-button'),
},
},
annotationLayerSection: {
addAnnotationLayer: dataTestLocator('annotation_layers'),
addAnnotationLayerModal: {
container: dataTestLocator('popover-content'),
name: dataTestLocator('annotation-layer-name-header'),
formula: dataTestLocator('annotation-layer-value-header'),
input: dataTestLocator(''),
},
},
timeSection: {
timeRangeFilter: dataTestLocator('time-range-trigger'),
timeRangeFilterModal: {
container: '.ant-popover-content',
footer: '.footer',
cancelButton: dataTestLocator('cancel-button'),
configureLastTimeRange: {
container: '.ant-radio-group',
checkedItem: '.ant-radio-checked + span',
},
configureCustomTimeRange: {
container: dataTestLocator('custom-frame'),
timeInput: '.ant-input-number-input-wrap > input',
},
configureNoFilterTimeRange: {
container: dataTestLocator('no-filter'),
},
},
},
advancedAnalyticsSection: {
timeShift: {
container: dataTestLocator('time_compare'),
input: 'input[type=text]',
selectedValues: '.Select__multi-value__label',
},
},
},
editDatasetModal: {
container: '.ant-modal-content',
datasetTabsContainer: dataTestLocator('edit-dataset-tabs'),
saveButton: dataTestLocator('datasource-modal-save'),
metricsTab: {
addItem: dataTestLocator('crud-add-table-item'),
rowsContainer: dataTestLocator('table-content-rows'),
},
confirmModal: {
okButton: '.ant-modal-confirm-btns .ant-btn-primary',
},
},
vizualizationTypeModal: {
vizTypeButton: dataTestLocator('viztype-selector-container'),
},
};
export const createChartView = {
chooseDatasetInput: '.ant-select-selection-search-input',
chooseDatasetOption: '.ant-select-item-option-content',
chooseDatasetList: '.rc-virtual-list-holder-inner',
tableVizType: "[alt='Table']",
};
export const editDashboardView = {
dashboardName: dataTestLocator('dashboard-title-input'),
dashboardEditingContainer: dataTestLocator('dashboard-content'),
editComponent: dataTestLocator('new-component'),
discardChanges: dataTestLocator('discard-changes-button'),
chartBox: dataTestLocator('chart-grid-component'),
tabsList: {
tabsContainer: '[class="ant-tabs-nav-list"]',
tab: '.ant-tabs-tab',
},
};
export const dashboardView = {
dashboardContainer: dataTestLocator('grid-container'),
saveModal: {
modal: '.ant-modal-content',
dashboardNameInput: '.ant-input',
saveButton: dataTestLocator('modal-save-dashboard-button'),
},
dashboardProperties: {
modal: '.ant-modal-content',
dashboardTitleInput: dataTestLocator('dashboard-title-input'),
modalButton: '[type="button"]',
},
chart: {
trashIcon: dataTestLocator('dashboard-delete-component-button'),
refreshChart: dataTestLocator('refresh-chart-menu-item'),
},
threeDotsMenuIcon: '#save-dash-split-button',
threeDotsMenuDropdown: dataTestLocator('header-actions-menu'),
refreshDashboard: dataTestLocator('refresh-dashboard-menu-item'),
saveAsMenuOption: dataTestLocator('save-as-menu-item'),
dashboardTab: dataTestLocator('dragdroppable-object'),
salesDashboardSpecific: {
vehicleSalesFilterTimeRange: dataTestLocator('time-range-trigger'),
secondTabSalesDashboard: dataTestLocator('dragdroppable-object'),
},
timeRangeModal: {
rangeTypeField: '.ant-select-selection-item',
startTimeInputNumber: '.ant-input-number-input',
datePicker: '.ant-picker-input',
applyButton: dataTestLocator('date-filter-control__apply-button'),
radioGroup: '.ant-radio-group',
radioButton: '.ant-radio',
finalFilterRangePreviewCustom:
'.css-c2bup7 > :nth-child(6) > :nth-child(2)',
finalFilterRangePreviewLast: '.css-c2bup7 > :nth-child(7) > :nth-child(2)',
finalFilterRangePreviewPrevious:
'.css-c2bup7 > :nth-child(7) > :nth-child(2)',
},
treeMapChartModal: {
selectItem: '.Select_control',
selectItemInput: '.Select__control input[type=text]',
applyButton: '.filter_box button:not(:disabled)',
clearItemIcon: '.Select__clear-indicator',
},
sliceThreeDots: '[aria-label="More Options"]',
sliceThreeDotsDropdown: '[role="menu"]',
editDashboardButton: '[aria-label=edit-alt]',
starIcon: dataTestLocator('fave-unfave-icon'),
dashboardHeader: dataTestLocator('dashboard-header'),
dashboardSectionContainer: dataTestLocator(
'grid-row-background--transparent',
),
markdownEditor: dataTestLocator('dashboard-markdown-editor'),
dashboardComponent: dataTestLocator('dashboard-component-chart-holder'),
tabsList: {
tabsContainer: dataTestLocator('dashboard-component-tabs'),
tabsNavList: dataTestLocator('nav-list'),
tabs: '.ant-tabs-nav-list',
tab: '.ant-tabs-tab',
},
};
| superset-frontend/cypress-base/cypress/support/directories.ts | 0 | https://github.com/apache/superset/commit/60db35cb4d8462aeb4121e8a8b9eccee9c23621e | [
0.00017733359709382057,
0.00017034538905136287,
0.00016380983288399875,
0.0001706277544144541,
0.0000032317200293618953
] |
{
"id": 3,
"code_window": [
"-e file:.\n",
" # via\n",
" # -r requirements/base.in\n",
" # -r requirements/testing.in\n",
"astroid==2.6.6\n",
" # via pylint\n",
"backcall==0.2.0\n",
" # via ipython\n",
"cachetools==4.2.4\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"appnope==0.1.2\n",
" # via ipython\n"
],
"file_path": "requirements/testing.txt",
"type": "add",
"edit_start_line_idx": 13
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import { action } from '@storybook/addon-actions';
import {
SuperChart,
getChartTransformPropsRegistry,
GenericDataType,
} from '@superset-ui/core';
import RangeFilterPlugin from './index';
import transformProps from './transformProps';
new RangeFilterPlugin().configure({ key: 'filter_range' }).register();
getChartTransformPropsRegistry().registerValue('filter_range', transformProps);
export default {
title: 'Filter Plugins',
};
export const range = ({ width, height }: { width: number; height: number }) => (
<SuperChart
chartType="filter_range"
width={width}
height={height}
queriesData={[{ data: [{ min: 10, max: 100 }] }]}
filterState={{ value: [10, 70] }}
formData={{
groupby: ['SP_POP_TOTL'],
adhoc_filters: [],
extra_filters: [],
viz_type: 'filter_range',
metrics: [
{
aggregate: 'MIN',
column: {
column_name: 'SP_POP_TOTL',
id: 1,
type_generic: GenericDataType.NUMERIC,
},
expressionType: 'SIMPLE',
hasCustomLabel: true,
label: 'min',
},
{
aggregate: 'MAX',
column: {
column_name: 'SP_POP_TOTL',
id: 2,
type_generic: GenericDataType.NUMERIC,
},
expressionType: 'SIMPLE',
hasCustomLabel: true,
label: 'max',
},
],
}}
hooks={{
setDataMask: action('setDataMask'),
}}
/>
);
| superset-frontend/src/filters/components/Range/RangeFilterPlugin.stories.tsx | 0 | https://github.com/apache/superset/commit/60db35cb4d8462aeb4121e8a8b9eccee9c23621e | [
0.00017560251581016928,
0.00017344023217447102,
0.0001695802784524858,
0.0001742374588502571,
0.0000019147314560541417
] |
{
"id": 4,
"code_window": [
" \"snowflake\": [\n",
" \"snowflake-sqlalchemy==1.2.4\"\n",
" ], # PINNED! 1.2.5 introduced breaking changes requiring sqlalchemy>=1.4.0\n",
" \"teradata\": [\"sqlalchemy-teradata==0.9.0.dev0\"],\n",
" \"thumbnails\": [\"Pillow>=8.3.2, <9.0.0\"],\n",
" \"vertica\": [\"sqlalchemy-vertica-python>=0.5.9, < 0.6\"],\n",
" \"netezza\": [\"nzalchemy>=11.0.2\"],\n",
" },\n",
" python_requires=\"~=3.7\",\n",
" author=\"Apache Software Foundation\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"thumbnails\": [\"Pillow>=8.3.2, <10.0.0\"],\n"
],
"file_path": "setup.py",
"type": "replace",
"edit_start_line_idx": 162
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import io
import json
import os
import subprocess
import sys
from setuptools import find_packages, setup
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
PACKAGE_JSON = os.path.join(BASE_DIR, "superset-frontend", "package.json")
with open(PACKAGE_JSON, "r") as package_file:
version_string = json.load(package_file)["version"]
with io.open("README.md", "r", encoding="utf-8") as f:
long_description = f.read()
def get_git_sha() -> str:
try:
s = subprocess.check_output(["git", "rev-parse", "HEAD"])
return s.decode().strip()
except Exception:
return ""
GIT_SHA = get_git_sha()
version_info = {"GIT_SHA": GIT_SHA, "version": version_string}
print("-==-" * 15)
print("VERSION: " + version_string)
print("GIT SHA: " + GIT_SHA)
print("-==-" * 15)
VERSION_INFO_FILE = os.path.join(BASE_DIR, "superset", "static", "version_info.json")
with open(VERSION_INFO_FILE, "w") as version_file:
json.dump(version_info, version_file)
setup(
name="apache-superset",
description="A modern, enterprise-ready business intelligence web application",
long_description=long_description,
long_description_content_type="text/markdown",
version=version_string,
packages=find_packages(),
include_package_data=True,
zip_safe=False,
entry_points={"console_scripts": ["superset=superset.cli.main:superset"]},
install_requires=[
"backoff>=1.8.0",
"bleach>=3.0.2, <4.0.0",
"cachelib>=0.4.1,<0.5",
"celery>=4.3.0, <5.0.0, !=4.4.1",
"click<8",
"colorama",
"croniter>=0.3.28",
"cron-descriptor",
"cryptography>=3.3.2",
"deprecation>=2.1.0, <2.2.0",
"flask>=1.1.0, <2.0.0",
"flask-appbuilder>=3.4.3, <4.0.0",
"flask-caching>=1.10.0",
"flask-compress",
"flask-talisman",
"flask-migrate",
"flask-wtf",
"func_timeout",
"geopy",
"graphlib-backport",
"gunicorn>=20.1.0",
"holidays==0.10.3", # PINNED! https://github.com/dr-prodigy/python-holidays/issues/406
"humanize",
"itsdangerous>=1.0.0, <2.0.0", # https://github.com/apache/superset/pull/14627
"isodate",
"markdown>=3.0",
"msgpack>=1.0.0, <1.1",
"pandas>=1.3.0, <1.4",
"parsedatetime",
"pgsanity",
"polyline",
"pyparsing>=3.0.6, <4",
"python-dateutil",
"python-dotenv",
"python-geohash",
"pyarrow>=5.0.0, <6.0",
"pyyaml>=5.4",
"PyJWT>=1.7.1, <2",
"redis",
"selenium>=3.141.0",
"simplejson>=3.15.0",
"slackclient==2.5.0", # PINNED! slack changes file upload api in the future versions
"sqlalchemy>=1.3.16, <1.4, !=1.3.21",
"sqlalchemy-utils>=0.37.8, <0.38",
"sqlparse==0.3.0", # PINNED! see https://github.com/andialbrecht/sqlparse/issues/562
"tabulate==0.8.9",
# needed to support Literal (3.8) and TypeGuard (3.10)
"typing-extensions>=3.10, <4",
"wtforms-json",
],
extras_require={
"athena": ["pyathena>=1.10.8, <1.11"],
"aurora-data-api": ["preset-sqlalchemy-aurora-data-api>=0.2.8,<0.3"],
"bigquery": [
"pandas_gbq>=0.10.0",
"pybigquery>=0.4.10",
"google-cloud-bigquery>=2.4.0",
],
"clickhouse": ["clickhouse-sqlalchemy>=0.1.4, <0.2"],
"cockroachdb": ["cockroachdb>=0.3.5, <0.4"],
"cors": ["flask-cors>=2.0.0"],
"crate": ["crate[sqlalchemy]>=0.26.0, <0.27"],
"databricks": ["databricks-dbapi[sqlalchemy]>=0.5.0, <0.6"],
"db2": ["ibm-db-sa>=0.3.5, <0.4"],
"dremio": ["sqlalchemy-dremio>=1.1.5, <1.3"],
"drill": ["sqlalchemy-drill==0.1.dev"],
"druid": ["pydruid>=0.6.1,<0.7"],
"solr": ["sqlalchemy-solr >= 0.2.0"],
"elasticsearch": ["elasticsearch-dbapi>=0.2.0, <0.3.0"],
"exasol": ["sqlalchemy-exasol>=2.1.0, <2.2"],
"excel": ["xlrd>=1.2.0, <1.3"],
"firebird": ["sqlalchemy-firebird>=0.7.0, <0.8"],
"firebolt": ["firebolt-sqlalchemy>=0.0.1"],
"gsheets": ["shillelagh[gsheetsapi]>=1.0.3, <2"],
"hana": ["hdbcli==2.4.162", "sqlalchemy_hana==0.4.0"],
"hive": ["pyhive[hive]>=0.6.1", "tableschema", "thrift>=0.11.0, <1.0.0"],
"impala": ["impyla>0.16.2, <0.17"],
"kusto": ["sqlalchemy-kusto>=1.0.1, <2"],
"kylin": ["kylinpy>=2.8.1, <2.9"],
"mmsql": ["pymssql>=2.1.4, <2.2"],
"mysql": ["mysqlclient>=2.1.0, <3"],
"oracle": ["cx-Oracle>8.0.0, <8.1"],
"pinot": ["pinotdb>=0.3.3, <0.4"],
"postgres": ["psycopg2-binary==2.9.1"],
"presto": ["pyhive[presto]>=0.4.0"],
"trino": ["sqlalchemy-trino>=0.2"],
"prophet": ["prophet>=1.0.1, <1.1", "pystan<3.0"],
"redshift": ["sqlalchemy-redshift>=0.8.1, < 0.9"],
"rockset": ["rockset>=0.7.68, <0.8"],
"shillelagh": [
"shillelagh[datasetteapi,gsheetsapi,socrata,weatherapi]>=1.0.3, <2"
],
"snowflake": [
"snowflake-sqlalchemy==1.2.4"
], # PINNED! 1.2.5 introduced breaking changes requiring sqlalchemy>=1.4.0
"teradata": ["sqlalchemy-teradata==0.9.0.dev0"],
"thumbnails": ["Pillow>=8.3.2, <9.0.0"],
"vertica": ["sqlalchemy-vertica-python>=0.5.9, < 0.6"],
"netezza": ["nzalchemy>=11.0.2"],
},
python_requires="~=3.7",
author="Apache Software Foundation",
author_email="[email protected]",
url="https://superset.apache.org/",
download_url="https://www.apache.org/dist/superset/" + version_string,
classifiers=[
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
],
)
| setup.py | 1 | https://github.com/apache/superset/commit/60db35cb4d8462aeb4121e8a8b9eccee9c23621e | [
0.9318629503250122,
0.05531899258494377,
0.00016297632828354836,
0.00017576297977939248,
0.2130291759967804
] |
{
"id": 4,
"code_window": [
" \"snowflake\": [\n",
" \"snowflake-sqlalchemy==1.2.4\"\n",
" ], # PINNED! 1.2.5 introduced breaking changes requiring sqlalchemy>=1.4.0\n",
" \"teradata\": [\"sqlalchemy-teradata==0.9.0.dev0\"],\n",
" \"thumbnails\": [\"Pillow>=8.3.2, <9.0.0\"],\n",
" \"vertica\": [\"sqlalchemy-vertica-python>=0.5.9, < 0.6\"],\n",
" \"netezza\": [\"nzalchemy>=11.0.2\"],\n",
" },\n",
" python_requires=\"~=3.7\",\n",
" author=\"Apache Software Foundation\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"thumbnails\": [\"Pillow>=8.3.2, <10.0.0\"],\n"
],
"file_path": "setup.py",
"type": "replace",
"edit_start_line_idx": 162
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { t, ChartMetadata, ChartPlugin } from '@superset-ui/core';
import transformProps from './transformProps';
import thumbnail from './images/thumbnail.png';
import example1 from './images/WorldMap1.jpg';
import example2 from './images/WorldMap2.jpg';
import controlPanel from './controlPanel';
const metadata = new ChartMetadata({
category: t('Map'),
credits: ['http://datamaps.github.io/'],
description: t(
'A map of the world, that can indicate values in different countries.',
),
exampleGallery: [{ url: example1 }, { url: example2 }],
name: t('World Map'),
tags: [
t('2D'),
t('Aesthetic'),
t('Comparison'),
t('Intensity'),
t('Legacy'),
t('Multi-Dimensions'),
t('Multi-Layers'),
t('Multi-Variables'),
t('Scatter'),
t('Popular'),
],
thumbnail,
useLegacyApi: true,
});
export default class WorldMapChartPlugin extends ChartPlugin {
constructor() {
super({
loadChart: () => import('./ReactWorldMap'),
metadata,
transformProps,
controlPanel,
});
}
}
| superset-frontend/plugins/legacy-plugin-chart-world-map/src/index.js | 0 | https://github.com/apache/superset/commit/60db35cb4d8462aeb4121e8a8b9eccee9c23621e | [
0.00017782481154426932,
0.00017332904099021107,
0.0001689804921625182,
0.00017457616922911257,
0.0000032120162813953357
] |
{
"id": 4,
"code_window": [
" \"snowflake\": [\n",
" \"snowflake-sqlalchemy==1.2.4\"\n",
" ], # PINNED! 1.2.5 introduced breaking changes requiring sqlalchemy>=1.4.0\n",
" \"teradata\": [\"sqlalchemy-teradata==0.9.0.dev0\"],\n",
" \"thumbnails\": [\"Pillow>=8.3.2, <9.0.0\"],\n",
" \"vertica\": [\"sqlalchemy-vertica-python>=0.5.9, < 0.6\"],\n",
" \"netezza\": [\"nzalchemy>=11.0.2\"],\n",
" },\n",
" python_requires=\"~=3.7\",\n",
" author=\"Apache Software Foundation\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"thumbnails\": [\"Pillow>=8.3.2, <10.0.0\"],\n"
],
"file_path": "setup.py",
"type": "replace",
"edit_start_line_idx": 162
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from flask_appbuilder import Model
from sqlalchemy import Column, Integer, Text
from superset.models.helpers import AuditMixinNullable
class DynamicPlugin(Model, AuditMixinNullable):
id = Column(Integer, primary_key=True)
name = Column(Text, unique=True, nullable=False)
# key corresponds to viz_type from static plugins
key = Column(Text, unique=True, nullable=False)
bundle_url = Column(Text, unique=True, nullable=False)
def __repr__(self) -> str:
return str(self.name)
| superset/models/dynamic_plugins.py | 0 | https://github.com/apache/superset/commit/60db35cb4d8462aeb4121e8a8b9eccee9c23621e | [
0.00017644271429162472,
0.00017018146172631532,
0.00016360175504814833,
0.00017034067423082888,
0.000004716342573374277
] |
{
"id": 4,
"code_window": [
" \"snowflake\": [\n",
" \"snowflake-sqlalchemy==1.2.4\"\n",
" ], # PINNED! 1.2.5 introduced breaking changes requiring sqlalchemy>=1.4.0\n",
" \"teradata\": [\"sqlalchemy-teradata==0.9.0.dev0\"],\n",
" \"thumbnails\": [\"Pillow>=8.3.2, <9.0.0\"],\n",
" \"vertica\": [\"sqlalchemy-vertica-python>=0.5.9, < 0.6\"],\n",
" \"netezza\": [\"nzalchemy>=11.0.2\"],\n",
" },\n",
" python_requires=\"~=3.7\",\n",
" author=\"Apache Software Foundation\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"thumbnails\": [\"Pillow>=8.3.2, <10.0.0\"],\n"
],
"file_path": "setup.py",
"type": "replace",
"edit_start_line_idx": 162
} | {
"name": "@superset-ui/legacy-plugin-chart-chord",
"version": "0.18.25",
"description": "Superset Legacy Chart - Chord Diagram",
"sideEffects": [
"*.css"
],
"main": "lib/index.js",
"module": "esm/index.js",
"files": [
"esm",
"lib"
],
"repository": {
"type": "git",
"url": "git+https://github.com/apache-superset/superset-ui.git"
},
"keywords": [
"superset"
],
"author": "Superset",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/apache-superset/superset-ui/issues"
},
"homepage": "https://github.com/apache-superset/superset-ui#readme",
"publishConfig": {
"access": "public"
},
"dependencies": {
"d3": "^3.5.17",
"prop-types": "^15.6.2",
"react": "^16.13.1"
},
"peerDependencies": {
"@superset-ui/chart-controls": "*",
"@superset-ui/core": "*"
}
}
| superset-frontend/plugins/legacy-plugin-chart-chord/package.json | 0 | https://github.com/apache/superset/commit/60db35cb4d8462aeb4121e8a8b9eccee9c23621e | [
0.00017316477897111326,
0.00017060438403859735,
0.00016824493650346994,
0.0001705039176158607,
0.0000017547203015055857
] |
{
"id": 0,
"code_window": [
" // recommended when something is leaving screen\n",
" leavingScreen: 195,\n",
"};\n",
"\n",
"/**\n",
" * @param {string|Array} props\n",
" * @param {object} param\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"const formatMs = (miliseconds) => `${Math.round(miliseconds)}ms`;\n",
"const isString = (value) => typeof value === 'string';\n",
"const isNumber = (value) => !isNaN(parseFloat(value));\n",
"\n"
],
"file_path": "src/styles/transitions.js",
"type": "add",
"edit_start_line_idx": 35
} | // @flow weak
/* eslint-disable no-param-reassign */
import warning from 'warning';
// Follow https://material.google.com/motion/duration-easing.html#duration-easing-natural-easing-curves
// to learn the context in which each easing should be used.
const easingInternal = {
// This is the most common easing curve.
easeInOut: 'cubic-bezier(0.4, 0.0, 0.2, 1)',
// Objects enter the screen at full velocity from off-screen and
// slowly decelerate to a resting point.
easeOut: 'cubic-bezier(0.0, 0.0, 0.2, 1)',
// Objects leave the screen at full velocity. They do not decelerate when off-screen.
easeIn: 'cubic-bezier(0.4, 0.0, 1, 1)',
// The sharp curve is used by objects that may return to the screen at any time.
sharp: 'cubic-bezier(0.4, 0.0, 0.6, 1)',
};
// Follow https://material.io/guidelines/motion/duration-easing.html#duration-easing-common-durations
// to learn when use what timing
const durationInternal = {
shortest: 150,
shorter: 200,
short: 250,
// most basic recommended timing
standard: 300,
// this is to be used in complex animations
complex: 375,
// recommended when something is entering screen
enteringScreen: 225,
// recommended when something is leaving screen
leavingScreen: 195,
};
/**
* @param {string|Array} props
* @param {object} param
* @param {string} param.prop
* @param {number} param.duration
* @param {string} param.easing
* @param {number} param.delay
*/
export default {
easing: easingInternal,
duration: durationInternal,
create(props = ['all'], {
duration = durationInternal.standard,
easing = easingInternal.easeInOut,
delay = 0,
...other
} = {}) {
warning(typeof props === 'string' || Array.isArray(props),
'argument "props" must be a string or Array');
warning(Number.isInteger(duration),
'argument "duration" must be a number');
warning(typeof easing === 'string',
'argument "easing" must be a string');
warning(Number.isInteger(delay),
'argument "delay" must be a string');
warning(Object.keys(other).length === 0,
`unrecognized argument(s) [${Object.keys(other).join(',')}]`);
return (Array.isArray(props) ? props : [props])
.map((value) => `${value} ${duration}ms ${easing} ${delay}ms`)
.join(',');
},
getAutoHeightDuration(height) {
if (!height) {
return 0;
}
const constant = height / 36;
const duration = (4 + (15 * (constant ** 0.25)) + (constant / 5)) * 10;
return Math.round(duration);
},
};
/**
* @deprecated Will be removed, please access via theme.transitions.easing
*/
export const easing = easingInternal;
/**
* @deprecated Will be removed, please access via theme.transitions.duration
*/
export const duration = durationInternal;
| src/styles/transitions.js | 1 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.04245125129818916,
0.004435568116605282,
0.00016620304086245596,
0.00019680429250001907,
0.012672006152570248
] |
{
"id": 0,
"code_window": [
" // recommended when something is leaving screen\n",
" leavingScreen: 195,\n",
"};\n",
"\n",
"/**\n",
" * @param {string|Array} props\n",
" * @param {object} param\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"const formatMs = (miliseconds) => `${Math.round(miliseconds)}ms`;\n",
"const isString = (value) => typeof value === 'string';\n",
"const isNumber = (value) => !isNaN(parseFloat(value));\n",
"\n"
],
"file_path": "src/styles/transitions.js",
"type": "add",
"edit_start_line_idx": 35
} | # Paper
In material design, the physical properties of [paper](https://material.google.com/layout/principles.html#principles-how-paper-works) are translated to the screen.
The background of an application resembles the flat, opaque texture of a sheet of paper, and an application’s behavior mimics paper’s ability to be re-sized, shuffled, and bound together in multiple sheets.
{{demo='demos/paper/PaperSheet.js'}}
| docs/site/src/demos/paper/paper.md | 0 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.0001642935094423592,
0.0001642935094423592,
0.0001642935094423592,
0.0001642935094423592,
0
] |
{
"id": 0,
"code_window": [
" // recommended when something is leaving screen\n",
" leavingScreen: 195,\n",
"};\n",
"\n",
"/**\n",
" * @param {string|Array} props\n",
" * @param {object} param\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"const formatMs = (miliseconds) => `${Math.round(miliseconds)}ms`;\n",
"const isString = (value) => typeof value === 'string';\n",
"const isNumber = (value) => !isNaN(parseFloat(value));\n",
"\n"
],
"file_path": "src/styles/transitions.js",
"type": "add",
"edit_start_line_idx": 35
} | <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M24 12c2.21 0 4-1.79 4-4 0-.75-.21-1.46-.57-2.06L24 0l-3.43 5.94C20.21 6.54 20 7.25 20 8c0 2.21 1.79 4 4 4zm9.19 19.97l-2.15-2.15-2.16 2.15c-2.61 2.61-7.17 2.61-9.78 0l-2.15-2.15-2.16 2.15C13.5 33.28 11.77 34 9.92 34c-1.45 0-2.8-.46-3.92-1.23V42c0 1.1.9 2 2 2h32c1.1 0 2-.9 2-2v-9.23c-1.12.77-2.46 1.23-3.92 1.23-1.85 0-3.58-.72-4.89-2.03zM36 18H26v-4h-4v4H12c-3.31 0-6 2.69-6 6v3.08C6 29.24 7.76 31 9.92 31c1.05 0 2.03-.41 2.77-1.15l4.28-4.27 4.27 4.26c1.48 1.48 4.06 1.48 5.54 0l4.28-4.26 4.27 4.26c.74.74 1.72 1.15 2.77 1.15 2.16 0 3.92-1.76 3.92-3.92V24c-.02-3.31-2.71-6-6.02-6z"/></svg> | packages/icon-builder/test/fixtures/material-design-icons/svg/social/svg/production/ic_cake_48px.svg | 0 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.00019067639368586242,
0.00019067639368586242,
0.00019067639368586242,
0.00019067639368586242,
0
] |
{
"id": 0,
"code_window": [
" // recommended when something is leaving screen\n",
" leavingScreen: 195,\n",
"};\n",
"\n",
"/**\n",
" * @param {string|Array} props\n",
" * @param {object} param\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"const formatMs = (miliseconds) => `${Math.round(miliseconds)}ms`;\n",
"const isString = (value) => typeof value === 'string';\n",
"const isNumber = (value) => !isNaN(parseFloat(value));\n",
"\n"
],
"file_path": "src/styles/transitions.js",
"type": "add",
"edit_start_line_idx": 35
} | // @flow weak
const { jsdom } = require('jsdom');
function createDOM() {
global.document = jsdom('');
global.window = document.defaultView;
Object.keys(document.defaultView).forEach((property) => {
if (typeof global[property] === 'undefined') {
global[property] = document.defaultView[property];
}
});
global.navigator = {
userAgent: 'node.js',
};
}
module.exports = createDOM;
| test/utils/dom.js | 0 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.00016854536079335958,
0.0001683899317868054,
0.00016823451733216643,
0.0001683899317868054,
1.5542173059657216e-7
] |
{
"id": 1,
"code_window": [
" duration = durationInternal.standard,\n",
" easing = easingInternal.easeInOut,\n",
" delay = 0,\n",
" ...other\n",
" } = {}) {\n",
" warning(typeof props === 'string' || Array.isArray(props),\n",
" 'argument \"props\" must be a string or Array');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" warning(isString(props) || Array.isArray(props),\n"
],
"file_path": "src/styles/transitions.js",
"type": "replace",
"edit_start_line_idx": 54
} | // @flow weak
/* eslint-disable no-param-reassign */
import warning from 'warning';
// Follow https://material.google.com/motion/duration-easing.html#duration-easing-natural-easing-curves
// to learn the context in which each easing should be used.
const easingInternal = {
// This is the most common easing curve.
easeInOut: 'cubic-bezier(0.4, 0.0, 0.2, 1)',
// Objects enter the screen at full velocity from off-screen and
// slowly decelerate to a resting point.
easeOut: 'cubic-bezier(0.0, 0.0, 0.2, 1)',
// Objects leave the screen at full velocity. They do not decelerate when off-screen.
easeIn: 'cubic-bezier(0.4, 0.0, 1, 1)',
// The sharp curve is used by objects that may return to the screen at any time.
sharp: 'cubic-bezier(0.4, 0.0, 0.6, 1)',
};
// Follow https://material.io/guidelines/motion/duration-easing.html#duration-easing-common-durations
// to learn when use what timing
const durationInternal = {
shortest: 150,
shorter: 200,
short: 250,
// most basic recommended timing
standard: 300,
// this is to be used in complex animations
complex: 375,
// recommended when something is entering screen
enteringScreen: 225,
// recommended when something is leaving screen
leavingScreen: 195,
};
/**
* @param {string|Array} props
* @param {object} param
* @param {string} param.prop
* @param {number} param.duration
* @param {string} param.easing
* @param {number} param.delay
*/
export default {
easing: easingInternal,
duration: durationInternal,
create(props = ['all'], {
duration = durationInternal.standard,
easing = easingInternal.easeInOut,
delay = 0,
...other
} = {}) {
warning(typeof props === 'string' || Array.isArray(props),
'argument "props" must be a string or Array');
warning(Number.isInteger(duration),
'argument "duration" must be a number');
warning(typeof easing === 'string',
'argument "easing" must be a string');
warning(Number.isInteger(delay),
'argument "delay" must be a string');
warning(Object.keys(other).length === 0,
`unrecognized argument(s) [${Object.keys(other).join(',')}]`);
return (Array.isArray(props) ? props : [props])
.map((value) => `${value} ${duration}ms ${easing} ${delay}ms`)
.join(',');
},
getAutoHeightDuration(height) {
if (!height) {
return 0;
}
const constant = height / 36;
const duration = (4 + (15 * (constant ** 0.25)) + (constant / 5)) * 10;
return Math.round(duration);
},
};
/**
* @deprecated Will be removed, please access via theme.transitions.easing
*/
export const easing = easingInternal;
/**
* @deprecated Will be removed, please access via theme.transitions.duration
*/
export const duration = durationInternal;
| src/styles/transitions.js | 1 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.9966754913330078,
0.2957598567008972,
0.0001744328619679436,
0.0016306804027408361,
0.4493922293186188
] |
{
"id": 1,
"code_window": [
" duration = durationInternal.standard,\n",
" easing = easingInternal.easeInOut,\n",
" delay = 0,\n",
" ...other\n",
" } = {}) {\n",
" warning(typeof props === 'string' || Array.isArray(props),\n",
" 'argument \"props\" must be a string or Array');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" warning(isString(props) || Array.isArray(props),\n"
],
"file_path": "src/styles/transitions.js",
"type": "replace",
"edit_start_line_idx": 54
} | 'use strict';
// import all rules in lib/rules
module.exports.rules = {
'docgen-ignore-before-comment': require('./rules/docgen-ignore-before-comment'),
};
// import processors
module.exports.processors = {
// add your processors here
};
| packages/eslint-plugin-material-ui/lib/index.js | 0 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.00017621608276385814,
0.0001743971079122275,
0.0001725781476125121,
0.0001743971079122275,
0.000001818967575673014
] |
{
"id": 1,
"code_window": [
" duration = durationInternal.standard,\n",
" easing = easingInternal.easeInOut,\n",
" delay = 0,\n",
" ...other\n",
" } = {}) {\n",
" warning(typeof props === 'string' || Array.isArray(props),\n",
" 'argument \"props\" must be a string or Array');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" warning(isString(props) || Array.isArray(props),\n"
],
"file_path": "src/styles/transitions.js",
"type": "replace",
"edit_start_line_idx": 54
} | // @flow weak
import addEventListener from 'dom-helpers/events/on';
import removeEventListener from 'dom-helpers/events/off';
export default function (node, event, handler, options) {
addEventListener(node, event, handler, options);
return {
remove() {
removeEventListener(node, event, handler, options);
},
};
}
| src/utils/addEventListener.js | 0 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.0001746237394399941,
0.0001743203029036522,
0.00017401688091922551,
0.0001743203029036522,
3.034292603842914e-7
] |
{
"id": 1,
"code_window": [
" duration = durationInternal.standard,\n",
" easing = easingInternal.easeInOut,\n",
" delay = 0,\n",
" ...other\n",
" } = {}) {\n",
" warning(typeof props === 'string' || Array.isArray(props),\n",
" 'argument \"props\" must be a string or Array');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" warning(isString(props) || Array.isArray(props),\n"
],
"file_path": "src/styles/transitions.js",
"type": "replace",
"edit_start_line_idx": 54
} | // @flow weak
/* eslint-env mocha */
import React from 'react';
import { assert } from 'chai';
import { createShallowWithContext } from 'test/utils';
import Chip, { styleSheet } from './Chip.js';
import Avatar from '../Avatar/Avatar.js';
describe('<Chip />', () => {
let shallow;
let classes;
before(() => {
shallow = createShallowWithContext();
classes = shallow.context.styleManager.render(styleSheet);
});
describe('text only', () => {
let wrapper;
before(() => {
wrapper = shallow(
<Chip
className="my-Chip"
data-my-prop="woof"
>
Text Chip
</Chip>,
);
});
it('should render a button containing a span', () => {
assert.strictEqual(wrapper.is('button'), true, 'should be a button');
assert.strictEqual(wrapper.childAt(0).is('span'), true, 'should be a span');
});
it('should merge user classes & spread custom props to the root node', () => {
assert.strictEqual(wrapper.hasClass(classes.root), true);
assert.strictEqual(wrapper.hasClass('my-Chip'), true);
assert.strictEqual(wrapper.prop('data-my-prop'), 'woof');
});
it('should have a tabIndex prop with value -1', () => {
assert.strictEqual(wrapper.prop('tabIndex'), -1);
});
});
describe('clickable text chip', () => {
let wrapper;
let handleClick;
before(() => {
handleClick = () => {};
wrapper = shallow(
<Chip
className="my-Chip"
data-my-prop="woof"
onClick={handleClick}
>
Text Chip
</Chip>,
);
});
it('should render a button containing a span', () => {
assert.strictEqual(wrapper.is('button'), true, 'should be a button');
assert.strictEqual(wrapper.childAt(0).is('span'), true, 'should be a span');
});
it('should merge user classes & spread custom props to the root node', () => {
assert.strictEqual(wrapper.hasClass(classes.root), true);
assert.strictEqual(wrapper.hasClass('my-Chip'), true);
assert.strictEqual(wrapper.prop('data-my-prop'), 'woof');
assert.strictEqual(wrapper.prop('onClick'), handleClick);
});
it('should not have a tabIndex prop', () => {
assert.strictEqual(wrapper.prop('tabIndex'), undefined);
});
it('should apply user value of tabIndex', () => {
wrapper = shallow(
<Chip
onClick={() => {}}
tabIndex={5} // eslint-disable-line jsx-a11y/tabindex-no-positive
>
Text Chip
</Chip>,
);
assert.strictEqual(wrapper.prop('tabIndex'), 5);
});
});
describe('deletable Avatar chip', () => {
let wrapper;
before(() => {
wrapper = shallow(
<Chip
avatar={
<Avatar className="my-Avatar" data-my-prop="woof">
MB
</Avatar>
}
label="Text Avatar Chip"
onRequestDelete={() => {}}
className="my-Chip"
data-my-prop="woof"
/>,
);
});
it('should render a button containing an Avatar, span and svg', () => {
assert.strictEqual(wrapper.is('button'), true, 'should be a button');
assert.strictEqual(wrapper.childAt(0).is('Avatar'), true, 'should have an Avatar');
assert.strictEqual(wrapper.childAt(1).is('span'), true, 'should have a span');
assert.strictEqual(wrapper.childAt(2).is('pure(Cancel)'), true,
'should be an svg icon');
});
it('should merge user classes & spread custom props to the root node', () => {
assert.strictEqual(wrapper.hasClass(classes.root), true);
assert.strictEqual(wrapper.hasClass('my-Chip'), true);
assert.strictEqual(wrapper.prop('data-my-prop'), 'woof');
});
it('should merge user classes & spread custom props to the Avatar node', () => {
assert.strictEqual(wrapper.childAt(0).hasClass(classes.avatar), true);
assert.strictEqual(wrapper.childAt(0).hasClass('my-Avatar'), true);
assert.strictEqual(wrapper.childAt(0).prop('data-my-prop'), 'woof');
});
it('should not have a tabIndex prop', () => {
assert.strictEqual(wrapper.prop('tabIndex'), undefined);
});
});
});
| src/Chip/Chip.spec.js | 0 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.00017614770331420004,
0.00017228924843948334,
0.00016912039427552372,
0.00017230788944289088,
0.0000019975873328803573
] |
{
"id": 2,
"code_window": [
" 'argument \"props\" must be a string or Array');\n",
" warning(Number.isInteger(duration),\n",
" 'argument \"duration\" must be a number');\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [
" warning(isNumber(duration),\n"
],
"file_path": "src/styles/transitions.js",
"type": "replace",
"edit_start_line_idx": 56
} | // @flow weak
/* eslint-disable no-param-reassign */
import warning from 'warning';
// Follow https://material.google.com/motion/duration-easing.html#duration-easing-natural-easing-curves
// to learn the context in which each easing should be used.
const easingInternal = {
// This is the most common easing curve.
easeInOut: 'cubic-bezier(0.4, 0.0, 0.2, 1)',
// Objects enter the screen at full velocity from off-screen and
// slowly decelerate to a resting point.
easeOut: 'cubic-bezier(0.0, 0.0, 0.2, 1)',
// Objects leave the screen at full velocity. They do not decelerate when off-screen.
easeIn: 'cubic-bezier(0.4, 0.0, 1, 1)',
// The sharp curve is used by objects that may return to the screen at any time.
sharp: 'cubic-bezier(0.4, 0.0, 0.6, 1)',
};
// Follow https://material.io/guidelines/motion/duration-easing.html#duration-easing-common-durations
// to learn when use what timing
const durationInternal = {
shortest: 150,
shorter: 200,
short: 250,
// most basic recommended timing
standard: 300,
// this is to be used in complex animations
complex: 375,
// recommended when something is entering screen
enteringScreen: 225,
// recommended when something is leaving screen
leavingScreen: 195,
};
/**
* @param {string|Array} props
* @param {object} param
* @param {string} param.prop
* @param {number} param.duration
* @param {string} param.easing
* @param {number} param.delay
*/
export default {
easing: easingInternal,
duration: durationInternal,
create(props = ['all'], {
duration = durationInternal.standard,
easing = easingInternal.easeInOut,
delay = 0,
...other
} = {}) {
warning(typeof props === 'string' || Array.isArray(props),
'argument "props" must be a string or Array');
warning(Number.isInteger(duration),
'argument "duration" must be a number');
warning(typeof easing === 'string',
'argument "easing" must be a string');
warning(Number.isInteger(delay),
'argument "delay" must be a string');
warning(Object.keys(other).length === 0,
`unrecognized argument(s) [${Object.keys(other).join(',')}]`);
return (Array.isArray(props) ? props : [props])
.map((value) => `${value} ${duration}ms ${easing} ${delay}ms`)
.join(',');
},
getAutoHeightDuration(height) {
if (!height) {
return 0;
}
const constant = height / 36;
const duration = (4 + (15 * (constant ** 0.25)) + (constant / 5)) * 10;
return Math.round(duration);
},
};
/**
* @deprecated Will be removed, please access via theme.transitions.easing
*/
export const easing = easingInternal;
/**
* @deprecated Will be removed, please access via theme.transitions.duration
*/
export const duration = durationInternal;
| src/styles/transitions.js | 1 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.2830713987350464,
0.02982998453080654,
0.0001664280571276322,
0.00109415827319026,
0.08444186300039291
] |
{
"id": 2,
"code_window": [
" 'argument \"props\" must be a string or Array');\n",
" warning(Number.isInteger(duration),\n",
" 'argument \"duration\" must be a number');\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [
" warning(isNumber(duration),\n"
],
"file_path": "src/styles/transitions.js",
"type": "replace",
"edit_start_line_idx": 56
} | // @flow weak
import React, { Component } from 'react';
import EventListener from 'react-event-listener';
import createHelper from 'recompose/createHelper';
import createEagerFactory from 'recompose/createEagerFactory';
import customPropTypes from '../utils/customPropTypes';
import { keys } from '../styles/breakpoints';
export const isWidthUp = (baseWidth, width) => (
keys.indexOf(baseWidth) <= keys.indexOf(width)
);
export const isWidthDown = (baseWidth, width) => (
keys.indexOf(baseWidth) > keys.indexOf(width)
);
function withWidth(options = {}) {
const {
resizeInterval = 166, // Corresponds to 10 frames at 60 Hz.
} = options;
return (BaseComponent) => {
const factory = createEagerFactory(BaseComponent);
return class WithWidth extends Component {
static contextTypes = {
theme: customPropTypes.muiRequired,
};
state = {
width: null,
};
componentDidMount() {
this.updateWidth(window.innerWidth);
}
componentWillUnmount() {
clearTimeout(this.deferTimer);
}
deferTimer = null;
handleResize = () => {
clearTimeout(this.deferTimer);
this.deferTimer = setTimeout(() => {
this.updateWidth(window.innerWidth);
}, resizeInterval);
};
updateWidth(innerWidth) {
const breakpoints = this.context.theme.breakpoints;
let width = null;
/**
* Start with the slowest value as low end devices often have a small screen.
*
* innerWidth |0 xs sm md lg xl
* |-------|-------|-------|-------|-------|------>
* width | xs | xs | sm | md | lg | xl
*/
let index = 1;
while (width === null && index < breakpoints.keys.length) {
const currentWidth = breakpoints.keys[index];
if (innerWidth < breakpoints.getWidth(currentWidth)) {
width = breakpoints.keys[index - 1];
break;
}
index += 1;
}
width = width || 'xl';
if (width !== this.state.width) {
this.setState({
width,
});
}
}
render() {
const width = this.state.width;
/**
* When rendering the component on the server,
* we have no idea about the screen width.
* In order to prevent blinks and help the reconciliation
* we are not rendering the component.
*
* A better alternative would be to send client hints.
* But the browser support of this API is low:
* http://caniuse.com/#search=client%20hint
*/
if (width === null) {
return null;
}
return (
<EventListener target="window" onResize={this.handleResize}>
{factory({
width,
...this.props,
})}
</EventListener>
);
}
};
};
}
export default createHelper(withWidth, 'withWidth');
| src/utils/withWidth.js | 0 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.0004022146458737552,
0.0001924828247865662,
0.0001662268041400239,
0.0001700530992820859,
0.00006374100485118106
] |
{
"id": 2,
"code_window": [
" 'argument \"props\" must be a string or Array');\n",
" warning(Number.isInteger(duration),\n",
" 'argument \"duration\" must be a number');\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [
" warning(isNumber(duration),\n"
],
"file_path": "src/styles/transitions.js",
"type": "replace",
"edit_start_line_idx": 56
} | // @flow weak
import React, { Component, PropTypes } from 'react';
import classNames from 'classnames';
import { createStyleSheet } from 'jss-theme-reactor';
import customPropTypes from '../utils/customPropTypes';
function isDirty(obj) {
return obj && obj.value && obj.value.length > 0;
}
export const styleSheet = createStyleSheet('MuiInput', (theme) => {
const { palette, transitions } = theme;
return {
wrapper: {
// Mimics the default input display property used by browsers for an input.
display: 'inline-block',
position: 'relative',
},
formControl: {
marginTop: 10,
marginBottom: 10,
},
inkbar: {
'&:after': {
backgroundColor: palette.accent.A200,
left: 0,
bottom: -1,
// Doing the other way around crash on IE11 "''"" https://github.com/cssinjs/jss/issues/242
content: '""',
height: 2,
position: 'absolute',
right: 0,
transform: 'scaleX(0)',
transition: transitions.create('transform', {
duration: transitions.duration.shorter,
easing: transitions.easing.easeOut,
}),
},
'&$focused:after': {
transform: 'scaleX(1)',
},
},
focused: {},
error: {
'&:after': {
backgroundColor: palette.error[500],
transform: 'scaleX(1)', // error is always underlined in red
},
},
input: {
font: 'inherit',
padding: '6px 0',
border: 0,
display: 'block',
verticalAlign: 'middle',
whiteSpace: 'normal',
background: 'none',
lineHeight: 1,
appearance: 'textfield', // Improve type search style.
color: theme.palette.text.primary,
width: '100%',
'&:focus': {
outline: 0,
},
'&::-webkit-search-decoration': { // Remove the padding when type=search.
appearance: 'none',
},
},
disabled: {
color: theme.palette.text.disabled,
cursor: 'not-allowed',
},
underline: {
borderBottom: `1px solid ${theme.palette.text.divider}`,
'&$disabled': {
borderBottomStyle: 'dotted',
},
},
};
});
/**
* Input
*/
export default class Input extends Component {
static propTypes = {
/**
* The CSS class name of the wrapper element.
*/
className: PropTypes.string,
/**
* The element or component used for the root node.
*/
component: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
/**
* If `true`, the input will be disabled.
*/
disabled: PropTypes.bool,
error: PropTypes.bool,
/**
* The CSS class name of the input element.
*/
inputClassName: PropTypes.string,
/**
* @ignore
*/
onBlur: PropTypes.func,
/**
* @ignore
*/
onChange: PropTypes.func,
/**
* @ignore
*/
onClean: PropTypes.func,
/**
* @ignore
*/
onDirty: PropTypes.func,
/**
* @ignore
*/
onFocus: PropTypes.func,
/**
* Type of the input element. It should be a valid HTML5 input type.
*/
type: PropTypes.string,
/**
* If set to true, the input will have an underline.
*/
underline: PropTypes.bool,
/**
* The input value, required for a controlled component.
*/
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
};
static defaultProps = {
component: 'input',
disabled: false,
type: 'text',
underline: true,
};
static contextTypes = {
muiFormControl: PropTypes.object,
styleManager: customPropTypes.muiRequired,
};
state = {
focused: false,
};
componentWillMount() {
if (this.isControlled()) {
this.checkDirty(this.props);
}
}
componentDidMount() {
if (!this.isControlled()) {
this.checkDirty(this.input);
}
}
componentWillUpdate(nextProps) {
if (this.isControlled()) {
this.checkDirty(nextProps);
}
}
// Holds the input reference
input = null;
focus = () => this.input.focus();
handleFocus = (event) => {
this.setState({ focused: true });
if (this.props.onFocus) {
this.props.onFocus(event);
}
};
handleBlur = (event) => {
this.setState({ focused: false });
if (this.props.onBlur) {
this.props.onBlur(event);
}
};
handleChange = (event) => {
if (!this.isControlled()) {
this.checkDirty(this.input);
}
if (this.props.onChange) {
this.props.onChange(event);
}
};
isControlled() {
return typeof this.props.value === 'string';
}
checkDirty(obj) {
const { muiFormControl } = this.context;
if (isDirty(obj)) {
if (muiFormControl && muiFormControl.onDirty) {
muiFormControl.onDirty();
}
if (this.props.onDirty) {
this.props.onDirty();
}
return;
}
if (muiFormControl && muiFormControl.onClean) {
muiFormControl.onClean();
}
if (this.props.onClean) {
this.props.onClean();
}
}
render() {
const {
className: classNameProp,
component: ComponentProp,
inputClassName: inputClassNameProp,
disabled,
error: errorProp,
onBlur, // eslint-disable-line no-unused-vars
onFocus, // eslint-disable-line no-unused-vars
onChange, // eslint-disable-line no-unused-vars
underline,
...other
} = this.props;
const { muiFormControl, styleManager } = this.context;
const classes = styleManager.render(styleSheet);
let error = errorProp;
if (typeof error === 'undefined' && muiFormControl) {
error = muiFormControl.error;
}
const wrapperClassName = classNames(classes.wrapper, {
[classes.formControl]: muiFormControl,
[classes.inkbar]: underline,
[classes.focused]: this.state.focused,
[classes.error]: error,
}, classNameProp);
const inputClassName = classNames(classes.input, {
[classes.underline]: underline,
[classes.disabled]: disabled,
}, inputClassNameProp);
const required = muiFormControl && muiFormControl.required === true;
return (
<div className={wrapperClassName}>
<ComponentProp
ref={(c) => { this.input = c; }}
className={inputClassName}
onBlur={this.handleBlur}
onFocus={this.handleFocus}
onChange={this.handleChange}
disabled={disabled}
aria-required={required ? true : undefined}
{...other}
/>
</div>
);
}
}
| src/Input/Input.js | 0 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.003200308885425329,
0.00036774022737517953,
0.0001662758004385978,
0.00017219630535691977,
0.0005663657793775201
] |
{
"id": 2,
"code_window": [
" 'argument \"props\" must be a string or Array');\n",
" warning(Number.isInteger(duration),\n",
" 'argument \"duration\" must be a number');\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [
" warning(isNumber(duration),\n"
],
"file_path": "src/styles/transitions.js",
"type": "replace",
"edit_start_line_idx": 56
} | // @flow weak
import { cloneElement, Children, isValidElement } from 'react';
export function cloneChildrenWithClassName(children, className) {
return Children.map(children, (child) => {
return isValidElement(child) && cloneElement(child, {
className: child.props.hasOwnProperty('className') ?
`${child.props.className} ${className}` : className,
});
});
}
| src/utils/reactHelpers.js | 0 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.00028909166576340795,
0.00023235722619574517,
0.0001756227866280824,
0.00023235722619574517,
0.000056734439567662776
] |
{
"id": 3,
"code_window": [
" 'argument \"duration\" must be a number');\n",
" warning(typeof easing === 'string',\n",
" 'argument \"easing\" must be a string');\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [
" warning(isString(easing),\n"
],
"file_path": "src/styles/transitions.js",
"type": "replace",
"edit_start_line_idx": 58
} | // @flow weak
/* eslint-env mocha */
import { assert } from 'chai';
import { stub } from 'sinon';
import transitions, { easing, duration } from './transitions';
describe('transitions', () => {
let consoleErrorStub;
beforeEach(() => {
consoleErrorStub = stub(console, 'error');
});
afterEach(() => {
consoleErrorStub.restore();
});
describe('create() function', () => {
it('should create default transition withnout arguments', () => {
const transition = transitions.create();
assert.strictEqual(transition, `all ${duration.standard}ms ${easing.easeInOut} 0ms`);
assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()');
});
it('should take string props as a first argument', () => {
const transition = transitions.create('color');
assert.strictEqual(transition, `color ${duration.standard}ms ${easing.easeInOut} 0ms`);
assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()');
});
it('should also take array of props as first argument', () => {
const options = { delay: 20 };
const multiple = transitions.create(['color', 'size'], options);
const single1 = transitions.create('color', options);
const single2 = transitions.create('size', options);
const expected = `${single1},${single2}`;
assert.strictEqual(multiple, expected);
assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()');
});
it('should warn when first argument is of bad type', () => {
transitions.create(5554);
transitions.create({});
assert.strictEqual(consoleErrorStub.callCount, 2, 'Wrong number of calls of warning()');
});
it('should optionally accept number "duration" option in second argument', () => {
const transition = transitions.create('font', { duration: 500 });
assert.strictEqual(transition, `font 500ms ${easing.easeInOut} 0ms`);
assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()');
});
it('should warn when bad "duration" option type', () => {
transitions.create('font', { duration: '' });
transitions.create('font', { duration: {} });
assert.strictEqual(consoleErrorStub.callCount, 2, 'Wrong number of calls of warning()');
});
it('should optionally accept string "easing" option in second argument', () => {
const transition = transitions.create('transform', { easing: easing.sharp });
assert.strictEqual(transition, `transform ${duration.standard}ms ${easing.sharp} 0ms`);
assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()');
});
it('should warn when bad "easing" option type', () => {
transitions.create('transform', { easing: 123 });
transitions.create('transform', { easing: {} });
assert.strictEqual(consoleErrorStub.callCount, 2, 'Wrong number of calls of warning()');
});
it('should optionally accept number "delay" option in second argument', () => {
const transition = transitions.create('size', { delay: 150 });
assert.strictEqual(transition, `size ${duration.standard}ms ${easing.easeInOut} 150ms`);
assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()');
});
it('should warn when bad "delay" option type', () => {
transitions.create('size', { delay: '' });
transitions.create('size', { delay: {} });
assert.strictEqual(consoleErrorStub.callCount, 2, 'Wrong number of calls of warning()');
});
it('should warn when passed unrecognized option', () => {
transitions.create('size', { fffds: 'value' });
assert.strictEqual(consoleErrorStub.callCount, 1, 'Wrong number of calls of warning()');
});
});
});
| src/styles/transitions.spec.js | 1 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.4998582899570465,
0.1152094304561615,
0.00016997366037685424,
0.035146504640579224,
0.1748248189687729
] |
{
"id": 3,
"code_window": [
" 'argument \"duration\" must be a number');\n",
" warning(typeof easing === 'string',\n",
" 'argument \"easing\" must be a string');\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [
" warning(isString(easing),\n"
],
"file_path": "src/styles/transitions.js",
"type": "replace",
"edit_start_line_idx": 58
} | // @flow weak
import React from 'react';
import { createStyleSheet } from 'jss-theme-reactor';
import customPropTypes from 'material-ui/utils/customPropTypes';
import {
Card,
CardContent,
CardActions,
} from 'material-ui/Card';
import Button from 'material-ui/Button';
import Text from 'material-ui/Text';
const styleSheet = createStyleSheet('SimpleCard', (theme) => ({
card: { minWidth: 275 },
bullet: {
display: 'inline-block',
margin: '0 2px',
transform: 'scale(0.8)',
},
title: {
marginBottom: 16,
fontSize: 14,
color: theme.palette.text.secondary,
},
pos: {
marginBottom: 12,
color: theme.palette.text.secondary,
},
}));
export default function SimpleCard(props, context) {
const classes = context.styleManager.render(styleSheet);
const bull = <span className={classes.bullet}>•</span>;
return (
<div>
<Card className={classes.card}>
<CardContent>
<Text type="body1" className={classes.title}>Word of the Day</Text>
<Text type="headline" component="h2">
be{bull}nev{bull}o{bull}lent
</Text>
<Text type="body1" className={classes.pos}>adjective</Text>
<Text component="p">
well meaning and kindly.<br />
{'"a benevolent smile"'}
</Text>
</CardContent>
<CardActions>
<Button compact>Learn More</Button>
</CardActions>
</Card>
</div>
);
}
SimpleCard.contextTypes = {
styleManager: customPropTypes.muiRequired,
};
| docs/site/src/demos/cards/SimpleCard.js | 0 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.0001755228586262092,
0.000170943807461299,
0.00016768295608926564,
0.00017043473781086504,
0.0000028529686915135244
] |
{
"id": 3,
"code_window": [
" 'argument \"duration\" must be a number');\n",
" warning(typeof easing === 'string',\n",
" 'argument \"easing\" must be a string');\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [
" warning(isString(easing),\n"
],
"file_path": "src/styles/transitions.js",
"type": "replace",
"edit_start_line_idx": 58
} | TableBody
=========
A material table body.
```jsx
<TableBody>
<TableRow>....</TableRow>
</TableBody>
```
Props
-----
| Name | Type | Default | Description |
|:-----|:-----|:--------|:------------|
| children | node | | Should be valid `<tbody>` children such as `TableRow`. |
| className | string | | The CSS class name of the root element. |
Any other properties supplied will be spread to the root element.
| docs/api/Table/TableBody.md | 0 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.0010312559315934777,
0.00045848681475035846,
0.00016678313841111958,
0.00017742137424647808,
0.00040503221680410206
] |
{
"id": 3,
"code_window": [
" 'argument \"duration\" must be a number');\n",
" warning(typeof easing === 'string',\n",
" 'argument \"easing\" must be a string');\n"
],
"labels": [
"keep",
"replace",
"keep"
],
"after_edit": [
" warning(isString(easing),\n"
],
"file_path": "src/styles/transitions.js",
"type": "replace",
"edit_start_line_idx": 58
} | TableSortLabel
==============
A button based label for placing inside `TableCell` for column sorting.
Props
-----
| Name | Type | Default | Description |
|:-----|:-----|:--------|:------------|
| active | bool | false | If set to true, will have the active styling (should be true for the sorted column). |
| children | node | | Label contents, the arrow will be appended automatically and aligned using flexbox. |
| className | string | | The CSS class name of the root element. |
| direction | enum: 'asc'<br> 'desc'<br> | 'desc' | The current sort direction. |
Any other properties supplied will be spread to the root element.
| docs/api/Table/TableSortLabel.md | 0 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.0005218250444158912,
0.0003451082739047706,
0.0001683914742898196,
0.0003451082739047706,
0.00017671678506303579
] |
{
"id": 4,
"code_window": [
" 'argument \"easing\" must be a string');\n",
" warning(Number.isInteger(delay),\n",
" 'argument \"delay\" must be a string');\n",
" warning(Object.keys(other).length === 0,\n",
" `unrecognized argument(s) [${Object.keys(other).join(',')}]`);\n",
"\n",
" return (Array.isArray(props) ? props : [props])\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" warning(isNumber(delay),\n"
],
"file_path": "src/styles/transitions.js",
"type": "replace",
"edit_start_line_idx": 60
} | // @flow weak
/* eslint-disable no-param-reassign */
import warning from 'warning';
// Follow https://material.google.com/motion/duration-easing.html#duration-easing-natural-easing-curves
// to learn the context in which each easing should be used.
const easingInternal = {
// This is the most common easing curve.
easeInOut: 'cubic-bezier(0.4, 0.0, 0.2, 1)',
// Objects enter the screen at full velocity from off-screen and
// slowly decelerate to a resting point.
easeOut: 'cubic-bezier(0.0, 0.0, 0.2, 1)',
// Objects leave the screen at full velocity. They do not decelerate when off-screen.
easeIn: 'cubic-bezier(0.4, 0.0, 1, 1)',
// The sharp curve is used by objects that may return to the screen at any time.
sharp: 'cubic-bezier(0.4, 0.0, 0.6, 1)',
};
// Follow https://material.io/guidelines/motion/duration-easing.html#duration-easing-common-durations
// to learn when use what timing
const durationInternal = {
shortest: 150,
shorter: 200,
short: 250,
// most basic recommended timing
standard: 300,
// this is to be used in complex animations
complex: 375,
// recommended when something is entering screen
enteringScreen: 225,
// recommended when something is leaving screen
leavingScreen: 195,
};
/**
* @param {string|Array} props
* @param {object} param
* @param {string} param.prop
* @param {number} param.duration
* @param {string} param.easing
* @param {number} param.delay
*/
export default {
easing: easingInternal,
duration: durationInternal,
create(props = ['all'], {
duration = durationInternal.standard,
easing = easingInternal.easeInOut,
delay = 0,
...other
} = {}) {
warning(typeof props === 'string' || Array.isArray(props),
'argument "props" must be a string or Array');
warning(Number.isInteger(duration),
'argument "duration" must be a number');
warning(typeof easing === 'string',
'argument "easing" must be a string');
warning(Number.isInteger(delay),
'argument "delay" must be a string');
warning(Object.keys(other).length === 0,
`unrecognized argument(s) [${Object.keys(other).join(',')}]`);
return (Array.isArray(props) ? props : [props])
.map((value) => `${value} ${duration}ms ${easing} ${delay}ms`)
.join(',');
},
getAutoHeightDuration(height) {
if (!height) {
return 0;
}
const constant = height / 36;
const duration = (4 + (15 * (constant ** 0.25)) + (constant / 5)) * 10;
return Math.round(duration);
},
};
/**
* @deprecated Will be removed, please access via theme.transitions.easing
*/
export const easing = easingInternal;
/**
* @deprecated Will be removed, please access via theme.transitions.duration
*/
export const duration = durationInternal;
| src/styles/transitions.js | 1 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.981031596660614,
0.09896879643201828,
0.0001668039767537266,
0.00017222578753717244,
0.29402682185173035
] |
{
"id": 4,
"code_window": [
" 'argument \"easing\" must be a string');\n",
" warning(Number.isInteger(delay),\n",
" 'argument \"delay\" must be a string');\n",
" warning(Object.keys(other).length === 0,\n",
" `unrecognized argument(s) [${Object.keys(other).join(',')}]`);\n",
"\n",
" return (Array.isArray(props) ? props : [props])\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" warning(isNumber(delay),\n"
],
"file_path": "src/styles/transitions.js",
"type": "replace",
"edit_start_line_idx": 60
} | // @flow weak
export function createRippleHandler(instance, eventName, action, cb) {
return function handleEvent(event) {
if (cb) {
cb.call(instance, event);
}
if (event.defaultPrevented) {
return false;
}
if (instance.ripple) {
instance.ripple[action](event);
}
if (instance.props && typeof instance.props[`on${eventName}`] === 'function') {
instance.props[`on${eventName}`](event);
}
return true;
};
}
| src/Ripple/rippleHandler.js | 0 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.00017411779845133424,
0.00017058882804121822,
0.00016758193669375032,
0.00017006671987473965,
0.000002693673195608426
] |
{
"id": 4,
"code_window": [
" 'argument \"easing\" must be a string');\n",
" warning(Number.isInteger(delay),\n",
" 'argument \"delay\" must be a string');\n",
" warning(Object.keys(other).length === 0,\n",
" `unrecognized argument(s) [${Object.keys(other).join(',')}]`);\n",
"\n",
" return (Array.isArray(props) ? props : [props])\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" warning(isNumber(delay),\n"
],
"file_path": "src/styles/transitions.js",
"type": "replace",
"edit_start_line_idx": 60
} | // @flow weak
/* eslint-env mocha */
import React from 'react';
import { assert } from 'chai';
import { createShallowWithContext } from 'test/utils';
import DialogContent, { styleSheet } from './DialogContent';
describe('<DialogContent />', () => {
let shallow;
let classes;
before(() => {
shallow = createShallowWithContext();
classes = shallow.context.styleManager.render(styleSheet);
});
it('should render a div', () => {
const wrapper = shallow(
<DialogContent />,
);
assert.strictEqual(wrapper.is('div'), true, 'should be a div');
});
it('should spread custom props on the root node', () => {
const wrapper = shallow(<DialogContent data-my-prop="woof" />);
assert.strictEqual(wrapper.prop('data-my-prop'), 'woof', 'custom prop should be woof');
});
it('should render with the user and root classes', () => {
const wrapper = shallow(<DialogContent className="woof" />);
assert.strictEqual(wrapper.hasClass('woof'), true, 'should have the "woof" class');
assert.strictEqual(wrapper.hasClass(classes.root), true, 'should have the root class');
});
it('should render children', () => {
const children = <p />;
const wrapper = shallow(<DialogContent>{children}</DialogContent>);
assert.strictEqual(wrapper.children().equals(children), true);
});
});
| src/Dialog/DialogContent.spec.js | 0 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.00017669475346338004,
0.00017374163144268095,
0.00017010678129736334,
0.000175202134414576,
0.0000026255315788148437
] |
{
"id": 4,
"code_window": [
" 'argument \"easing\" must be a string');\n",
" warning(Number.isInteger(delay),\n",
" 'argument \"delay\" must be a string');\n",
" warning(Object.keys(other).length === 0,\n",
" `unrecognized argument(s) [${Object.keys(other).join(',')}]`);\n",
"\n",
" return (Array.isArray(props) ? props : [props])\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" warning(isNumber(delay),\n"
],
"file_path": "src/styles/transitions.js",
"type": "replace",
"edit_start_line_idx": 60
} | module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-mocha-test');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.initConfig({
mochaTest: {
test: {
options: {
reporter: 'spec',
clearRequireCache: true,
},
src: ['test/*.js'],
},
},
watch: {
js: {
options: {
spawn: false,
},
files: ['build.js', 'test/*.js'],
tasks: ['default'],
},
},
});
// On watch events, if the changed file is a test file then configure mochaTest to only
// run the tests from that file. Otherwise run all the tests
const defaultTestSrc = grunt.config('mochaTest.test.src');
grunt.event.on('watch', function(action, filepath) {
grunt.config('mochaTest.test.src', defaultTestSrc);
if (filepath.match('test/')) {
grunt.config('mochaTest.test.src', filepath);
}
});
grunt.registerTask('default', 'mochaTest');
};
| packages/icon-builder/Gruntfile.js | 0 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.00017834099708124995,
0.00017456989735364914,
0.00017014489276334643,
0.00017489684978500009,
0.0000029186044230300467
] |
{
"id": 5,
"code_window": [
" `unrecognized argument(s) [${Object.keys(other).join(',')}]`);\n",
"\n",
" return (Array.isArray(props) ? props : [props])\n",
" .map((value) => `${value} ${duration}ms ${easing} ${delay}ms`)\n",
" .join(',');\n",
" },\n",
"\n",
" getAutoHeightDuration(height) {\n",
" if (!height) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .map((animatedProp) => `${animatedProp} ${formatMs(duration)} ${easing} ${formatMs(delay)}`)\n"
],
"file_path": "src/styles/transitions.js",
"type": "replace",
"edit_start_line_idx": 66
} | // @flow weak
/* eslint-disable no-param-reassign */
import warning from 'warning';
// Follow https://material.google.com/motion/duration-easing.html#duration-easing-natural-easing-curves
// to learn the context in which each easing should be used.
const easingInternal = {
// This is the most common easing curve.
easeInOut: 'cubic-bezier(0.4, 0.0, 0.2, 1)',
// Objects enter the screen at full velocity from off-screen and
// slowly decelerate to a resting point.
easeOut: 'cubic-bezier(0.0, 0.0, 0.2, 1)',
// Objects leave the screen at full velocity. They do not decelerate when off-screen.
easeIn: 'cubic-bezier(0.4, 0.0, 1, 1)',
// The sharp curve is used by objects that may return to the screen at any time.
sharp: 'cubic-bezier(0.4, 0.0, 0.6, 1)',
};
// Follow https://material.io/guidelines/motion/duration-easing.html#duration-easing-common-durations
// to learn when use what timing
const durationInternal = {
shortest: 150,
shorter: 200,
short: 250,
// most basic recommended timing
standard: 300,
// this is to be used in complex animations
complex: 375,
// recommended when something is entering screen
enteringScreen: 225,
// recommended when something is leaving screen
leavingScreen: 195,
};
/**
* @param {string|Array} props
* @param {object} param
* @param {string} param.prop
* @param {number} param.duration
* @param {string} param.easing
* @param {number} param.delay
*/
export default {
easing: easingInternal,
duration: durationInternal,
create(props = ['all'], {
duration = durationInternal.standard,
easing = easingInternal.easeInOut,
delay = 0,
...other
} = {}) {
warning(typeof props === 'string' || Array.isArray(props),
'argument "props" must be a string or Array');
warning(Number.isInteger(duration),
'argument "duration" must be a number');
warning(typeof easing === 'string',
'argument "easing" must be a string');
warning(Number.isInteger(delay),
'argument "delay" must be a string');
warning(Object.keys(other).length === 0,
`unrecognized argument(s) [${Object.keys(other).join(',')}]`);
return (Array.isArray(props) ? props : [props])
.map((value) => `${value} ${duration}ms ${easing} ${delay}ms`)
.join(',');
},
getAutoHeightDuration(height) {
if (!height) {
return 0;
}
const constant = height / 36;
const duration = (4 + (15 * (constant ** 0.25)) + (constant / 5)) * 10;
return Math.round(duration);
},
};
/**
* @deprecated Will be removed, please access via theme.transitions.easing
*/
export const easing = easingInternal;
/**
* @deprecated Will be removed, please access via theme.transitions.duration
*/
export const duration = durationInternal;
| src/styles/transitions.js | 1 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.983688235282898,
0.10239642858505249,
0.0001626279845368117,
0.001363391987979412,
0.2938833236694336
] |
{
"id": 5,
"code_window": [
" `unrecognized argument(s) [${Object.keys(other).join(',')}]`);\n",
"\n",
" return (Array.isArray(props) ? props : [props])\n",
" .map((value) => `${value} ${duration}ms ${easing} ${delay}ms`)\n",
" .join(',');\n",
" },\n",
"\n",
" getAutoHeightDuration(height) {\n",
" if (!height) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .map((animatedProp) => `${animatedProp} ${formatMs(duration)} ${easing} ${formatMs(delay)}`)\n"
],
"file_path": "src/styles/transitions.js",
"type": "replace",
"edit_start_line_idx": 66
} | // @flow weak
import React from 'react';
import Avatar from 'material-ui/Avatar';
import { deepOrange } from 'material-ui/styles/colors';
import Icon from 'material-ui/Icon';
export default function IconAvatar() {
return (
<Avatar
style={{
color: '#fff',
backgroundColor: deepOrange[500],
}}
>
<Icon>favorite</Icon>
</Avatar>
);
}
| test/regressions/tests/Avatar/IconAvatar.js | 0 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.00017517173546366394,
0.00017417033086530864,
0.00017316891171503812,
0.00017417033086530864,
0.0000010014118743129075
] |
{
"id": 5,
"code_window": [
" `unrecognized argument(s) [${Object.keys(other).join(',')}]`);\n",
"\n",
" return (Array.isArray(props) ? props : [props])\n",
" .map((value) => `${value} ${duration}ms ${easing} ${delay}ms`)\n",
" .join(',');\n",
" },\n",
"\n",
" getAutoHeightDuration(height) {\n",
" if (!height) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .map((animatedProp) => `${animatedProp} ${formatMs(duration)} ${easing} ${formatMs(delay)}`)\n"
],
"file_path": "src/styles/transitions.js",
"type": "replace",
"edit_start_line_idx": 66
} | // @flow weak
import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
import { createStyleSheet } from 'jss-theme-reactor';
import shallowEqual from 'recompose/shallowEqual';
import { List } from 'material-ui/List';
import Toolbar from 'material-ui/Toolbar';
import Drawer from 'material-ui/Drawer';
import Text from 'material-ui/Text';
import Divider from 'material-ui/Divider';
import customPropTypes from 'material-ui/utils/customPropTypes';
import AppDrawerNavItem from './AppDrawerNavItem';
export const styleSheet = createStyleSheet('AppDrawer', (theme) => {
return {
paper: {
width: '250px',
backgroundColor: theme.palette.background.paper,
},
title: {
color: theme.palette.text.secondary,
'&:hover': {
textDecoration: 'none',
color: theme.palette.primary[500],
},
},
};
});
function renderNavItems(props, navRoot) {
let navItems = null;
if (navRoot.childRoutes && navRoot.childRoutes.length) {
navItems = navRoot.childRoutes.reduce(reduceChildRoutes.bind(null, props), []);
}
return (
<List>
{navItems}
</List>
);
}
function reduceChildRoutes(props, items, childRoute, index) {
if (childRoute.nav) {
if (childRoute.childRoutes && childRoute.childRoutes.length) {
const openImmediately = props.routes.indexOf(childRoute) !== -1 || false;
items.push(
<AppDrawerNavItem
key={index}
openImmediately={openImmediately}
title={childRoute.title}
>
{renderNavItems(props, childRoute)}
</AppDrawerNavItem>,
);
} else {
items.push(
<AppDrawerNavItem
key={index}
title={childRoute.title}
to={childRoute.path}
onClick={props.onRequestClose}
/>,
);
}
}
return items;
}
export default class AppDrawer extends Component {
static propTypes = {
className: PropTypes.string,
docked: PropTypes.bool.isRequired,
onRequestClose: PropTypes.func.isRequired,
open: PropTypes.bool.isRequired,
routes: PropTypes.array.isRequired,
};
static contextTypes = {
theme: customPropTypes.muiRequired,
styleManager: customPropTypes.muiRequired,
};
shouldComponentUpdate(nextProps, nextState, nextContext) {
return (
!shallowEqual(this.props, nextProps) ||
!shallowEqual(this.state, nextState) ||
!shallowEqual(this.context, nextContext)
);
}
render() {
const classes = this.context.styleManager.render(styleSheet);
return (
<Drawer
className={this.props.className}
paperClassName={classes.paper}
open={this.props.open}
onRequestClose={this.props.onRequestClose}
docked={this.props.docked}
>
<div className={classes.nav}>
<Toolbar>
<Link className={classes.title} to="/" onClick={this.props.onRequestClose}>
<Text type="title">Material UI</Text>
</Link>
<Divider absolute />
</Toolbar>
{renderNavItems(this.props, this.props.routes[0])}
</div>
</Drawer>
);
}
}
| docs/site/src/components/AppDrawer.js | 0 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.0005286834202706814,
0.00021606514928862453,
0.00016609547310508788,
0.00017622373707126826,
0.00009763983689481393
] |
{
"id": 5,
"code_window": [
" `unrecognized argument(s) [${Object.keys(other).join(',')}]`);\n",
"\n",
" return (Array.isArray(props) ? props : [props])\n",
" .map((value) => `${value} ${duration}ms ${easing} ${delay}ms`)\n",
" .join(',');\n",
" },\n",
"\n",
" getAutoHeightDuration(height) {\n",
" if (!height) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .map((animatedProp) => `${animatedProp} ${formatMs(duration)} ${easing} ${formatMs(delay)}`)\n"
],
"file_path": "src/styles/transitions.js",
"type": "replace",
"edit_start_line_idx": 66
} | // @flow weak
/* eslint-env mocha */
| src/styles/colors.spec.js | 0 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.00017226001364178956,
0.00017226001364178956,
0.00017226001364178956,
0.00017226001364178956,
0
] |
{
"id": 6,
"code_window": [
" assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()');\n",
" });\n",
"\n",
" it('should warn when bad \"duration\" option type', () => {\n",
" transitions.create('font', { duration: '' });\n",
" transitions.create('font', { duration: {} });\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should round decimal digits of \"duration\" prop to whole numbers', () => {\n",
" const transition = transitions.create('font', { duration: 12.125 });\n",
" assert.strictEqual(transition, `font 12ms ${easing.easeInOut} 0ms`);\n",
" assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()');\n",
" });\n",
"\n"
],
"file_path": "src/styles/transitions.spec.js",
"type": "add",
"edit_start_line_idx": 53
} | // @flow weak
/* eslint-disable no-param-reassign */
import warning from 'warning';
// Follow https://material.google.com/motion/duration-easing.html#duration-easing-natural-easing-curves
// to learn the context in which each easing should be used.
const easingInternal = {
// This is the most common easing curve.
easeInOut: 'cubic-bezier(0.4, 0.0, 0.2, 1)',
// Objects enter the screen at full velocity from off-screen and
// slowly decelerate to a resting point.
easeOut: 'cubic-bezier(0.0, 0.0, 0.2, 1)',
// Objects leave the screen at full velocity. They do not decelerate when off-screen.
easeIn: 'cubic-bezier(0.4, 0.0, 1, 1)',
// The sharp curve is used by objects that may return to the screen at any time.
sharp: 'cubic-bezier(0.4, 0.0, 0.6, 1)',
};
// Follow https://material.io/guidelines/motion/duration-easing.html#duration-easing-common-durations
// to learn when use what timing
const durationInternal = {
shortest: 150,
shorter: 200,
short: 250,
// most basic recommended timing
standard: 300,
// this is to be used in complex animations
complex: 375,
// recommended when something is entering screen
enteringScreen: 225,
// recommended when something is leaving screen
leavingScreen: 195,
};
/**
* @param {string|Array} props
* @param {object} param
* @param {string} param.prop
* @param {number} param.duration
* @param {string} param.easing
* @param {number} param.delay
*/
export default {
easing: easingInternal,
duration: durationInternal,
create(props = ['all'], {
duration = durationInternal.standard,
easing = easingInternal.easeInOut,
delay = 0,
...other
} = {}) {
warning(typeof props === 'string' || Array.isArray(props),
'argument "props" must be a string or Array');
warning(Number.isInteger(duration),
'argument "duration" must be a number');
warning(typeof easing === 'string',
'argument "easing" must be a string');
warning(Number.isInteger(delay),
'argument "delay" must be a string');
warning(Object.keys(other).length === 0,
`unrecognized argument(s) [${Object.keys(other).join(',')}]`);
return (Array.isArray(props) ? props : [props])
.map((value) => `${value} ${duration}ms ${easing} ${delay}ms`)
.join(',');
},
getAutoHeightDuration(height) {
if (!height) {
return 0;
}
const constant = height / 36;
const duration = (4 + (15 * (constant ** 0.25)) + (constant / 5)) * 10;
return Math.round(duration);
},
};
/**
* @deprecated Will be removed, please access via theme.transitions.easing
*/
export const easing = easingInternal;
/**
* @deprecated Will be removed, please access via theme.transitions.duration
*/
export const duration = durationInternal;
| src/styles/transitions.js | 1 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.0018735408084467053,
0.0005294833099469543,
0.0001639670372242108,
0.00020587866310961545,
0.0005612426321022213
] |
{
"id": 6,
"code_window": [
" assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()');\n",
" });\n",
"\n",
" it('should warn when bad \"duration\" option type', () => {\n",
" transitions.create('font', { duration: '' });\n",
" transitions.create('font', { duration: {} });\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should round decimal digits of \"duration\" prop to whole numbers', () => {\n",
" const transition = transitions.create('font', { duration: 12.125 });\n",
" assert.strictEqual(transition, `font 12ms ${easing.easeInOut} 0ms`);\n",
" assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()');\n",
" });\n",
"\n"
],
"file_path": "src/styles/transitions.spec.js",
"type": "add",
"edit_start_line_idx": 53
} | #! /usr/bin/env node
/**
* Material-UI Icon Builder
* ========================
*
* Usage:
*
* node ./build.js --help
*
*/
'use strict';
const fs = require('fs');
const path = require('path');
const rimraf = require('rimraf');
const Mustache = require('mustache');
const _ = require('lodash');
const glob = require('glob');
const mkdirp = require('mkdirp');
const SVG_ICON_RELATIVE_REQUIRE = '../../SvgIcon';
const SVG_ICON_ABSOLUTE_REQUIRE = 'material-ui/SvgIcon';
const RENAME_FILTER_DEFAULT = './filters/rename/default';
const RENAME_FILTER_MUI = './filters/rename/material-design-icons';
const DEFAULT_OPTIONS = {
muiRequire: 'absolute',
glob: '/**/*.svg',
innerPath: '',
renameFilter: RENAME_FILTER_DEFAULT,
};
function parseArgs() {
return require('yargs')
.usage('Build JSX components from SVG\'s.\nUsage: $0')
.demand('output-dir')
.describe('output-dir', 'Directory to output jsx components')
.demand('svg-dir')
.describe('svg-dir', 'SVG directory')
.describe('glob', 'Glob to match inside of --svg-dir. Default **/*.svg')
.describe('inner-path', '"Reach into" subdirs, since libraries like material-design-icons' +
' use arbitrary build directories to organize icons' +
' e.g. "action/svg/production/icon_3d_rotation_24px.svg"')
.describe('file-suffix', 'Filter only files ending with a suffix (pretty much only' +
' for material-ui-icons)')
.describe('rename-filter', `Path to JS module used to rename destination filename and path.
Default: ${RENAME_FILTER_DEFAULT}`)
.options('mui-require', {
demand: false,
type: 'string',
describe: `Load material-ui dependencies (SvgIcon) relatively or absolutely.
(absolute|relative).
For material-ui distributions, relative, for anything else, you probably want absolute.`,
}).argv;
}
function main(options, cb) {
let originalWrite; // todo, add wiston / other logging tool
options = _.defaults(options, DEFAULT_OPTIONS);
if (options.disable_log) { // disable console.log opt, used for tests.
originalWrite = process.stdout.write;
process.stdout.write = function() {};
}
rimraf.sync(options.outputDir); // Clean old files
console.log('** Starting Build');
let renameFilter = options.renameFilter;
if (_.isString(renameFilter)) {
renameFilter = require(renameFilter);
}
if (!_.isFunction(renameFilter)) {
throw Error('renameFilter must be a function');
}
fs.mkdirSync(options.outputDir);
const files = glob.sync(path.join(options.svgDir, options.glob));
files.forEach(function(svgPath) {
const svgPathObj = path.parse(svgPath);
const innerPath = path.dirname(svgPath)
.replace(options.svgDir, '')
.replace(path.relative(process.cwd(), options.svgDir), ''); // for relative dirs
const destPath = renameFilter(svgPathObj, innerPath, options);
processFile(svgPath, destPath, options);
});
if (cb) {
cb();
}
if (options.disable_log) { // bring back stdout
process.stdout.write = originalWrite;
}
}
/**
* @param {string} svgPath
* Absolute path to svg file to process.
*
* @param {string} destPath
* Path to jsx file relative to {options.outputDir}
*
* @param {object} options
*/
function processFile(svgPath, destPath, options) {
const outputFileDir = path.dirname(path.join(options.outputDir, destPath));
if (!fs.existsSync(outputFileDir)) {
console.log('Making dir: ' + outputFileDir);
mkdirp.sync(outputFileDir);
}
const fileString = getJsxString(svgPath, destPath, options);
const absDestPath = path.join(options.outputDir, destPath);
fs.writeFileSync(absDestPath, fileString);
}
/**
* Return Pascal-Cased classname.
*
* @param {string} svgPath
* @returns {string} class name
*/
function pascalCase(destPath) {
const splitregex = new RegExp('[' + path.sep + '-]+');
let parts = destPath.replace('.js', '').split(splitregex);
parts = _.map(parts, function(part) {
return part.charAt(0).toUpperCase() + part.substring(1);
});
const className = parts.join('');
return className;
}
function getJsxString(svgPath, destPath, options) {
const className = pascalCase(destPath);
console.log(' ' + className);
const data = fs.readFileSync(svgPath, {
encoding: 'utf8',
});
const template = fs.readFileSync(path.join(__dirname, 'tpl/SvgIcon.js'), {
encoding: 'utf8',
});
// Extract the paths from the svg string
let paths = data.slice(data.indexOf('>') + 1);
paths = paths.slice(0, -6);
// Clean xml paths
paths = paths.replace(/xlink:href="#a"/g, '');
paths = paths.replace(/xlink:href="#c"/g, '');
paths = paths.replace(/fill-opacity=/g, 'fillOpacity=');
paths = paths.replace(/\s?fill=".*?"/g, '');
// Node acts weird if we put this directly into string concatenation
const muiRequireStmt = options.muiRequire === 'relative' ? SVG_ICON_RELATIVE_REQUIRE : SVG_ICON_ABSOLUTE_REQUIRE;
return Mustache.render(
template, {
muiRequireStmt: muiRequireStmt,
paths: paths,
className: className,
}
);
}
if (require.main === module) {
const argv = parseArgs();
main(argv);
}
module.exports = {
pascalCase: pascalCase,
getJsxString: getJsxString,
processFile: processFile,
main: main,
SVG_ICON_RELATIVE_REQUIRE: SVG_ICON_RELATIVE_REQUIRE,
SVG_ICON_ABSOLUTE_REQUIRE: SVG_ICON_ABSOLUTE_REQUIRE,
RENAME_FILTER_DEFAULT: RENAME_FILTER_DEFAULT,
RENAME_FILTER_MUI: RENAME_FILTER_MUI,
};
| packages/icon-builder/build.js | 0 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.0003409249475225806,
0.0001819759636418894,
0.00016845378559082747,
0.00017346323875244707,
0.00003753166674869135
] |
{
"id": 6,
"code_window": [
" assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()');\n",
" });\n",
"\n",
" it('should warn when bad \"duration\" option type', () => {\n",
" transitions.create('font', { duration: '' });\n",
" transitions.create('font', { duration: {} });\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should round decimal digits of \"duration\" prop to whole numbers', () => {\n",
" const transition = transitions.create('font', { duration: 12.125 });\n",
" assert.strictEqual(transition, `font 12ms ${easing.easeInOut} 0ms`);\n",
" assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()');\n",
" });\n",
"\n"
],
"file_path": "src/styles/transitions.spec.js",
"type": "add",
"edit_start_line_idx": 53
} | // @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 classNames from 'classnames';
import { createStyleSheet } from 'jss-theme-reactor';
import customPropTypes from '../utils/customPropTypes';
const GUTTERS = [0, 8, 16, 24, 40];
const GRID_SIZES = [true, 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, index) => {
if (index === 0) { // Skip the first one as handle above.
return;
}
// Only keep 6 significant numbers.
const width = `${Math.round((size / 12) * Math.pow(10, 6)) / Math.pow(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,
};
});
// No need for a media query for the first size.
if (breakpoint === 'xs') {
Object.assign(globalStyles, styles);
} else {
globalStyles[theme.breakpoints.up(breakpoint)] = styles;
}
}
function generateGutter(theme, breakpoint) {
const styles = {};
GUTTERS.forEach((gutter, index) => {
if (index === 0) { // Skip the default style.
return;
}
styles[`gutter-${breakpoint}-${gutter}`] = {
margin: -gutter / 2,
'& > $typeItem': {
padding: gutter / 2,
},
};
});
return styles;
}
export const styleSheet = createStyleSheet('MuiLayout', (theme) => {
// Default CSS values
// flex: '0 1 auto',
// flexDirection: 'row',
// alignItems: 'flex-start',
// flexWrap: 'nowrap',
// justifyContent: 'flex-start',
return {
typeContainer: {
boxSizing: 'border-box',
display: 'flex',
flexWrap: 'wrap',
},
typeItem: {
boxSizing: 'border-box',
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,
align,
direction,
xs,
sm,
md,
lg,
xl,
gutter,
justify,
wrap,
...other
} = props;
const classes = context.styleManager.render(styleSheet);
return (
<ComponentProp
className={classNames({
[classes.typeContainer]: container,
[classes.typeItem]: item,
[classes[`gutter-xs-${gutter}`]]: container && gutter !== 0,
[classes[`direction-xs-${direction}`]]: direction !== Layout.defaultProps.direction,
[classes[`wrap-xs-${wrap}`]]: wrap !== Layout.defaultProps.wrap,
[classes[`align-xs-${align}`]]: align !== Layout.defaultProps.align,
[classes[`justify-xs-${justify}`]]: justify !== Layout.defaultProps.justify,
[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>
);
}
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: PropTypes.oneOf(GRID_SIZES),
/**
* 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: PropTypes.oneOf(GRID_SIZES), // 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: PropTypes.oneOf(GRID_SIZES), // 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: PropTypes.oneOf(GRID_SIZES), // 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: PropTypes.oneOf(GRID_SIZES), // eslint-disable-line react/sort-prop-types
/**
* Defines the `align-items` style property.
* It's applied for all the screen sizes.
*/
align: PropTypes.oneOf([ // eslint-disable-line react/sort-prop-types
'flex-start',
'center',
'flex-end',
'stretch',
]),
/**
* Defines the `flex-direction` style property.
* It's applied for all the screen sizes.
*/
direction: PropTypes.oneOf([ // eslint-disable-line react/sort-prop-types
'row',
'row-reverse',
'column',
'column-reverse',
]),
/**
* Defines the space between the type `item` component.
* It can only be used on a type `container` component.
*/
gutter: PropTypes.oneOf(GUTTERS), // eslint-disable-line react/sort-prop-types
/**
* Defines the `justify-content` style property.
* It's applied for all the screen sizes.
*/
justify: PropTypes.oneOf([ // eslint-disable-line react/sort-prop-types
'flex-start',
'center',
'flex-end',
'space-between',
'space-around',
]),
/**
* Defines the `flex-wrap` style property.
* It's applied for all the screen sizes.
*/
wrap: PropTypes.oneOf([ // eslint-disable-line react/sort-prop-types
'nowrap',
'wrap',
'wrap-reverse',
]),
};
Layout.defaultProps = {
component: 'div',
container: false,
item: false,
align: 'flex-start',
direction: 'row',
gutter: 16,
justify: 'flex-start',
wrap: 'wrap',
};
Layout.contextTypes = {
styleManager: customPropTypes.muiRequired,
};
/**
* Add a wrapper component to generate some helper messages in the development
* environment.
*/
let LayoutWrapper = Layout; // eslint-disable-line import/no-mutable-exports
if (process.env.NODE_ENV !== 'production') {
const requireProp = (requiredProp) =>
(props, propName, componentName, location, propFullName) => {
const propFullNameSafe = propFullName || propName;
if (typeof props[propName] !== 'undefined' && !props[requiredProp]) {
return new Error(
`The property \`${propFullNameSafe}\` of ` +
`\`Layout\` must be used on \`${requiredProp}\`.`,
);
}
return null;
};
LayoutWrapper = (props) => <Layout {...props} />;
LayoutWrapper.propTypes = {
align: requireProp('container'),
direction: requireProp('container'),
gutter: requireProp('container'),
justify: requireProp('container'),
lg: requireProp('item'),
md: requireProp('item'),
sm: requireProp('item'),
wrap: requireProp('container'),
xs: requireProp('item'),
};
}
export default LayoutWrapper;
| src/Layout/Layout.js | 0 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.0005159018910489976,
0.00018184396321885288,
0.00016420893371105194,
0.00017269834643229842,
0.000058236946642864496
] |
{
"id": 6,
"code_window": [
" assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()');\n",
" });\n",
"\n",
" it('should warn when bad \"duration\" option type', () => {\n",
" transitions.create('font', { duration: '' });\n",
" transitions.create('font', { duration: {} });\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should round decimal digits of \"duration\" prop to whole numbers', () => {\n",
" const transition = transitions.create('font', { duration: 12.125 });\n",
" assert.strictEqual(transition, `font 12ms ${easing.easeInOut} 0ms`);\n",
" assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()');\n",
" });\n",
"\n"
],
"file_path": "src/styles/transitions.spec.js",
"type": "add",
"edit_start_line_idx": 53
} | <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18"><path d="M9 8c1.11 0 2-.9 2-2s-.89-2-2-2c-1.1 0-2 .9-2 2s.9 2 2 2zm4 0c1.11 0 2-.9 2-2s-.89-2-2-2c-.36 0-.69.1-.98.27.3.51.48 1.1.48 1.73s-.18 1.22-.48 1.73c.29.17.63.27.98.27zM9 9.2c-1.67 0-5 .83-5 2.5V13h10v-1.3c0-1.67-3.33-2.5-5-2.5zM5 7H3V5H2v2H0v1h2v2h1V8h2V7zm9.23 2.31c.75.6 1.27 1.38 1.27 2.39V13H18v-1.3c0-1.31-2.07-2.11-3.77-2.39z"/></svg> | packages/icon-builder/test/fixtures/material-design-icons/svg/social/svg/production/ic_group_add_18px.svg | 0 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.00017193739768117666,
0.00017193739768117666,
0.00017193739768117666,
0.00017193739768117666,
0
] |
{
"id": 7,
"code_window": [
" assert.strictEqual(transition, `size ${duration.standard}ms ${easing.easeInOut} 150ms`);\n",
" assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()');\n",
" });\n",
"\n",
" it('should warn when bad \"delay\" option type', () => {\n",
" transitions.create('size', { delay: '' });\n",
" transitions.create('size', { delay: {} });\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should round decimal digits of \"delay\" prop to whole numbers', () => {\n",
" const transition = transitions.create('size', { delay: 1.547 });\n",
" assert.strictEqual(transition, `size ${duration.standard}ms ${easing.easeInOut} 2ms`);\n",
" assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()');\n",
" });\n",
"\n"
],
"file_path": "src/styles/transitions.spec.js",
"type": "add",
"edit_start_line_idx": 77
} | // @flow weak
/* eslint-disable no-param-reassign */
import warning from 'warning';
// Follow https://material.google.com/motion/duration-easing.html#duration-easing-natural-easing-curves
// to learn the context in which each easing should be used.
const easingInternal = {
// This is the most common easing curve.
easeInOut: 'cubic-bezier(0.4, 0.0, 0.2, 1)',
// Objects enter the screen at full velocity from off-screen and
// slowly decelerate to a resting point.
easeOut: 'cubic-bezier(0.0, 0.0, 0.2, 1)',
// Objects leave the screen at full velocity. They do not decelerate when off-screen.
easeIn: 'cubic-bezier(0.4, 0.0, 1, 1)',
// The sharp curve is used by objects that may return to the screen at any time.
sharp: 'cubic-bezier(0.4, 0.0, 0.6, 1)',
};
// Follow https://material.io/guidelines/motion/duration-easing.html#duration-easing-common-durations
// to learn when use what timing
const durationInternal = {
shortest: 150,
shorter: 200,
short: 250,
// most basic recommended timing
standard: 300,
// this is to be used in complex animations
complex: 375,
// recommended when something is entering screen
enteringScreen: 225,
// recommended when something is leaving screen
leavingScreen: 195,
};
/**
* @param {string|Array} props
* @param {object} param
* @param {string} param.prop
* @param {number} param.duration
* @param {string} param.easing
* @param {number} param.delay
*/
export default {
easing: easingInternal,
duration: durationInternal,
create(props = ['all'], {
duration = durationInternal.standard,
easing = easingInternal.easeInOut,
delay = 0,
...other
} = {}) {
warning(typeof props === 'string' || Array.isArray(props),
'argument "props" must be a string or Array');
warning(Number.isInteger(duration),
'argument "duration" must be a number');
warning(typeof easing === 'string',
'argument "easing" must be a string');
warning(Number.isInteger(delay),
'argument "delay" must be a string');
warning(Object.keys(other).length === 0,
`unrecognized argument(s) [${Object.keys(other).join(',')}]`);
return (Array.isArray(props) ? props : [props])
.map((value) => `${value} ${duration}ms ${easing} ${delay}ms`)
.join(',');
},
getAutoHeightDuration(height) {
if (!height) {
return 0;
}
const constant = height / 36;
const duration = (4 + (15 * (constant ** 0.25)) + (constant / 5)) * 10;
return Math.round(duration);
},
};
/**
* @deprecated Will be removed, please access via theme.transitions.easing
*/
export const easing = easingInternal;
/**
* @deprecated Will be removed, please access via theme.transitions.duration
*/
export const duration = durationInternal;
| src/styles/transitions.js | 1 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.006907902657985687,
0.0023728066589683294,
0.00016227852029260248,
0.0018782790284603834,
0.0022613070905208588
] |
{
"id": 7,
"code_window": [
" assert.strictEqual(transition, `size ${duration.standard}ms ${easing.easeInOut} 150ms`);\n",
" assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()');\n",
" });\n",
"\n",
" it('should warn when bad \"delay\" option type', () => {\n",
" transitions.create('size', { delay: '' });\n",
" transitions.create('size', { delay: {} });\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should round decimal digits of \"delay\" prop to whole numbers', () => {\n",
" const transition = transitions.create('size', { delay: 1.547 });\n",
" assert.strictEqual(transition, `size ${duration.standard}ms ${easing.easeInOut} 2ms`);\n",
" assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()');\n",
" });\n",
"\n"
],
"file_path": "src/styles/transitions.spec.js",
"type": "add",
"edit_start_line_idx": 77
} | # Progress
[Progress and activity indicators](https://material.google.com/components/progress-activity.html)
are visual indications of an app loading content.
A single visual indicator should be used to represent each type of operation.
For example, a refresh operation should display either a refresh bar or an activity circle, but not both.
**Determinate** indicators display how long an operation will take.
**Indeterminate** indicators visualize an unspecified wait time.
## Circular
### Indeterminate
{{demo='demos/progress/Circular.js'}}
### Interactive Integration
{{demo='demos/progress/CircularFab.js'}}
## Linear
### Indeterminate
{{demo='demos/progress/LinearIndeterminate.js'}}
### Determinate
{{demo='demos/progress/LinearDeterminate.js'}}
### Buffer
{{demo='demos/progress/LinearBuffer.js'}}
### Query
{{demo='demos/progress/LinearQuery.js'}}
| docs/site/src/demos/progress/progress.md | 0 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.0001735045952955261,
0.00016977636551018804,
0.00016286539903376251,
0.00017136773385573179,
0.000004096171323908493
] |
{
"id": 7,
"code_window": [
" assert.strictEqual(transition, `size ${duration.standard}ms ${easing.easeInOut} 150ms`);\n",
" assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()');\n",
" });\n",
"\n",
" it('should warn when bad \"delay\" option type', () => {\n",
" transitions.create('size', { delay: '' });\n",
" transitions.create('size', { delay: {} });\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should round decimal digits of \"delay\" prop to whole numbers', () => {\n",
" const transition = transitions.create('size', { delay: 1.547 });\n",
" assert.strictEqual(transition, `size ${duration.standard}ms ${easing.easeInOut} 2ms`);\n",
" assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()');\n",
" });\n",
"\n"
],
"file_path": "src/styles/transitions.spec.js",
"type": "add",
"edit_start_line_idx": 77
} | ListItem
========
Props
-----
| Name | Type | Default | Description |
|:-----|:-----|:--------|:------------|
| button | bool | false | |
| children | node | | |
| className | string | | The CSS class name of the root element. |
| component | union | 'div' | |
| dense | bool | false | |
| divider | bool | false | |
| gutters | bool | true | |
Any other properties supplied will be spread to the root element.
| docs/api/List/ListItem.md | 0 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.0001735874975565821,
0.00017184608441311866,
0.00017010467126965523,
0.00017184608441311866,
0.0000017414131434634328
] |
{
"id": 7,
"code_window": [
" assert.strictEqual(transition, `size ${duration.standard}ms ${easing.easeInOut} 150ms`);\n",
" assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()');\n",
" });\n",
"\n",
" it('should warn when bad \"delay\" option type', () => {\n",
" transitions.create('size', { delay: '' });\n",
" transitions.create('size', { delay: {} });\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should round decimal digits of \"delay\" prop to whole numbers', () => {\n",
" const transition = transitions.create('size', { delay: 1.547 });\n",
" assert.strictEqual(transition, `size ${duration.standard}ms ${easing.easeInOut} 2ms`);\n",
" assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()');\n",
" });\n",
"\n"
],
"file_path": "src/styles/transitions.spec.js",
"type": "add",
"edit_start_line_idx": 77
} | // @flow weak
import React from 'react';
import Paper from 'material-ui/Paper';
import { createStyleSheet } from 'jss-theme-reactor';
import customPropTypes from 'material-ui/utils/customPropTypes';
import Layout from 'material-ui/Layout';
const styleSheet = createStyleSheet('SimpleLayout', () => ({
root: {
width: 400,
},
paper: {
padding: 16,
textAlign: 'center',
},
}));
export default function SimpleLayout(props, context) {
const classes = context.styleManager.render(styleSheet);
return (
<div className={classes.root}>
<Layout container gutter={24}>
<Layout item xs={12}>
<Paper className={classes.paper}>
xs=12
</Paper>
</Layout>
<Layout item xs={6}>
<Paper className={classes.paper}>
xs=6
</Paper>
</Layout>
<Layout item xs={6}>
<Paper className={classes.paper}>
xs=6
</Paper>
</Layout>
<Layout item xs={3}>
<Paper className={classes.paper}>
xs=3
</Paper>
</Layout>
<Layout item xs={3}>
<Paper className={classes.paper}>
xs=3
</Paper>
</Layout>
<Layout item xs={3}>
<Paper className={classes.paper}>
xs=3
</Paper>
</Layout>
<Layout item xs={3}>
<Paper className={classes.paper}>
xs=3
</Paper>
</Layout>
</Layout>
</div>
);
}
SimpleLayout.contextTypes = {
styleManager: customPropTypes.muiRequired,
};
| test/regressions/tests/Layout/SimpleLayout.js | 0 | https://github.com/mui/material-ui/commit/bfff16c0f3a401a3dade1516ea84eeb277af5996 | [
0.00017462807591073215,
0.00017200267757289112,
0.00016552551824133843,
0.00017350426060147583,
0.00000315821603180666
] |
{
"id": 0,
"code_window": [
"\n",
"import * as html from '../ml_parser/ast';\n",
"import {InterpolationConfig} from '../ml_parser/interpolation_config';\n",
"\n",
"import {digestMessage} from './digest';\n",
"import * as i18n from './i18n_ast';\n",
"import {createI18nMessageFactory} from './i18n_parser';\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {ParseTreeResult} from '../ml_parser/parser';\n"
],
"file_path": "modules/@angular/compiler/src/i18n/extractor_merger.ts",
"type": "add",
"edit_start_line_idx": 10
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as html from '../ml_parser/ast';
import {InterpolationConfig} from '../ml_parser/interpolation_config';
import {digestMessage} from './digest';
import * as i18n from './i18n_ast';
import {createI18nMessageFactory} from './i18n_parser';
import {I18nError} from './parse_util';
import {TranslationBundle} from './translation_bundle';
const _I18N_ATTR = 'i18n';
const _I18N_ATTR_PREFIX = 'i18n-';
const _I18N_COMMENT_PREFIX_REGEXP = /^i18n:?/;
/**
* Extract translatable messages from an html AST
*/
export function extractMessages(
nodes: html.Node[], interpolationConfig: InterpolationConfig, implicitTags: string[],
implicitAttrs: {[k: string]: string[]}): ExtractionResult {
const visitor = new _Visitor(implicitTags, implicitAttrs);
return visitor.extract(nodes, interpolationConfig);
}
export function mergeTranslations(
nodes: html.Node[], translations: TranslationBundle, interpolationConfig: InterpolationConfig,
implicitTags: string[], implicitAttrs: {[k: string]: string[]}): html.Node[] {
const visitor = new _Visitor(implicitTags, implicitAttrs);
return visitor.merge(nodes, translations, interpolationConfig);
}
export class ExtractionResult {
constructor(public messages: i18n.Message[], public errors: I18nError[]) {}
}
enum _VisitorMode {
Extract,
Merge
}
/**
* This Visitor is used:
* 1. to extract all the translatable strings from an html AST (see `extract()`),
* 2. to replace the translatable strings with the actual translations (see `merge()`)
*
* @internal
*/
class _Visitor implements html.Visitor {
// <el i18n>...</el>
private _inI18nNode: boolean;
private _depth: number;
private _inImplicitNode: boolean;
// <!--i18n-->...<!--/i18n-->
private _blockMeaningAndDesc: string;
private _blockChildren: html.Node[];
private _blockStartDepth: number;
private _inI18nBlock: boolean;
// {<icu message>}
private _inIcu: boolean;
private _msgCountAtSectionStart: number;
private _errors: I18nError[];
private _mode: _VisitorMode;
// _VisitorMode.Extract only
private _messages: i18n.Message[];
// _VisitorMode.Merge only
private _translations: TranslationBundle;
private _createI18nMessage:
(msg: html.Node[], meaning: string, description: string) => i18n.Message;
constructor(private _implicitTags: string[], private _implicitAttrs: {[k: string]: string[]}) {}
/**
* Extracts the messages from the tree
*/
extract(nodes: html.Node[], interpolationConfig: InterpolationConfig): ExtractionResult {
this._init(_VisitorMode.Extract, interpolationConfig);
nodes.forEach(node => node.visit(this, null));
if (this._inI18nBlock) {
this._reportError(nodes[nodes.length - 1], 'Unclosed block');
}
return new ExtractionResult(this._messages, this._errors);
}
/**
* Returns a tree where all translatable nodes are translated
*/
merge(
nodes: html.Node[], translations: TranslationBundle,
interpolationConfig: InterpolationConfig): html.Node[] {
this._init(_VisitorMode.Merge, interpolationConfig);
this._translations = translations;
// Construct a single fake root element
const wrapper = new html.Element('wrapper', [], nodes, null, null, null);
const translatedNode = wrapper.visit(this, null);
// TODO(vicb): return MergeResult with errors
if (this._inI18nBlock) {
this._reportError(nodes[nodes.length - 1], 'Unclosed block');
}
return translatedNode.children;
}
visitExpansionCase(icuCase: html.ExpansionCase, context: any): any {
// Parse cases for translatable html attributes
const expression = html.visitAll(this, icuCase.expression, context);
if (this._mode === _VisitorMode.Merge) {
return new html.ExpansionCase(
icuCase.value, expression, icuCase.sourceSpan, icuCase.valueSourceSpan,
icuCase.expSourceSpan);
}
}
visitExpansion(icu: html.Expansion, context: any): html.Expansion {
this._mayBeAddBlockChildren(icu);
const wasInIcu = this._inIcu;
if (!this._inIcu) {
// nested ICU messages should not be extracted but top-level translated as a whole
if (this._isInTranslatableSection) {
this._addMessage([icu]);
}
this._inIcu = true;
}
const cases = html.visitAll(this, icu.cases, context);
if (this._mode === _VisitorMode.Merge) {
icu = new html.Expansion(
icu.switchValue, icu.type, cases, icu.sourceSpan, icu.switchValueSourceSpan);
}
this._inIcu = wasInIcu;
return icu;
}
visitComment(comment: html.Comment, context: any): any {
const isOpening = _isOpeningComment(comment);
if (isOpening && this._isInTranslatableSection) {
this._reportError(comment, 'Could not start a block inside a translatable section');
return;
}
const isClosing = _isClosingComment(comment);
if (isClosing && !this._inI18nBlock) {
this._reportError(comment, 'Trying to close an unopened block');
return;
}
if (!this._inI18nNode && !this._inIcu) {
if (!this._inI18nBlock) {
if (isOpening) {
this._inI18nBlock = true;
this._blockStartDepth = this._depth;
this._blockChildren = [];
this._blockMeaningAndDesc = comment.value.replace(_I18N_COMMENT_PREFIX_REGEXP, '').trim();
this._openTranslatableSection(comment);
}
} else {
if (isClosing) {
if (this._depth == this._blockStartDepth) {
this._closeTranslatableSection(comment, this._blockChildren);
this._inI18nBlock = false;
const message = this._addMessage(this._blockChildren, this._blockMeaningAndDesc);
// merge attributes in sections
const nodes = this._translateMessage(comment, message);
return html.visitAll(this, nodes);
} else {
this._reportError(comment, 'I18N blocks should not cross element boundaries');
return;
}
}
}
}
}
visitText(text: html.Text, context: any): html.Text {
if (this._isInTranslatableSection) {
this._mayBeAddBlockChildren(text);
}
return text;
}
visitElement(el: html.Element, context: any): html.Element {
this._mayBeAddBlockChildren(el);
this._depth++;
const wasInI18nNode = this._inI18nNode;
const wasInImplicitNode = this._inImplicitNode;
let childNodes: html.Node[];
// Extract only top level nodes with the (implicit) "i18n" attribute if not in a block or an ICU
// message
const i18nAttr = _getI18nAttr(el);
const isImplicit = this._implicitTags.some((tag: string): boolean => el.name === tag) &&
!this._inIcu && !this._isInTranslatableSection;
const isTopLevelImplicit = !wasInImplicitNode && isImplicit;
this._inImplicitNode = this._inImplicitNode || isImplicit;
if (!this._isInTranslatableSection && !this._inIcu) {
if (i18nAttr) {
// explicit translation
this._inI18nNode = true;
const message = this._addMessage(el.children, i18nAttr.value);
childNodes = this._translateMessage(el, message);
} else if (isTopLevelImplicit) {
// implicit translation
this._inI18nNode = true;
const message = this._addMessage(el.children);
childNodes = this._translateMessage(el, message);
}
if (this._mode == _VisitorMode.Extract) {
const isTranslatable = i18nAttr || isTopLevelImplicit;
if (isTranslatable) {
this._openTranslatableSection(el);
}
html.visitAll(this, el.children);
if (isTranslatable) {
this._closeTranslatableSection(el, el.children);
}
}
if (this._mode === _VisitorMode.Merge && !i18nAttr && !isTopLevelImplicit) {
childNodes = [];
el.children.forEach(child => {
const visited = child.visit(this, context);
if (visited && !this._isInTranslatableSection) {
// Do not add the children from translatable sections (= i18n blocks here)
// They will be added when the section is close (i.e. on `<!-- /i18n -->`)
childNodes = childNodes.concat(visited);
}
});
}
} else {
if (i18nAttr || isTopLevelImplicit) {
this._reportError(
el, 'Could not mark an element as translatable inside a translatable section');
}
if (this._mode == _VisitorMode.Extract) {
// Descend into child nodes for extraction
html.visitAll(this, el.children);
}
if (this._mode == _VisitorMode.Merge) {
// Translate attributes in ICU messages
childNodes = [];
el.children.forEach(child => {
const visited = child.visit(this, context);
if (visited && !this._isInTranslatableSection) {
// Do not add the children from translatable sections (= i18n blocks here)
// They will be added when the section is close (i.e. on `<!-- /i18n -->`)
childNodes = childNodes.concat(visited);
}
});
}
}
this._visitAttributesOf(el);
this._depth--;
this._inI18nNode = wasInI18nNode;
this._inImplicitNode = wasInImplicitNode;
if (this._mode === _VisitorMode.Merge) {
// There are no childNodes in translatable sections - those nodes will be replace anyway
const translatedAttrs = this._translateAttributes(el);
return new html.Element(
el.name, translatedAttrs, childNodes, el.sourceSpan, el.startSourceSpan,
el.endSourceSpan);
}
}
visitAttribute(attribute: html.Attribute, context: any): any {
throw new Error('unreachable code');
}
private _init(mode: _VisitorMode, interpolationConfig: InterpolationConfig): void {
this._mode = mode;
this._inI18nBlock = false;
this._inI18nNode = false;
this._depth = 0;
this._inIcu = false;
this._msgCountAtSectionStart = void 0;
this._errors = [];
this._messages = [];
this._inImplicitNode = false;
this._createI18nMessage = createI18nMessageFactory(interpolationConfig);
}
// looks for translatable attributes
private _visitAttributesOf(el: html.Element): void {
const explicitAttrNameToValue: {[k: string]: string} = {};
const implicitAttrNames: string[] = this._implicitAttrs[el.name] || [];
el.attrs.filter(attr => attr.name.startsWith(_I18N_ATTR_PREFIX))
.forEach(
attr => explicitAttrNameToValue[attr.name.slice(_I18N_ATTR_PREFIX.length)] =
attr.value);
el.attrs.forEach(attr => {
if (attr.name in explicitAttrNameToValue) {
this._addMessage([attr], explicitAttrNameToValue[attr.name]);
} else if (implicitAttrNames.some(name => attr.name === name)) {
this._addMessage([attr]);
}
});
}
// add a translatable message
private _addMessage(ast: html.Node[], meaningAndDesc?: string): i18n.Message {
if (ast.length == 0 ||
ast.length == 1 && ast[0] instanceof html.Attribute && !(<html.Attribute>ast[0]).value) {
// Do not create empty messages
return;
}
const [meaning, description] = _splitMeaningAndDesc(meaningAndDesc);
const message = this._createI18nMessage(ast, meaning, description);
this._messages.push(message);
return message;
}
// Translates the given message given the `TranslationBundle`
// no-op when called in extraction mode (returns [])
private _translateMessage(el: html.Node, message: i18n.Message): html.Node[] {
if (message && this._mode === _VisitorMode.Merge) {
const id = digestMessage(message);
const nodes = this._translations.get(id);
if (nodes) {
return nodes;
}
this._reportError(el, `Translation unavailable for message id="${id}"`);
}
return [];
}
// translate the attributes of an element and remove i18n specific attributes
private _translateAttributes(el: html.Element): html.Attribute[] {
const attributes = el.attrs;
const i18nAttributeMeanings: {[name: string]: string} = {};
attributes.forEach(attr => {
if (attr.name.startsWith(_I18N_ATTR_PREFIX)) {
i18nAttributeMeanings[attr.name.slice(_I18N_ATTR_PREFIX.length)] =
_splitMeaningAndDesc(attr.value)[0];
}
});
const translatedAttributes: html.Attribute[] = [];
attributes.forEach((attr) => {
if (attr.name === _I18N_ATTR || attr.name.startsWith(_I18N_ATTR_PREFIX)) {
// strip i18n specific attributes
return;
}
if (attr.value && attr.value != '' && i18nAttributeMeanings.hasOwnProperty(attr.name)) {
const meaning = i18nAttributeMeanings[attr.name];
const message: i18n.Message = this._createI18nMessage([attr], meaning, '');
const id = digestMessage(message);
const nodes = this._translations.get(id);
if (nodes) {
if (nodes[0] instanceof html.Text) {
const value = (nodes[0] as html.Text).value;
translatedAttributes.push(new html.Attribute(attr.name, value, attr.sourceSpan));
} else {
this._reportError(
el, `Unexpected translation for attribute "${attr.name}" (id="${id}")`);
}
} else {
this._reportError(
el, `Translation unavailable for attribute "${attr.name}" (id="${id}")`);
}
} else {
translatedAttributes.push(attr);
}
});
return translatedAttributes;
}
/**
* Add the node as a child of the block when:
* - we are in a block,
* - we are not inside a ICU message (those are handled separately),
* - the node is a "direct child" of the block
*/
private _mayBeAddBlockChildren(node: html.Node): void {
if (this._inI18nBlock && !this._inIcu && this._depth == this._blockStartDepth) {
this._blockChildren.push(node);
}
}
/**
* Marks the start of a section, see `_endSection`
*/
private _openTranslatableSection(node: html.Node): void {
if (this._isInTranslatableSection) {
this._reportError(node, 'Unexpected section start');
} else {
this._msgCountAtSectionStart = this._messages.length;
}
}
/**
* A translatable section could be:
* - a translatable element,
* - nodes between `<!-- i18n -->` and `<!-- /i18n -->` comments
*/
private get _isInTranslatableSection(): boolean {
return this._msgCountAtSectionStart !== void 0;
}
/**
* Terminates a section.
*
* If a section has only one significant children (comments not significant) then we should not
* keep the message from this children:
*
* `<p i18n="meaning|description">{ICU message}</p>` would produce two messages:
* - one for the <p> content with meaning and description,
* - another one for the ICU message.
*
* In this case the last message is discarded as it contains less information (the AST is
* otherwise identical).
*
* Note that we should still keep messages extracted from attributes inside the section (ie in the
* ICU message here)
*/
private _closeTranslatableSection(node: html.Node, directChildren: html.Node[]): void {
if (!this._isInTranslatableSection) {
this._reportError(node, 'Unexpected section end');
return;
}
const startIndex = this._msgCountAtSectionStart;
const significantChildren: number = directChildren.reduce(
(count: number, node: html.Node): number => count + (node instanceof html.Comment ? 0 : 1),
0);
if (significantChildren == 1) {
for (let i = this._messages.length - 1; i >= startIndex; i--) {
const ast = this._messages[i].nodes;
if (!(ast.length == 1 && ast[0] instanceof i18n.Text)) {
this._messages.splice(i, 1);
break;
}
}
}
this._msgCountAtSectionStart = void 0;
}
private _reportError(node: html.Node, msg: string): void {
this._errors.push(new I18nError(node.sourceSpan, msg));
}
}
function _isOpeningComment(n: html.Node): boolean {
return n instanceof html.Comment && n.value && n.value.startsWith('i18n');
}
function _isClosingComment(n: html.Node): boolean {
return n instanceof html.Comment && n.value && n.value === '/i18n';
}
function _getI18nAttr(p: html.Element): html.Attribute {
return p.attrs.find(attr => attr.name === _I18N_ATTR) || null;
}
function _splitMeaningAndDesc(i18n: string): [string, string] {
if (!i18n) return ['', ''];
const pipeIndex = i18n.indexOf('|');
return pipeIndex == -1 ? ['', i18n] : [i18n.slice(0, pipeIndex), i18n.slice(pipeIndex + 1)];
}
| modules/@angular/compiler/src/i18n/extractor_merger.ts | 1 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.06935592740774155,
0.001653108512982726,
0.00016341997252311558,
0.00019542654627002776,
0.009584118612110615
] |
{
"id": 0,
"code_window": [
"\n",
"import * as html from '../ml_parser/ast';\n",
"import {InterpolationConfig} from '../ml_parser/interpolation_config';\n",
"\n",
"import {digestMessage} from './digest';\n",
"import * as i18n from './i18n_ast';\n",
"import {createI18nMessageFactory} from './i18n_parser';\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {ParseTreeResult} from '../ml_parser/parser';\n"
],
"file_path": "modules/@angular/compiler/src/i18n/extractor_merger.ts",
"type": "add",
"edit_start_line_idx": 10
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {AsyncPipe, NgFor} from '@angular/common';
import {ElementSchemaRegistry} from '@angular/compiler/src/schema/element_schema_registry';
import {TEST_COMPILER_PROVIDERS} from '@angular/compiler/test/test_bindings';
import {MockSchemaRegistry} from '@angular/compiler/testing';
import {AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, DebugElement, Directive, DoCheck, Injectable, Input, OnChanges, OnDestroy, OnInit, Output, Pipe, PipeTransform, RenderComponentType, Renderer, RootRenderer, SimpleChange, SimpleChanges, TemplateRef, Type, ViewContainerRef, ViewMetadata, WrappedValue, forwardRef} from '@angular/core';
import {DebugDomRenderer} from '@angular/core/src/debug/debug_renderer';
import {ComponentFixture, TestBed, TestComponentBuilder, fakeAsync, flushMicrotasks, tick} from '@angular/core/testing';
import {afterEach, beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {By} from '@angular/platform-browser/src/dom/debug/by';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {DomRootRenderer} from '@angular/platform-browser/src/dom/dom_renderer';
import {EventEmitter} from '../../src/facade/async';
import {StringMapWrapper} from '../../src/facade/collection';
import {BaseException} from '../../src/facade/exceptions';
import {NumberWrapper, isBlank} from '../../src/facade/lang';
export function main() {
let tcb: TestComponentBuilder;
let elSchema: MockSchemaRegistry;
let renderLog: RenderLog;
let directiveLog: DirectiveLog;
function createCompFixture<T>(template: string): ComponentFixture<TestComponent>;
function createCompFixture<T>(template: string, compType: Type<T>): ComponentFixture<T>;
function createCompFixture<T>(
template: string, compType: Type<T>, _tcb: TestComponentBuilder): ComponentFixture<T>;
function createCompFixture<T>(
template: string, compType: Type<T> = <any>TestComponent,
_tcb: TestComponentBuilder = null): ComponentFixture<T> {
if (isBlank(_tcb)) {
_tcb = tcb;
}
return _tcb
.overrideView(
compType,
new ViewMetadata({template: template, directives: ALL_DIRECTIVES, pipes: ALL_PIPES}))
.createFakeAsync(compType);
}
function queryDirs(el: DebugElement, dirType: Type<any>): any {
var nodes = el.queryAllNodes(By.directive(dirType));
return nodes.map(node => node.injector.get(dirType));
}
function _bindSimpleProp<T>(bindAttr: string): ComponentFixture<TestComponent>;
function _bindSimpleProp<T>(bindAttr: string, compType: Type<T>): ComponentFixture<T>;
function _bindSimpleProp<T>(
bindAttr: string, compType: Type<T> = <any>TestComponent): ComponentFixture<T> {
var template = `<div ${bindAttr}></div>`;
return createCompFixture(template, compType);
}
function _bindSimpleValue(expression: any): ComponentFixture<TestComponent>;
function _bindSimpleValue<T>(expression: any, compType: Type<T>): ComponentFixture<T>;
function _bindSimpleValue<T>(
expression: any, compType: Type<T> = <any>TestComponent): ComponentFixture<T> {
return _bindSimpleProp(`[someProp]='${expression}'`, compType);
}
function _bindAndCheckSimpleValue(
expression: any, compType: Type<any> = TestComponent): string[] {
const ctx = _bindSimpleValue(expression, compType);
ctx.detectChanges(false);
return renderLog.log;
}
describe(`ChangeDetection`, () => {
// On CJS fakeAsync is not supported...
if (!getDOM().supportsDOMEvents()) return;
beforeEach(() => {
TestBed.configureCompiler({providers: TEST_COMPILER_PROVIDERS});
TestBed.configureTestingModule({
providers:
[RenderLog, DirectiveLog, {provide: RootRenderer, useClass: LoggingRootRenderer}]
});
});
beforeEach(fakeAsync(inject(
[TestComponentBuilder, ElementSchemaRegistry, RenderLog, DirectiveLog],
(_tcb: TestComponentBuilder, _elSchema: MockSchemaRegistry, _renderLog: RenderLog,
_directiveLog: DirectiveLog) => {
tcb = _tcb;
elSchema = _elSchema;
renderLog = _renderLog;
directiveLog = _directiveLog;
elSchema.existingProperties['someProp'] = true;
})));
describe('expressions', () => {
it('should support literals',
fakeAsync(() => { expect(_bindAndCheckSimpleValue(10)).toEqual(['someProp=10']); }));
it('should strip quotes from literals',
fakeAsync(() => { expect(_bindAndCheckSimpleValue('"str"')).toEqual(['someProp=str']); }));
it('should support newlines in literals', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('"a\n\nb"')).toEqual(['someProp=a\n\nb']);
}));
it('should support + operations',
fakeAsync(() => { expect(_bindAndCheckSimpleValue('10 + 2')).toEqual(['someProp=12']); }));
it('should support - operations',
fakeAsync(() => { expect(_bindAndCheckSimpleValue('10 - 2')).toEqual(['someProp=8']); }));
it('should support * operations',
fakeAsync(() => { expect(_bindAndCheckSimpleValue('10 * 2')).toEqual(['someProp=20']); }));
it('should support / operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('10 / 2')).toEqual([`someProp=${5.0}`]);
})); // dart exp=5.0, js exp=5
it('should support % operations',
fakeAsync(() => { expect(_bindAndCheckSimpleValue('11 % 2')).toEqual(['someProp=1']); }));
it('should support == operations on identical', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('1 == 1')).toEqual(['someProp=true']);
}));
it('should support != operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('1 != 1')).toEqual(['someProp=false']);
}));
it('should support == operations on coerceible', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('1 == true')).toEqual([`someProp=true`]);
}));
it('should support === operations on identical', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('1 === 1')).toEqual(['someProp=true']);
}));
it('should support !== operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('1 !== 1')).toEqual(['someProp=false']);
}));
it('should support === operations on coerceible', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('1 === true')).toEqual(['someProp=false']);
}));
it('should support true < operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('1 < 2')).toEqual(['someProp=true']);
}));
it('should support false < operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('2 < 1')).toEqual(['someProp=false']);
}));
it('should support false > operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('1 > 2')).toEqual(['someProp=false']);
}));
it('should support true > operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('2 > 1')).toEqual(['someProp=true']);
}));
it('should support true <= operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('1 <= 2')).toEqual(['someProp=true']);
}));
it('should support equal <= operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('2 <= 2')).toEqual(['someProp=true']);
}));
it('should support false <= operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('2 <= 1')).toEqual(['someProp=false']);
}));
it('should support true >= operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('2 >= 1')).toEqual(['someProp=true']);
}));
it('should support equal >= operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('2 >= 2')).toEqual(['someProp=true']);
}));
it('should support false >= operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('1 >= 2')).toEqual(['someProp=false']);
}));
it('should support true && operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('true && true')).toEqual(['someProp=true']);
}));
it('should support false && operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('true && false')).toEqual(['someProp=false']);
}));
it('should support true || operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('true || false')).toEqual(['someProp=true']);
}));
it('should support false || operations', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('false || false')).toEqual(['someProp=false']);
}));
it('should support negate', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('!true')).toEqual(['someProp=false']);
}));
it('should support double negate', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('!!true')).toEqual(['someProp=true']);
}));
it('should support true conditionals', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('1 < 2 ? 1 : 2')).toEqual(['someProp=1']);
}));
it('should support false conditionals', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('1 > 2 ? 1 : 2')).toEqual(['someProp=2']);
}));
it('should support keyed access to a list item', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('["foo", "bar"][0]')).toEqual(['someProp=foo']);
}));
it('should support keyed access to a map item', fakeAsync(() => {
expect(_bindAndCheckSimpleValue('{"foo": "bar"}["foo"]')).toEqual(['someProp=bar']);
}));
it('should report all changes on the first run including uninitialized values',
fakeAsync(() => {
expect(_bindAndCheckSimpleValue('value', Uninitialized)).toEqual(['someProp=null']);
}));
it('should report all changes on the first run including null values', fakeAsync(() => {
var ctx = _bindSimpleValue('a', TestData);
ctx.componentInstance.a = null;
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['someProp=null']);
}));
it('should support simple chained property access', fakeAsync(() => {
var ctx = _bindSimpleValue('address.city', Person);
ctx.componentInstance.name = 'Victor';
ctx.componentInstance.address = new Address('Grenoble');
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['someProp=Grenoble']);
}));
describe('safe navigation operator', () => {
it('should support reading properties of nulls', fakeAsync(() => {
var ctx = _bindSimpleValue('address?.city', Person);
ctx.componentInstance.address = null;
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['someProp=null']);
}));
it('should support calling methods on nulls', fakeAsync(() => {
var ctx = _bindSimpleValue('address?.toString()', Person);
ctx.componentInstance.address = null;
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['someProp=null']);
}));
it('should support reading properties on non nulls', fakeAsync(() => {
var ctx = _bindSimpleValue('address?.city', Person);
ctx.componentInstance.address = new Address('MTV');
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['someProp=MTV']);
}));
it('should support calling methods on non nulls', fakeAsync(() => {
var ctx = _bindSimpleValue('address?.toString()', Person);
ctx.componentInstance.address = new Address('MTV');
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['someProp=MTV']);
}));
it('should support short-circuting safe navigation', fakeAsync(() => {
const ctx = _bindSimpleValue('value?.address.city', PersonHolder);
ctx.componentInstance.value = null;
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['someProp=null']);
}));
it('should support nested short-circuting safe navigation', fakeAsync(() => {
const ctx = _bindSimpleValue('value.value?.address.city', PersonHolderHolder);
ctx.componentInstance.value = new PersonHolder();
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['someProp=null']);
}));
it('should support chained short-circuting safe navigation', fakeAsync(() => {
const ctx = _bindSimpleValue('value?.value?.address.city', PersonHolderHolder);
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['someProp=null']);
}));
it('should still throw if right-side would throw', fakeAsync(() => {
expect(() => {
const ctx = _bindSimpleValue('value?.address.city', PersonHolder);
const person = new Person();
person.address = null;
ctx.componentInstance.value = person;
ctx.detectChanges(false);
}).toThrow();
}));
});
it('should support method calls', fakeAsync(() => {
var ctx = _bindSimpleValue('sayHi("Jim")', Person);
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['someProp=Hi, Jim']);
}));
it('should support function calls', fakeAsync(() => {
var ctx = _bindSimpleValue('a()(99)', TestData);
ctx.componentInstance.a = () => (a: any) => a;
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['someProp=99']);
}));
it('should support chained method calls', fakeAsync(() => {
var ctx = _bindSimpleValue('address.toString()', Person);
ctx.componentInstance.address = new Address('MTV');
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['someProp=MTV']);
}));
it('should support NaN', fakeAsync(() => {
var ctx = _bindSimpleValue('age', Person);
ctx.componentInstance.age = NumberWrapper.NaN;
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['someProp=NaN']);
renderLog.clear();
ctx.detectChanges(false);
expect(renderLog.log).toEqual([]);
}));
it('should do simple watching', fakeAsync(() => {
var ctx = _bindSimpleValue('name', Person);
ctx.componentInstance.name = 'misko';
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['someProp=misko']);
renderLog.clear();
ctx.detectChanges(false);
expect(renderLog.log).toEqual([]);
renderLog.clear();
ctx.componentInstance.name = 'Misko';
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['someProp=Misko']);
}));
it('should support literal array made of literals', fakeAsync(() => {
var ctx = _bindSimpleValue('[1, 2]');
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual([[1, 2]]);
}));
it('should support empty literal array', fakeAsync(() => {
var ctx = _bindSimpleValue('[]');
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual([[]]);
}));
it('should support literal array made of expressions', fakeAsync(() => {
var ctx = _bindSimpleValue('[1, a]', TestData);
ctx.componentInstance.a = 2;
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual([[1, 2]]);
}));
it('should not recreate literal arrays unless their content changed', fakeAsync(() => {
var ctx = _bindSimpleValue('[1, a]', TestData);
ctx.componentInstance.a = 2;
ctx.detectChanges(false);
ctx.detectChanges(false);
ctx.componentInstance.a = 3;
ctx.detectChanges(false);
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual([[1, 2], [1, 3]]);
}));
it('should support literal maps made of literals', fakeAsync(() => {
var ctx = _bindSimpleValue('{z: 1}');
ctx.detectChanges(false);
expect(renderLog.loggedValues[0]['z']).toEqual(1);
}));
it('should support empty literal map', fakeAsync(() => {
var ctx = _bindSimpleValue('{}');
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual([{}]);
}));
it('should support literal maps made of expressions', fakeAsync(() => {
var ctx = _bindSimpleValue('{z: a}');
ctx.componentInstance.a = 1;
ctx.detectChanges(false);
expect(renderLog.loggedValues[0]['z']).toEqual(1);
}));
it('should not recreate literal maps unless their content changed', fakeAsync(() => {
var ctx = _bindSimpleValue('{z: a}');
ctx.componentInstance.a = 1;
ctx.detectChanges(false);
ctx.detectChanges(false);
ctx.componentInstance.a = 2;
ctx.detectChanges(false);
ctx.detectChanges(false);
expect(renderLog.loggedValues.length).toBe(2);
expect(renderLog.loggedValues[0]['z']).toEqual(1);
expect(renderLog.loggedValues[1]['z']).toEqual(2);
}));
it('should support interpolation', fakeAsync(() => {
var ctx = _bindSimpleProp('someProp="B{{a}}A"', TestData);
ctx.componentInstance.a = 'value';
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['someProp=BvalueA']);
}));
it('should output empty strings for null values in interpolation', fakeAsync(() => {
var ctx = _bindSimpleProp('someProp="B{{a}}A"', TestData);
ctx.componentInstance.a = null;
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['someProp=BA']);
}));
it('should escape values in literals that indicate interpolation',
fakeAsync(() => { expect(_bindAndCheckSimpleValue('"$"')).toEqual(['someProp=$']); }));
it('should read locals', fakeAsync(() => {
var ctx =
createCompFixture('<template testLocals let-local="someLocal">{{local}}</template>');
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['{{someLocalValue}}']);
}));
describe('pipes', () => {
it('should use the return value of the pipe', fakeAsync(() => {
var ctx = _bindSimpleValue('name | countingPipe', Person);
ctx.componentInstance.name = 'bob';
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual(['bob state:0']);
}));
it('should support arguments in pipes', fakeAsync(() => {
var ctx = _bindSimpleValue('name | multiArgPipe:"one":address.city', Person);
ctx.componentInstance.name = 'value';
ctx.componentInstance.address = new Address('two');
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual(['value one two default']);
}));
it('should associate pipes right-to-left', fakeAsync(() => {
var ctx = _bindSimpleValue('name | multiArgPipe:"a":"b" | multiArgPipe:0:1', Person);
ctx.componentInstance.name = 'value';
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual(['value a b default 0 1 default']);
}));
it('should support calling pure pipes with different number of arguments', fakeAsync(() => {
var ctx = _bindSimpleValue('name | multiArgPipe:"a":"b" | multiArgPipe:0:1:2', Person);
ctx.componentInstance.name = 'value';
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual(['value a b default 0 1 2']);
}));
it('should do nothing when no change', fakeAsync(() => {
var ctx = _bindSimpleValue('"Megatron" | identityPipe', Person);
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['someProp=Megatron']);
renderLog.clear();
ctx.detectChanges(false);
expect(renderLog.log).toEqual([]);
}));
it('should unwrap the wrapped value', fakeAsync(() => {
var ctx = _bindSimpleValue('"Megatron" | wrappedPipe', Person);
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['someProp=Megatron']);
renderLog.clear();
ctx.detectChanges(false);
expect(renderLog.log).toEqual(['someProp=Megatron']);
}));
it('should call pure pipes only if the arguments change', fakeAsync(() => {
var ctx = _bindSimpleValue('name | countingPipe', Person);
// change from undefined -> null
ctx.componentInstance.name = null;
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual(['null state:0']);
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual(['null state:0']);
// change from null -> some value
ctx.componentInstance.name = 'bob';
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual(['null state:0', 'bob state:1']);
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual(['null state:0', 'bob state:1']);
// change from some value -> some other value
ctx.componentInstance.name = 'bart';
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual([
'null state:0', 'bob state:1', 'bart state:2'
]);
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual([
'null state:0', 'bob state:1', 'bart state:2'
]);
}));
it('should call pure pipes that are used multiple times only when the arguments change',
fakeAsync(() => {
var ctx = createCompFixture(
`<div [someProp]="name | countingPipe"></div><div [someProp]="age | countingPipe"></div>` +
'<div *ngFor="let x of [1,2]" [someProp]="address.city | countingPipe"></div>',
Person);
ctx.componentInstance.name = 'a';
ctx.componentInstance.age = 10;
ctx.componentInstance.address = new Address('mtv');
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual([
'mtv state:0', 'mtv state:1', 'a state:2', '10 state:3'
]);
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual([
'mtv state:0', 'mtv state:1', 'a state:2', '10 state:3'
]);
ctx.componentInstance.age = 11;
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual([
'mtv state:0', 'mtv state:1', 'a state:2', '10 state:3', '11 state:4'
]);
}));
it('should call impure pipes on each change detection run', fakeAsync(() => {
var ctx = _bindSimpleValue('name | countingImpurePipe', Person);
ctx.componentInstance.name = 'bob';
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual(['bob state:0']);
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual(['bob state:0', 'bob state:1']);
}));
});
describe('event expressions', () => {
it('should support field assignments', fakeAsync(() => {
var ctx = _bindSimpleProp('(event)="b=a=$event"');
var childEl = ctx.debugElement.children[0];
var evt = 'EVENT';
childEl.triggerEventHandler('event', evt);
expect(ctx.componentInstance.a).toEqual(evt);
expect(ctx.componentInstance.b).toEqual(evt);
}));
it('should support keyed assignments', fakeAsync(() => {
var ctx = _bindSimpleProp('(event)="a[0]=$event"');
var childEl = ctx.debugElement.children[0];
ctx.componentInstance.a = ['OLD'];
var evt = 'EVENT';
childEl.triggerEventHandler('event', evt);
expect(ctx.componentInstance.a).toEqual([evt]);
}));
it('should support chains', fakeAsync(() => {
var ctx = _bindSimpleProp('(event)="a=a+1; a=a+1;"');
var childEl = ctx.debugElement.children[0];
ctx.componentInstance.a = 0;
childEl.triggerEventHandler('event', 'EVENT');
expect(ctx.componentInstance.a).toEqual(2);
}));
it('should throw when trying to assign to a local', fakeAsync(() => {
expect(() => {
_bindSimpleProp('(event)="$event=1"');
}).toThrowError(new RegExp('Cannot assign to a reference or variable!'));
}));
it('should support short-circuiting', fakeAsync(() => {
var ctx = _bindSimpleProp('(event)="true ? a = a + 1 : a = a + 1"');
var childEl = ctx.debugElement.children[0];
ctx.componentInstance.a = 0;
childEl.triggerEventHandler('event', 'EVENT');
expect(ctx.componentInstance.a).toEqual(1);
}));
});
});
describe('change notification', () => {
describe('updating directives', () => {
it('should happen without invoking the renderer', fakeAsync(() => {
var ctx = createCompFixture('<div testDirective [a]="42"></div>');
ctx.detectChanges(false);
expect(renderLog.log).toEqual([]);
expect(queryDirs(ctx.debugElement, TestDirective)[0].a).toEqual(42);
}));
});
describe('reading directives', () => {
it('should read directive properties', fakeAsync(() => {
var ctx = createCompFixture(
'<div testDirective [a]="42" ref-dir="testDirective" [someProp]="dir.a"></div>');
ctx.detectChanges(false);
expect(renderLog.loggedValues).toEqual([42]);
}));
});
describe('ngOnChanges', () => {
it('should notify the directive when a group of records changes', fakeAsync(() => {
var ctx = createCompFixture(
'<div [testDirective]="\'aName\'" [a]="1" [b]="2"></div><div [testDirective]="\'bName\'" [a]="4"></div>');
ctx.detectChanges(false);
var dirs = queryDirs(ctx.debugElement, TestDirective);
expect(dirs[0].changes).toEqual({'a': 1, 'b': 2, 'name': 'aName'});
expect(dirs[1].changes).toEqual({'a': 4, 'name': 'bName'});
}));
});
});
describe('lifecycle', () => {
function createCompWithContentAndViewChild(): ComponentFixture<any> {
return createCompFixture(
'<div testDirective="parent"><div *ngIf="true" testDirective="contentChild"></div><other-cmp></other-cmp></div>',
TestComponent,
tcb.overrideTemplate(AnotherComponent, '<div testDirective="viewChild"></div>'));
}
describe('ngOnInit', () => {
it('should be called after ngOnChanges', fakeAsync(() => {
var ctx = createCompFixture('<div testDirective="dir"></div>');
expect(directiveLog.filter(['ngOnInit', 'ngOnChanges'])).toEqual([]);
ctx.detectChanges(false);
expect(directiveLog.filter(['ngOnInit', 'ngOnChanges'])).toEqual([
'dir.ngOnChanges', 'dir.ngOnInit'
]);
directiveLog.clear();
ctx.detectChanges(false);
expect(directiveLog.filter(['ngOnInit'])).toEqual([]);
}));
it('should only be called only once', fakeAsync(() => {
var ctx = createCompFixture('<div testDirective="dir"></div>');
ctx.detectChanges(false);
expect(directiveLog.filter(['ngOnInit'])).toEqual(['dir.ngOnInit']);
// reset directives
directiveLog.clear();
// Verify that checking should not call them.
ctx.checkNoChanges();
expect(directiveLog.filter(['ngOnInit'])).toEqual([]);
// re-verify that changes should not call them
ctx.detectChanges(false);
expect(directiveLog.filter(['ngOnInit'])).toEqual([]);
}));
it('should not call ngOnInit again if it throws', fakeAsync(() => {
var ctx = createCompFixture('<div testDirective="dir" throwOn="ngOnInit"></div>');
var errored = false;
// First pass fails, but ngOnInit should be called.
try {
ctx.detectChanges(false);
} catch (e) {
errored = true;
}
expect(errored).toBe(true);
expect(directiveLog.filter(['ngOnInit'])).toEqual(['dir.ngOnInit']);
directiveLog.clear();
// Second change detection also fails, but this time ngOnInit should not be called.
try {
ctx.detectChanges(false);
} catch (e) {
throw new BaseException('Second detectChanges() should not have run detection.');
}
expect(directiveLog.filter(['ngOnInit'])).toEqual([]);
}));
});
describe('ngDoCheck', () => {
it('should be called after ngOnInit', fakeAsync(() => {
var ctx = createCompFixture('<div testDirective="dir"></div>');
ctx.detectChanges(false);
expect(directiveLog.filter(['ngDoCheck', 'ngOnInit'])).toEqual([
'dir.ngOnInit', 'dir.ngDoCheck'
]);
}));
it('should be called on every detectChanges run, except for checkNoChanges',
fakeAsync(() => {
var ctx = createCompFixture('<div testDirective="dir"></div>');
ctx.detectChanges(false);
expect(directiveLog.filter(['ngDoCheck'])).toEqual(['dir.ngDoCheck']);
// reset directives
directiveLog.clear();
// Verify that checking should not call them.
ctx.checkNoChanges();
expect(directiveLog.filter(['ngDoCheck'])).toEqual([]);
// re-verify that changes are still detected
ctx.detectChanges(false);
expect(directiveLog.filter(['ngDoCheck'])).toEqual(['dir.ngDoCheck']);
}));
});
describe('ngAfterContentInit', () => {
it('should be called after processing the content children but before the view children',
fakeAsync(() => {
var ctx = createCompWithContentAndViewChild();
ctx.detectChanges(false);
expect(directiveLog.filter(['ngDoCheck', 'ngAfterContentInit'])).toEqual([
'parent.ngDoCheck', 'contentChild.ngDoCheck', 'contentChild.ngAfterContentInit',
'parent.ngAfterContentInit', 'viewChild.ngDoCheck', 'viewChild.ngAfterContentInit'
]);
}));
it('should only be called only once', fakeAsync(() => {
var ctx = createCompFixture('<div testDirective="dir"></div>');
ctx.detectChanges(false);
expect(directiveLog.filter(['ngAfterContentInit'])).toEqual([
'dir.ngAfterContentInit'
]);
// reset directives
directiveLog.clear();
// Verify that checking should not call them.
ctx.checkNoChanges();
expect(directiveLog.filter(['ngAfterContentInit'])).toEqual([]);
// re-verify that changes should not call them
ctx.detectChanges(false);
expect(directiveLog.filter(['ngAfterContentInit'])).toEqual([]);
}));
it('should not call ngAfterContentInit again if it throws', fakeAsync(() => {
var ctx =
createCompFixture('<div testDirective="dir" throwOn="ngAfterContentInit"></div>');
var errored = false;
// First pass fails, but ngAfterContentInit should be called.
try {
ctx.detectChanges(false);
} catch (e) {
errored = true;
}
expect(errored).toBe(true);
expect(directiveLog.filter(['ngAfterContentInit'])).toEqual([
'dir.ngAfterContentInit'
]);
directiveLog.clear();
// Second change detection also fails, but this time ngAfterContentInit should not be
// called.
try {
ctx.detectChanges(false);
} catch (e) {
throw new BaseException('Second detectChanges() should not have run detection.');
}
expect(directiveLog.filter(['ngAfterContentInit'])).toEqual([]);
}));
});
describe('ngAfterContentChecked', () => {
it('should be called after the content children but before the view children',
fakeAsync(() => {
var ctx = createCompWithContentAndViewChild();
ctx.detectChanges(false);
expect(directiveLog.filter(['ngDoCheck', 'ngAfterContentChecked'])).toEqual([
'parent.ngDoCheck', 'contentChild.ngDoCheck', 'contentChild.ngAfterContentChecked',
'parent.ngAfterContentChecked', 'viewChild.ngDoCheck',
'viewChild.ngAfterContentChecked'
]);
}));
it('should be called on every detectChanges run, except for checkNoChanges',
fakeAsync(() => {
var ctx = createCompFixture('<div testDirective="dir"></div>');
ctx.detectChanges(false);
expect(directiveLog.filter(['ngAfterContentChecked'])).toEqual([
'dir.ngAfterContentChecked'
]);
// reset directives
directiveLog.clear();
// Verify that checking should not call them.
ctx.checkNoChanges();
expect(directiveLog.filter(['ngAfterContentChecked'])).toEqual([]);
// re-verify that changes are still detected
ctx.detectChanges(false);
expect(directiveLog.filter(['ngAfterContentChecked'])).toEqual([
'dir.ngAfterContentChecked'
]);
}));
it('should be called in reverse order so the child is always notified before the parent',
fakeAsync(() => {
var ctx = createCompFixture(
'<div testDirective="parent"><div testDirective="child"></div></div>');
ctx.detectChanges(false);
expect(directiveLog.filter(['ngAfterContentChecked'])).toEqual([
'child.ngAfterContentChecked', 'parent.ngAfterContentChecked'
]);
}));
});
describe('ngAfterViewInit', () => {
it('should be called after processing the view children', fakeAsync(() => {
var ctx = createCompWithContentAndViewChild();
ctx.detectChanges(false);
expect(directiveLog.filter(['ngDoCheck', 'ngAfterViewInit'])).toEqual([
'parent.ngDoCheck', 'contentChild.ngDoCheck', 'contentChild.ngAfterViewInit',
'viewChild.ngDoCheck', 'viewChild.ngAfterViewInit', 'parent.ngAfterViewInit'
]);
}));
it('should only be called only once', fakeAsync(() => {
var ctx = createCompFixture('<div testDirective="dir"></div>');
ctx.detectChanges(false);
expect(directiveLog.filter(['ngAfterViewInit'])).toEqual(['dir.ngAfterViewInit']);
// reset directives
directiveLog.clear();
// Verify that checking should not call them.
ctx.checkNoChanges();
expect(directiveLog.filter(['ngAfterViewInit'])).toEqual([]);
// re-verify that changes should not call them
ctx.detectChanges(false);
expect(directiveLog.filter(['ngAfterViewInit'])).toEqual([]);
}));
it('should not call ngAfterViewInit again if it throws', fakeAsync(() => {
var ctx =
createCompFixture('<div testDirective="dir" throwOn="ngAfterViewInit"></div>');
var errored = false;
// First pass fails, but ngAfterViewInit should be called.
try {
ctx.detectChanges(false);
} catch (e) {
errored = true;
}
expect(errored).toBe(true);
expect(directiveLog.filter(['ngAfterViewInit'])).toEqual(['dir.ngAfterViewInit']);
directiveLog.clear();
// Second change detection also fails, but this time ngAfterViewInit should not be
// called.
try {
ctx.detectChanges(false);
} catch (e) {
throw new BaseException('Second detectChanges() should not have run detection.');
}
expect(directiveLog.filter(['ngAfterViewInit'])).toEqual([]);
}));
});
describe('ngAfterViewChecked', () => {
it('should be called after processing the view children', fakeAsync(() => {
var ctx = createCompWithContentAndViewChild();
ctx.detectChanges(false);
expect(directiveLog.filter(['ngDoCheck', 'ngAfterViewChecked'])).toEqual([
'parent.ngDoCheck', 'contentChild.ngDoCheck', 'contentChild.ngAfterViewChecked',
'viewChild.ngDoCheck', 'viewChild.ngAfterViewChecked', 'parent.ngAfterViewChecked'
]);
}));
it('should be called on every detectChanges run, except for checkNoChanges',
fakeAsync(() => {
var ctx = createCompFixture('<div testDirective="dir"></div>');
ctx.detectChanges(false);
expect(directiveLog.filter(['ngAfterViewChecked'])).toEqual([
'dir.ngAfterViewChecked'
]);
// reset directives
directiveLog.clear();
// Verify that checking should not call them.
ctx.checkNoChanges();
expect(directiveLog.filter(['ngAfterViewChecked'])).toEqual([]);
// re-verify that changes are still detected
ctx.detectChanges(false);
expect(directiveLog.filter(['ngAfterViewChecked'])).toEqual([
'dir.ngAfterViewChecked'
]);
}));
it('should be called in reverse order so the child is always notified before the parent',
fakeAsync(() => {
var ctx = createCompFixture(
'<div testDirective="parent"><div testDirective="child"></div></div>');
ctx.detectChanges(false);
expect(directiveLog.filter(['ngAfterViewChecked'])).toEqual([
'child.ngAfterViewChecked', 'parent.ngAfterViewChecked'
]);
}));
});
describe('ngOnDestroy', () => {
it('should be called on view destruction', fakeAsync(() => {
var ctx = createCompFixture('<div testDirective="dir"></div>');
ctx.detectChanges(false);
ctx.destroy();
expect(directiveLog.filter(['ngOnDestroy'])).toEqual(['dir.ngOnDestroy']);
}));
it('should be called after processing the content and view children', fakeAsync(() => {
var ctx = createCompFixture(
'<div testDirective="parent"><div *ngFor="let x of [0,1]" testDirective="contentChild{{x}}"></div>' +
'<other-cmp></other-cmp></div>',
TestComponent,
tcb.overrideTemplate(AnotherComponent, '<div testDirective="viewChild"></div>'));
ctx.detectChanges(false);
ctx.destroy();
expect(directiveLog.filter(['ngOnDestroy'])).toEqual([
'contentChild0.ngOnDestroy', 'contentChild1.ngOnDestroy', 'viewChild.ngOnDestroy',
'parent.ngOnDestroy'
]);
}));
it('should be called in reverse order so the child is always notified before the parent',
fakeAsync(() => {
var ctx = createCompFixture(
'<div testDirective="parent"><div testDirective="child"></div></div>');
ctx.detectChanges(false);
ctx.destroy();
expect(directiveLog.filter(['ngOnDestroy'])).toEqual([
'child.ngOnDestroy', 'parent.ngOnDestroy'
]);
}));
it('should call ngOnDestory on pipes', fakeAsync(() => {
var ctx = createCompFixture('{{true | pipeWithOnDestroy }}');
ctx.detectChanges(false);
ctx.destroy();
expect(directiveLog.filter(['ngOnDestroy'])).toEqual([
'pipeWithOnDestroy.ngOnDestroy'
]);
}));
it('should call ngOnDestroy on an injectable class', fakeAsync(() => {
var ctx = createCompFixture(
'<div testDirective="dir"></div>', TestComponent,
tcb.overrideProviders(TestDirective, [InjectableWithLifecycle]));
ctx.debugElement.children[0].injector.get(InjectableWithLifecycle);
ctx.detectChanges(false);
ctx.destroy();
expect(directiveLog.filter(['ngOnDestroy'])).toEqual([
'dir.ngOnDestroy', 'injectable.ngOnDestroy'
]);
}));
});
});
describe('enforce no new changes', () => {
it('should throw when a record gets changed after it has been checked', fakeAsync(() => {
const ctx = createCompFixture('<div [someProp]="a"></div>', TestData);
ctx.componentInstance.a = 1;
expect(() => ctx.checkNoChanges())
.toThrowError(/:0:5[\s\S]*Expression has changed after it was checked./g);
}));
it('should warn when the view has been created in a cd hook', fakeAsync(() => {
const ctx = createCompFixture('<div *gh9882>{{ a }}</div>', TestData);
ctx.componentInstance.a = 1;
expect(() => ctx.detectChanges())
.toThrowError(
/It seems like the view has been created after its parent and its children have been dirty checked/);
}));
it('should not throw when two arrays are structurally the same', fakeAsync(() => {
const ctx = _bindSimpleValue('a', TestData);
ctx.componentInstance.a = ['value'];
ctx.detectChanges(false);
ctx.componentInstance.a = ['value'];
expect(() => ctx.checkNoChanges()).not.toThrow();
}));
it('should not break the next run', fakeAsync(() => {
const ctx = _bindSimpleValue('a', TestData);
ctx.componentInstance.a = 'value';
expect(() => ctx.checkNoChanges()).toThrow();
ctx.detectChanges();
expect(renderLog.loggedValues).toEqual(['value']);
}));
});
describe('mode', () => {
it('Detached', fakeAsync(() => {
var ctx = createCompFixture('<comp-with-ref></comp-with-ref>');
var cmp: CompWithRef = queryDirs(ctx.debugElement, CompWithRef)[0];
cmp.value = 'hello';
cmp.changeDetectorRef.detach();
ctx.detectChanges();
expect(renderLog.log).toEqual([]);
}));
it('Reattaches', fakeAsync(() => {
var ctx = createCompFixture('<comp-with-ref></comp-with-ref>');
var cmp: CompWithRef = queryDirs(ctx.debugElement, CompWithRef)[0];
cmp.value = 'hello';
cmp.changeDetectorRef.detach();
ctx.detectChanges();
expect(renderLog.log).toEqual([]);
cmp.changeDetectorRef.reattach();
ctx.detectChanges();
expect(renderLog.log).toEqual(['{{hello}}']);
}));
it('Reattaches in the original cd mode', fakeAsync(() => {
var ctx = createCompFixture('<push-cmp></push-cmp>');
var cmp: PushComp = queryDirs(ctx.debugElement, PushComp)[0];
cmp.changeDetectorRef.detach();
cmp.changeDetectorRef.reattach();
// renderCount should NOT be incremented with each CD as CD mode should be resetted to
// on-push
ctx.detectChanges();
expect(cmp.renderCount).toBeGreaterThan(0);
var count = cmp.renderCount;
ctx.detectChanges();
expect(cmp.renderCount).toBe(count);
}));
});
describe('multi directive order', () => {
it('should follow the DI order for the same element', fakeAsync(() => {
var ctx =
createCompFixture('<div orderCheck2="2" orderCheck0="0" orderCheck1="1"></div>');
ctx.detectChanges(false);
ctx.destroy();
expect(directiveLog.filter(['set'])).toEqual(['0.set', '1.set', '2.set']);
}));
});
});
}
const ALL_DIRECTIVES = [
forwardRef(() => TestDirective),
forwardRef(() => TestComponent),
forwardRef(() => AnotherComponent),
forwardRef(() => TestLocals),
forwardRef(() => CompWithRef),
forwardRef(() => EmitterDirective),
forwardRef(() => PushComp),
forwardRef(() => OrderCheckDirective2),
forwardRef(() => OrderCheckDirective0),
forwardRef(() => OrderCheckDirective1),
forwardRef(() => Gh9882),
NgFor,
];
const ALL_PIPES = [
forwardRef(() => CountingPipe),
forwardRef(() => CountingImpurePipe),
forwardRef(() => MultiArgPipe),
forwardRef(() => PipeWithOnDestroy),
forwardRef(() => IdentityPipe),
forwardRef(() => WrappedPipe),
AsyncPipe,
];
@Injectable()
class RenderLog {
log: string[] = [];
loggedValues: any[] = [];
setElementProperty(el: any, propName: string, propValue: any) {
this.log.push(`${propName}=${propValue}`);
this.loggedValues.push(propValue);
}
setText(node: any, value: string) {
this.log.push(`{{${value}}}`);
this.loggedValues.push(value);
}
clear() {
this.log = [];
this.loggedValues = [];
}
}
@Injectable()
class LoggingRootRenderer implements RootRenderer {
constructor(private _delegate: DomRootRenderer, private _log: RenderLog) {}
renderComponent(componentProto: RenderComponentType): Renderer {
return new LoggingRenderer(this._delegate.renderComponent(componentProto), this._log);
}
}
class LoggingRenderer extends DebugDomRenderer {
constructor(delegate: Renderer, private _log: RenderLog) { super(delegate); }
setElementProperty(renderElement: any, propertyName: string, propertyValue: any) {
this._log.setElementProperty(renderElement, propertyName, propertyValue);
super.setElementProperty(renderElement, propertyName, propertyValue);
}
setText(renderNode: any, value: string) { this._log.setText(renderNode, value); }
}
class DirectiveLogEntry {
constructor(public directiveName: string, public method: string) {}
}
@Injectable()
class DirectiveLog {
entries: DirectiveLogEntry[] = [];
add(directiveName: string, method: string) {
this.entries.push(new DirectiveLogEntry(directiveName, method));
}
clear() { this.entries = []; }
filter(methods: string[]): string[] {
return this.entries.filter((entry) => methods.indexOf(entry.method) !== -1)
.map(entry => `${entry.directiveName}.${entry.method}`);
}
}
@Pipe({name: 'countingPipe'})
class CountingPipe implements PipeTransform {
state: number = 0;
transform(value: any) { return `${value} state:${this.state ++}`; }
}
@Pipe({name: 'countingImpurePipe', pure: false})
class CountingImpurePipe implements PipeTransform {
state: number = 0;
transform(value: any) { return `${value} state:${this.state ++}`; }
}
@Pipe({name: 'pipeWithOnDestroy'})
class PipeWithOnDestroy implements PipeTransform, OnDestroy {
constructor(private directiveLog: DirectiveLog) {}
ngOnDestroy() { this.directiveLog.add('pipeWithOnDestroy', 'ngOnDestroy'); }
transform(value: any): any { return null; }
}
@Pipe({name: 'identityPipe'})
class IdentityPipe implements PipeTransform {
transform(value: any) { return value; }
}
@Pipe({name: 'wrappedPipe'})
class WrappedPipe implements PipeTransform {
transform(value: any) { return WrappedValue.wrap(value); }
}
@Pipe({name: 'multiArgPipe'})
class MultiArgPipe implements PipeTransform {
transform(value: any, arg1: any, arg2: any, arg3 = 'default') {
return `${value} ${arg1} ${arg2} ${arg3}`;
}
}
@Component({selector: 'test-cmp', template: '', directives: ALL_DIRECTIVES, pipes: ALL_PIPES})
class TestComponent {
value: any;
a: any;
b: any;
}
@Component({selector: 'other-cmp', directives: ALL_DIRECTIVES, pipes: ALL_PIPES, template: ''})
class AnotherComponent {
}
@Component({
selector: 'comp-with-ref',
template: '<div (event)="noop()" emitterDirective></div>{{value}}',
host: {'event': 'noop()'},
directives: ALL_DIRECTIVES,
pipes: ALL_PIPES
})
class CompWithRef {
@Input() public value: any;
constructor(public changeDetectorRef: ChangeDetectorRef) {}
noop() {}
}
@Component({
selector: 'push-cmp',
template: '<div (event)="noop()" emitterDirective></div>{{value}}{{renderIncrement}}',
host: {'(event)': 'noop()'},
directives: ALL_DIRECTIVES,
pipes: ALL_PIPES,
changeDetection: ChangeDetectionStrategy.OnPush
})
class PushComp {
@Input() public value: any;
public renderCount: any = 0;
get renderIncrement() {
this.renderCount++;
return '';
}
constructor(public changeDetectorRef: ChangeDetectorRef) {}
noop() {}
}
@Directive({selector: '[emitterDirective]'})
class EmitterDirective {
@Output('event') emitter = new EventEmitter<string>();
}
@Directive({selector: '[gh9882]'})
class Gh9882 implements AfterContentInit {
constructor(private _viewContainer: ViewContainerRef, private _templateRef: TemplateRef<Object>) {
}
ngAfterContentInit(): any { this._viewContainer.createEmbeddedView(this._templateRef); }
}
@Directive({selector: '[testDirective]', exportAs: 'testDirective'})
class TestDirective implements OnInit, DoCheck, OnChanges, AfterContentInit, AfterContentChecked,
AfterViewInit, AfterViewChecked, OnDestroy {
@Input() a: any;
@Input() b: any;
changes: any;
event: any;
eventEmitter: EventEmitter<string> = new EventEmitter<string>();
@Input('testDirective') name: string;
@Input() throwOn: string;
constructor(public log: DirectiveLog) {}
onEvent(event: any) { this.event = event; }
ngDoCheck() { this.log.add(this.name, 'ngDoCheck'); }
ngOnInit() {
this.log.add(this.name, 'ngOnInit');
if (this.throwOn == 'ngOnInit') {
throw new BaseException('Boom!');
}
}
ngOnChanges(changes: SimpleChanges) {
this.log.add(this.name, 'ngOnChanges');
const r: {[k: string]: string} = {};
StringMapWrapper.forEach(changes, (c: SimpleChange, key: string) => r[key] = c.currentValue);
this.changes = r;
if (this.throwOn == 'ngOnChanges') {
throw new BaseException('Boom!');
}
}
ngAfterContentInit() {
this.log.add(this.name, 'ngAfterContentInit');
if (this.throwOn == 'ngAfterContentInit') {
throw new BaseException('Boom!');
}
}
ngAfterContentChecked() {
this.log.add(this.name, 'ngAfterContentChecked');
if (this.throwOn == 'ngAfterContentChecked') {
throw new BaseException('Boom!');
}
}
ngAfterViewInit() {
this.log.add(this.name, 'ngAfterViewInit');
if (this.throwOn == 'ngAfterViewInit') {
throw new BaseException('Boom!');
}
}
ngAfterViewChecked() {
this.log.add(this.name, 'ngAfterViewChecked');
if (this.throwOn == 'ngAfterViewChecked') {
throw new BaseException('Boom!');
}
}
ngOnDestroy() {
this.log.add(this.name, 'ngOnDestroy');
if (this.throwOn == 'ngOnDestroy') {
throw new BaseException('Boom!');
}
}
}
@Injectable()
class InjectableWithLifecycle {
name = 'injectable';
constructor(public log: DirectiveLog) {}
ngOnDestroy() { this.log.add(this.name, 'ngOnDestroy'); }
}
@Directive({selector: '[orderCheck0]'})
class OrderCheckDirective0 {
private _name: string;
@Input('orderCheck0')
set name(value: string) {
this._name = value;
this.log.add(this._name, 'set');
}
constructor(public log: DirectiveLog) {}
}
@Directive({selector: '[orderCheck1]'})
class OrderCheckDirective1 {
private _name: string;
@Input('orderCheck1')
set name(value: string) {
this._name = value;
this.log.add(this._name, 'set');
}
constructor(public log: DirectiveLog, _check0: OrderCheckDirective0) {}
}
@Directive({selector: '[orderCheck2]'})
class OrderCheckDirective2 {
private _name: string;
@Input('orderCheck2')
set name(value: string) {
this._name = value;
this.log.add(this._name, 'set');
}
constructor(public log: DirectiveLog, _check1: OrderCheckDirective1) {}
}
class TestLocalsContext {
constructor(public someLocal: string) {}
}
@Directive({selector: '[testLocals]'})
class TestLocals {
constructor(templateRef: TemplateRef<TestLocalsContext>, vcRef: ViewContainerRef) {
vcRef.createEmbeddedView(templateRef, new TestLocalsContext('someLocalValue'));
}
}
@Component({selector: 'root'})
class Person {
age: number;
name: string;
address: Address = null;
init(name: string, address: Address = null) {
this.name = name;
this.address = address;
}
sayHi(m: any): string { return `Hi, ${m}`; }
passThrough(val: any): any { return val; }
toString(): string {
var address = this.address == null ? '' : ' address=' + this.address.toString();
return 'name=' + this.name + address;
}
}
class Address {
cityGetterCalls: number = 0;
zipCodeGetterCalls: number = 0;
constructor(public _city: string, public _zipcode: any = null) {}
get city() {
this.cityGetterCalls++;
return this._city;
}
get zipcode() {
this.zipCodeGetterCalls++;
return this._zipcode;
}
set city(v) { this._city = v; }
set zipcode(v) { this._zipcode = v; }
toString(): string { return this.city || '-'; }
}
@Component({selector: 'root'})
class Uninitialized {
value: any = null;
}
@Component({selector: 'root'})
class TestData {
public a: any;
}
@Component({selector: 'root'})
class TestDataWithGetter {
public fn: Function;
get a() { return this.fn(); }
}
class Holder<T> {
value: T;
}
@Component({selector: 'root'})
class PersonHolder extends Holder<Person> {
}
@Component({selector: 'root'})
class PersonHolderHolder extends Holder<Holder<Person>> {
}
| modules/@angular/core/test/linker/change_detection_integration_spec.ts | 0 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.0001904251257656142,
0.00017299829050898552,
0.00016389077063649893,
0.00017314526485279202,
0.000003205850362064666
] |
{
"id": 0,
"code_window": [
"\n",
"import * as html from '../ml_parser/ast';\n",
"import {InterpolationConfig} from '../ml_parser/interpolation_config';\n",
"\n",
"import {digestMessage} from './digest';\n",
"import * as i18n from './i18n_ast';\n",
"import {createI18nMessageFactory} from './i18n_parser';\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {ParseTreeResult} from '../ml_parser/parser';\n"
],
"file_path": "modules/@angular/compiler/src/i18n/extractor_merger.ts",
"type": "add",
"edit_start_line_idx": 10
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {BaseException} from '@angular/core';
import {CompileDiDependencyMetadata, CompileDirectiveMetadata, CompileIdentifierMap, CompileIdentifierMetadata, CompileProviderMetadata, CompileQueryMetadata, CompileTokenMetadata} from '../compile_metadata';
import {ListWrapper, StringMapWrapper} from '../facade/collection';
import {isBlank, isPresent} from '../facade/lang';
import {Identifiers, identifierToken} from '../identifiers';
import * as o from '../output/output_ast';
import {convertValueToOutputAst} from '../output/value_util';
import {ProviderAst, ProviderAstType, ReferenceAst, TemplateAst} from '../template_parser/template_ast';
import {createDiTokenExpression} from '../util';
import {CompileMethod} from './compile_method';
import {CompileQuery, addQueryToTokenMap, createQueryList} from './compile_query';
import {CompileView} from './compile_view';
import {InjectMethodVars} from './constants';
import {getPropertyInView, injectFromViewParentInjector} from './util';
export class CompileNode {
constructor(
public parent: CompileElement, public view: CompileView, public nodeIndex: number,
public renderNode: o.Expression, public sourceAst: TemplateAst) {}
isNull(): boolean { return isBlank(this.renderNode); }
isRootElement(): boolean { return this.view != this.parent.view; }
}
export class CompileElement extends CompileNode {
static createNull(): CompileElement {
return new CompileElement(null, null, null, null, null, null, [], [], false, false, []);
}
private _compViewExpr: o.Expression = null;
public appElement: o.ReadPropExpr;
public elementRef: o.Expression;
public injector: o.Expression;
public instances = new CompileIdentifierMap<CompileTokenMetadata, o.Expression>();
private _resolvedProviders: CompileIdentifierMap<CompileTokenMetadata, ProviderAst>;
private _queryCount = 0;
private _queries = new CompileIdentifierMap<CompileTokenMetadata, CompileQuery[]>();
private _componentConstructorViewQueryLists: o.Expression[] = [];
public contentNodesByNgContentIndex: Array<o.Expression>[] = null;
public embeddedView: CompileView;
public referenceTokens: {[key: string]: CompileTokenMetadata};
constructor(
parent: CompileElement, view: CompileView, nodeIndex: number, renderNode: o.Expression,
sourceAst: TemplateAst, public component: CompileDirectiveMetadata,
private _directives: CompileDirectiveMetadata[],
private _resolvedProvidersArray: ProviderAst[], public hasViewContainer: boolean,
public hasEmbeddedView: boolean, references: ReferenceAst[]) {
super(parent, view, nodeIndex, renderNode, sourceAst);
this.referenceTokens = {};
references.forEach(ref => this.referenceTokens[ref.name] = ref.value);
this.elementRef = o.importExpr(Identifiers.ElementRef).instantiate([this.renderNode]);
this.instances.add(identifierToken(Identifiers.ElementRef), this.elementRef);
this.injector = o.THIS_EXPR.callMethod('injector', [o.literal(this.nodeIndex)]);
this.instances.add(identifierToken(Identifiers.Injector), this.injector);
this.instances.add(identifierToken(Identifiers.Renderer), o.THIS_EXPR.prop('renderer'));
if (this.hasViewContainer || this.hasEmbeddedView || isPresent(this.component)) {
this._createAppElement();
}
}
private _createAppElement() {
var fieldName = `_appEl_${this.nodeIndex}`;
var parentNodeIndex = this.isRootElement() ? null : this.parent.nodeIndex;
// private is fine here as no child view will reference an AppElement
this.view.fields.push(new o.ClassField(
fieldName, o.importType(Identifiers.AppElement), [o.StmtModifier.Private]));
var statement =
o.THIS_EXPR.prop(fieldName)
.set(o.importExpr(Identifiers.AppElement).instantiate([
o.literal(this.nodeIndex), o.literal(parentNodeIndex), o.THIS_EXPR, this.renderNode
]))
.toStmt();
this.view.createMethod.addStmt(statement);
this.appElement = o.THIS_EXPR.prop(fieldName);
this.instances.add(identifierToken(Identifiers.AppElement), this.appElement);
}
public createComponentFactoryResolver(entryComponents: CompileIdentifierMetadata[]) {
if (!entryComponents || entryComponents.length === 0) {
return;
}
var createComponentFactoryResolverExpr =
o.importExpr(Identifiers.CodegenComponentFactoryResolver).instantiate([
o.literalArr(entryComponents.map((entryComponent) => o.importExpr(entryComponent))),
injectFromViewParentInjector(identifierToken(Identifiers.ComponentFactoryResolver), false)
]);
var provider = new CompileProviderMetadata({
token: identifierToken(Identifiers.ComponentFactoryResolver),
useValue: createComponentFactoryResolverExpr
});
// Add ComponentFactoryResolver as first provider as it does not have deps on other providers
// ProviderAstType.PrivateService as only the component and its view can see it,
// but nobody else
this._resolvedProvidersArray.unshift(new ProviderAst(
provider.token, false, true, [provider], ProviderAstType.PrivateService, [],
this.sourceAst.sourceSpan));
}
setComponentView(compViewExpr: o.Expression) {
this._compViewExpr = compViewExpr;
this.contentNodesByNgContentIndex =
ListWrapper.createFixedSize(this.component.template.ngContentSelectors.length);
for (var i = 0; i < this.contentNodesByNgContentIndex.length; i++) {
this.contentNodesByNgContentIndex[i] = [];
}
}
setEmbeddedView(embeddedView: CompileView) {
this.embeddedView = embeddedView;
if (isPresent(embeddedView)) {
var createTemplateRefExpr = o.importExpr(Identifiers.TemplateRef_).instantiate([
this.appElement, this.embeddedView.viewFactory
]);
var provider = new CompileProviderMetadata(
{token: identifierToken(Identifiers.TemplateRef), useValue: createTemplateRefExpr});
// Add TemplateRef as first provider as it does not have deps on other providers
this._resolvedProvidersArray.unshift(new ProviderAst(
provider.token, false, true, [provider], ProviderAstType.Builtin, [],
this.sourceAst.sourceSpan));
}
}
beforeChildren(): void {
if (this.hasViewContainer) {
this.instances.add(
identifierToken(Identifiers.ViewContainerRef), this.appElement.prop('vcRef'));
}
this._resolvedProviders = new CompileIdentifierMap<CompileTokenMetadata, ProviderAst>();
this._resolvedProvidersArray.forEach(
provider => this._resolvedProviders.add(provider.token, provider));
// create all the provider instances, some in the view constructor,
// some as getters. We rely on the fact that they are already sorted topologically.
this._resolvedProviders.values().forEach((resolvedProvider) => {
var providerValueExpressions = resolvedProvider.providers.map((provider) => {
if (isPresent(provider.useExisting)) {
return this._getDependency(
resolvedProvider.providerType,
new CompileDiDependencyMetadata({token: provider.useExisting}));
} else if (isPresent(provider.useFactory)) {
var deps = isPresent(provider.deps) ? provider.deps : provider.useFactory.diDeps;
var depsExpr = deps.map((dep) => this._getDependency(resolvedProvider.providerType, dep));
return o.importExpr(provider.useFactory).callFn(depsExpr);
} else if (isPresent(provider.useClass)) {
var deps = isPresent(provider.deps) ? provider.deps : provider.useClass.diDeps;
var depsExpr = deps.map((dep) => this._getDependency(resolvedProvider.providerType, dep));
return o.importExpr(provider.useClass)
.instantiate(depsExpr, o.importType(provider.useClass));
} else {
return convertValueToOutputAst(provider.useValue);
}
});
var propName = `_${resolvedProvider.token.name}_${this.nodeIndex}_${this.instances.size}`;
var instance = createProviderProperty(
propName, resolvedProvider, providerValueExpressions, resolvedProvider.multiProvider,
resolvedProvider.eager, this);
this.instances.add(resolvedProvider.token, instance);
});
for (var i = 0; i < this._directives.length; i++) {
var directive = this._directives[i];
var directiveInstance = this.instances.get(identifierToken(directive.type));
directive.queries.forEach((queryMeta) => { this._addQuery(queryMeta, directiveInstance); });
}
var queriesWithReads: _QueryWithRead[] = [];
this._resolvedProviders.values().forEach((resolvedProvider) => {
var queriesForProvider = this._getQueriesFor(resolvedProvider.token);
ListWrapper.addAll(
queriesWithReads,
queriesForProvider.map(query => new _QueryWithRead(query, resolvedProvider.token)));
});
StringMapWrapper.forEach(this.referenceTokens, (_: CompileTokenMetadata, varName: string) => {
var token = this.referenceTokens[varName];
var varValue: o.Expression;
if (isPresent(token)) {
varValue = this.instances.get(token);
} else {
varValue = this.renderNode;
}
this.view.locals.set(varName, varValue);
var varToken = new CompileTokenMetadata({value: varName});
ListWrapper.addAll(
queriesWithReads,
this._getQueriesFor(varToken).map(query => new _QueryWithRead(query, varToken)));
});
queriesWithReads.forEach((queryWithRead) => {
var value: o.Expression;
if (isPresent(queryWithRead.read.identifier)) {
// query for an identifier
value = this.instances.get(queryWithRead.read);
} else {
// query for a reference
var token = this.referenceTokens[queryWithRead.read.value];
if (isPresent(token)) {
value = this.instances.get(token);
} else {
value = this.elementRef;
}
}
if (isPresent(value)) {
queryWithRead.query.addValue(value, this.view);
}
});
if (isPresent(this.component)) {
var componentConstructorViewQueryList = isPresent(this.component) ?
o.literalArr(this._componentConstructorViewQueryLists) :
o.NULL_EXPR;
var compExpr = isPresent(this.getComponent()) ? this.getComponent() : o.NULL_EXPR;
this.view.createMethod.addStmt(
this.appElement
.callMethod(
'initComponent',
[compExpr, componentConstructorViewQueryList, this._compViewExpr])
.toStmt());
}
}
afterChildren(childNodeCount: number) {
this._resolvedProviders.values().forEach((resolvedProvider) => {
// Note: afterChildren is called after recursing into children.
// This is good so that an injector match in an element that is closer to a requesting element
// matches first.
var providerExpr = this.instances.get(resolvedProvider.token);
// Note: view providers are only visible on the injector of that element.
// This is not fully correct as the rules during codegen don't allow a directive
// to get hold of a view provdier on the same element. We still do this semantic
// as it simplifies our model to having only one runtime injector per element.
var providerChildNodeCount =
resolvedProvider.providerType === ProviderAstType.PrivateService ? 0 : childNodeCount;
this.view.injectorGetMethod.addStmt(createInjectInternalCondition(
this.nodeIndex, providerChildNodeCount, resolvedProvider, providerExpr));
});
this._queries.values().forEach(
(queries) => queries.forEach(
(query) =>
query.afterChildren(this.view.createMethod, this.view.updateContentQueriesMethod)));
}
addContentNode(ngContentIndex: number, nodeExpr: o.Expression) {
this.contentNodesByNgContentIndex[ngContentIndex].push(nodeExpr);
}
getComponent(): o.Expression {
return isPresent(this.component) ? this.instances.get(identifierToken(this.component.type)) :
null;
}
getProviderTokens(): o.Expression[] {
return this._resolvedProviders.values().map(
(resolvedProvider) => createDiTokenExpression(resolvedProvider.token));
}
private _getQueriesFor(token: CompileTokenMetadata): CompileQuery[] {
var result: CompileQuery[] = [];
var currentEl: CompileElement = this;
var distance = 0;
var queries: CompileQuery[];
while (!currentEl.isNull()) {
queries = currentEl._queries.get(token);
if (isPresent(queries)) {
ListWrapper.addAll(
result, queries.filter((query) => query.meta.descendants || distance <= 1));
}
if (currentEl._directives.length > 0) {
distance++;
}
currentEl = currentEl.parent;
}
queries = this.view.componentView.viewQueries.get(token);
if (isPresent(queries)) {
ListWrapper.addAll(result, queries);
}
return result;
}
private _addQuery(queryMeta: CompileQueryMetadata, directiveInstance: o.Expression):
CompileQuery {
var propName = `_query_${queryMeta.selectors[0].name}_${this.nodeIndex}_${this._queryCount++}`;
var queryList = createQueryList(queryMeta, directiveInstance, propName, this.view);
var query = new CompileQuery(queryMeta, queryList, directiveInstance, this.view);
addQueryToTokenMap(this._queries, query);
return query;
}
private _getLocalDependency(
requestingProviderType: ProviderAstType, dep: CompileDiDependencyMetadata): o.Expression {
var result: o.Expression = null;
// constructor content query
if (isBlank(result) && isPresent(dep.query)) {
result = this._addQuery(dep.query, null).queryList;
}
// constructor view query
if (isBlank(result) && isPresent(dep.viewQuery)) {
result = createQueryList(
dep.viewQuery, null,
`_viewQuery_${dep.viewQuery.selectors[0].name}_${this.nodeIndex}_${this._componentConstructorViewQueryLists.length}`,
this.view);
this._componentConstructorViewQueryLists.push(result);
}
if (isPresent(dep.token)) {
// access builtins with special visibility
if (isBlank(result)) {
if (dep.token.equalsTo(identifierToken(Identifiers.ChangeDetectorRef))) {
if (requestingProviderType === ProviderAstType.Component) {
return this._compViewExpr.prop('ref');
} else {
return getPropertyInView(o.THIS_EXPR.prop('ref'), this.view, this.view.componentView);
}
}
}
// access regular providers on the element
if (isBlank(result)) {
let resolvedProvider = this._resolvedProviders.get(dep.token);
// don't allow directives / public services to access private services.
// only components and private services can access private services.
if (resolvedProvider && (requestingProviderType === ProviderAstType.Directive ||
requestingProviderType === ProviderAstType.PublicService) &&
resolvedProvider.providerType === ProviderAstType.PrivateService) {
return null;
}
result = this.instances.get(dep.token);
}
}
return result;
}
private _getDependency(requestingProviderType: ProviderAstType, dep: CompileDiDependencyMetadata):
o.Expression {
var currElement: CompileElement = this;
var result: o.Expression = null;
if (dep.isValue) {
result = o.literal(dep.value);
}
if (isBlank(result) && !dep.isSkipSelf) {
result = this._getLocalDependency(requestingProviderType, dep);
}
// check parent elements
while (isBlank(result) && !currElement.parent.isNull()) {
currElement = currElement.parent;
result = currElement._getLocalDependency(
ProviderAstType.PublicService, new CompileDiDependencyMetadata({token: dep.token}));
}
if (isBlank(result)) {
result = injectFromViewParentInjector(dep.token, dep.isOptional);
}
if (isBlank(result)) {
result = o.NULL_EXPR;
}
return getPropertyInView(result, this.view, currElement.view);
}
}
function createInjectInternalCondition(
nodeIndex: number, childNodeCount: number, provider: ProviderAst,
providerExpr: o.Expression): o.Statement {
var indexCondition: o.Expression;
if (childNodeCount > 0) {
indexCondition = o.literal(nodeIndex)
.lowerEquals(InjectMethodVars.requestNodeIndex)
.and(InjectMethodVars.requestNodeIndex.lowerEquals(
o.literal(nodeIndex + childNodeCount)));
} else {
indexCondition = o.literal(nodeIndex).identical(InjectMethodVars.requestNodeIndex);
}
return new o.IfStmt(
InjectMethodVars.token.identical(createDiTokenExpression(provider.token)).and(indexCondition),
[new o.ReturnStatement(providerExpr)]);
}
function createProviderProperty(
propName: string, provider: ProviderAst, providerValueExpressions: o.Expression[],
isMulti: boolean, isEager: boolean, compileElement: CompileElement): o.Expression {
var view = compileElement.view;
var resolvedProviderValueExpr: o.Expression;
var type: o.Type;
if (isMulti) {
resolvedProviderValueExpr = o.literalArr(providerValueExpressions);
type = new o.ArrayType(o.DYNAMIC_TYPE);
} else {
resolvedProviderValueExpr = providerValueExpressions[0];
type = providerValueExpressions[0].type;
}
if (isBlank(type)) {
type = o.DYNAMIC_TYPE;
}
if (isEager) {
view.fields.push(new o.ClassField(propName, type));
view.createMethod.addStmt(o.THIS_EXPR.prop(propName).set(resolvedProviderValueExpr).toStmt());
} else {
var internalField = `_${propName}`;
view.fields.push(new o.ClassField(internalField, type));
var getter = new CompileMethod(view);
getter.resetDebugInfo(compileElement.nodeIndex, compileElement.sourceAst);
// Note: Equals is important for JS so that it also checks the undefined case!
getter.addStmt(new o.IfStmt(
o.THIS_EXPR.prop(internalField).isBlank(),
[o.THIS_EXPR.prop(internalField).set(resolvedProviderValueExpr).toStmt()]));
getter.addStmt(new o.ReturnStatement(o.THIS_EXPR.prop(internalField)));
view.getters.push(new o.ClassGetter(propName, getter.finish(), type));
}
return o.THIS_EXPR.prop(propName);
}
class _QueryWithRead {
public read: CompileTokenMetadata;
constructor(public query: CompileQuery, match: CompileTokenMetadata) {
this.read = isPresent(query.meta.read) ? query.meta.read : match;
}
}
| modules/@angular/compiler/src/view_compiler/compile_element.ts | 0 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.0001984998380066827,
0.00017158975242637098,
0.00016438971215393394,
0.00017148812185041606,
0.0000049798222789831925
] |
{
"id": 0,
"code_window": [
"\n",
"import * as html from '../ml_parser/ast';\n",
"import {InterpolationConfig} from '../ml_parser/interpolation_config';\n",
"\n",
"import {digestMessage} from './digest';\n",
"import * as i18n from './i18n_ast';\n",
"import {createI18nMessageFactory} from './i18n_parser';\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {ParseTreeResult} from '../ml_parser/parser';\n"
],
"file_path": "modules/@angular/compiler/src/i18n/extractor_merger.ts",
"type": "add",
"edit_start_line_idx": 10
} |
angular.module('ngComponentRouter').
value('$route', null). // can be overloaded with ngRouteShim
// Because Angular 1 has no notion of a root component, we use an object with unique identity
// to represent this. Can be overloaded with a component name
value('$routerRootComponent', new Object()).
// Unfortunately, $location doesn't expose what the current hashPrefix is
// So we have to monkey patch the $locationProvider to capture this value
provider('$locationHashPrefix', ['$locationProvider', $locationHashPrefixProvider]).
factory('$rootRouter', ['$q', '$location', '$browser', '$rootScope', '$injector', '$routerRootComponent', '$locationHashPrefix', routerFactory]);
function $locationHashPrefixProvider($locationProvider) {
// Get hold of the original hashPrefix method
var hashPrefixFn = $locationProvider.hashPrefix.bind($locationProvider);
// Read the current hashPrefix (in case it was set before this monkey-patch occurred)
var hashPrefix = hashPrefixFn();
// Override the helper so that we can read any changes to the prefix (after this monkey-patch)
$locationProvider.hashPrefix = function(prefix) {
if (angular.isDefined(prefix)) {
hashPrefix = prefix;
}
return hashPrefixFn(prefix);
}
// Return the final hashPrefix as the value of this service
this.$get = function() { return hashPrefix; };
}
function routerFactory($q, $location, $browser, $rootScope, $injector, $routerRootComponent, $locationHashPrefix) {
// When this file is processed, the line below is replaced with
// the contents of `../lib/facades.es5`.
//{{FACADES}}
var exports = {
Injectable: function () {},
OpaqueToken: function () {},
Inject: function () {}
};
var routerRequire = function () {return exports;};
// When this file is processed, the line below is replaced with
// the contents of the compiled TypeScript classes.
//{{SHARED_CODE}}
function getComponentConstructor(name) {
var serviceName = name + 'Directive';
if ($injector.has(serviceName)) {
var definitions = $injector.get(serviceName);
if (definitions.length > 1) {
throw new BaseException('too many directives named "' + name + '"');
}
return definitions[0].controller;
} else {
throw new BaseException('directive "' + name + '" is not registered');
}
}
//TODO: this is a hack to replace the exiting implementation at run-time
exports.getCanActivateHook = function (directiveName) {
var controller = getComponentConstructor(directiveName);
return controller.$canActivate && function (next, prev) {
return $injector.invoke(controller.$canActivate, null, {
$nextInstruction: next,
$prevInstruction: prev
});
};
};
// This hack removes assertions about the type of the "component"
// property in a route config
exports.assertComponentExists = function () {};
angular.stringifyInstruction = function (instruction) {
return instruction.toRootUrl();
};
var RouteRegistry = exports.RouteRegistry;
var RootRouter = exports.RootRouter;
// Override this method to actually get hold of the child routes
RouteRegistry.prototype.configFromComponent = function (component) {
var that = this;
if (isString(component)) {
// Don't read the annotations component a type more than once –
// this prevents an infinite loop if a component routes recursively.
if (this._rules.has(component)) {
return;
}
var controller = getComponentConstructor(component);
if (angular.isArray(controller.$routeConfig)) {
controller.$routeConfig.forEach(function (config) {
var loader = config.loader;
if (isPresent(loader)) {
config = angular.extend({}, config, { loader: function() { return $injector.invoke(loader); } });
}
that.config(component, config);
});
}
}
}
var registry = new RouteRegistry($routerRootComponent);
var location = new Location();
var router = new RootRouter(registry, location, $routerRootComponent);
$rootScope.$watch(function () { return $location.url(); }, function (path) {
if (router.lastNavigationAttempt !== path) {
router.navigateByUrl(path);
}
});
router.subscribe(function () {
$rootScope.$broadcast('$routeChangeSuccess', {});
});
return router;
}
| modules/angular1_router/src/module_template.js | 0 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.00017459577065892518,
0.00017035800556186587,
0.00016402006440330297,
0.00017127746832557023,
0.00000271483872893441
] |
{
"id": 1,
"code_window": [
"\n",
"export function mergeTranslations(\n",
" nodes: html.Node[], translations: TranslationBundle, interpolationConfig: InterpolationConfig,\n",
" implicitTags: string[], implicitAttrs: {[k: string]: string[]}): html.Node[] {\n",
" const visitor = new _Visitor(implicitTags, implicitAttrs);\n",
" return visitor.merge(nodes, translations, interpolationConfig);\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" implicitTags: string[], implicitAttrs: {[k: string]: string[]}): ParseTreeResult {\n"
],
"file_path": "modules/@angular/compiler/src/i18n/extractor_merger.ts",
"type": "replace",
"edit_start_line_idx": 33
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
import {digestMessage, serializeNodes as serializeI18nNodes} from '../../src/i18n/digest';
import {extractMessages, mergeTranslations} from '../../src/i18n/extractor_merger';
import * as i18n from '../../src/i18n/i18n_ast';
import {TranslationBundle} from '../../src/i18n/translation_bundle';
import * as html from '../../src/ml_parser/ast';
import {HtmlParser} from '../../src/ml_parser/html_parser';
import {DEFAULT_INTERPOLATION_CONFIG} from '../../src/ml_parser/interpolation_config';
import {serializeNodes as serializeHtmlNodes} from '../ml_parser/ast_serializer_spec';
export function main() {
describe('Extractor', () => {
describe('elements', () => {
it('should extract from elements', () => {
expect(extract('<div i18n="m|d|e">text<span>nested</span></div>')).toEqual([
[['text', '<ph tag name="START_TAG_SPAN">nested</ph name="CLOSE_TAG_SPAN">'], 'm', 'd|e'],
]);
});
it('should extract from attributes', () => {
expect(
extract(
'<div i18n="m1|d1"><span i18n-title="m2|d2" title="single child">nested</span></div>'))
.toEqual([
[['<ph tag name="START_TAG_SPAN">nested</ph name="CLOSE_TAG_SPAN">'], 'm1', 'd1'],
[['single child'], 'm2', 'd2'],
]);
});
it('should extract from ICU messages', () => {
expect(
extract(
'<div i18n="m|d">{count, plural, =0 { <p i18n-title i18n-desc title="title" desc="desc"></p>}}</div>'))
.toEqual([
[
[
'{count, plural, =0 {[<ph tag name="START_PARAGRAPH"></ph name="CLOSE_PARAGRAPH">]}}'
],
'm', 'd'
],
[['title'], '', ''],
[['desc'], '', ''],
]);
});
it('should not create a message for empty elements',
() => { expect(extract('<div i18n="m|d"></div>')).toEqual([]); });
it('should ignore implicit elements in translatable elements', () => {
expect(extract('<div i18n="m|d"><p></p></div>', ['p'])).toEqual([
[['<ph tag name="START_PARAGRAPH"></ph name="CLOSE_PARAGRAPH">'], 'm', 'd']
]);
});
});
describe('blocks', () => {
it('should extract from blocks', () => {
expect(extract(`<!-- i18n: meaning1|desc1 -->message1<!-- /i18n -->
<!-- i18n: desc2 -->message2<!-- /i18n -->
<!-- i18n -->message3<!-- /i18n -->`))
.toEqual([
[['message1'], 'meaning1', 'desc1'],
[['message2'], '', 'desc2'],
[['message3'], '', ''],
]);
});
it('should ignore implicit elements in blocks', () => {
expect(extract('<!-- i18n:m|d --><p></p><!-- /i18n -->', ['p'])).toEqual([
[['<ph tag name="START_PARAGRAPH"></ph name="CLOSE_PARAGRAPH">'], 'm', 'd']
]);
});
it('should extract siblings', () => {
expect(
extract(
`<!-- i18n -->text<p>html<b>nested</b></p>{count, plural, =0 {<span>html</span>}}{{interp}}<!-- /i18n -->`))
.toEqual([
[
[
'{count, plural, =0 {[<ph tag name="START_TAG_SPAN">html</ph name="CLOSE_TAG_SPAN">]}}'
],
'', ''
],
[
[
'text',
'<ph tag name="START_PARAGRAPH">html, <ph tag name="START_BOLD_TEXT">nested</ph name="CLOSE_BOLD_TEXT"></ph name="CLOSE_PARAGRAPH">',
'<ph icu name="ICU">{count, plural, =0 {[<ph tag name="START_TAG_SPAN">html</ph name="CLOSE_TAG_SPAN">]}}</ph>',
'[<ph name="INTERPOLATION">interp</ph>]'
],
'', ''
],
]);
});
it('should ignore other comments', () => {
expect(extract(`<!-- i18n: meaning1|desc1 --><!-- other -->message1<!-- /i18n -->`))
.toEqual([
[['message1'], 'meaning1', 'desc1'],
]);
});
it('should not create a message for empty blocks',
() => { expect(extract(`<!-- i18n: meaning1|desc1 --><!-- /i18n -->`)).toEqual([]); });
});
describe('ICU messages', () => {
it('should extract ICU messages from translatable elements', () => {
// single message when ICU is the only children
expect(extract('<div i18n="m|d">{count, plural, =0 {text}}</div>')).toEqual([
[['{count, plural, =0 {[text]}}'], 'm', 'd'],
]);
// single message when ICU is the only (implicit) children
expect(extract('<div>{count, plural, =0 {text}}</div>', ['div'])).toEqual([
[['{count, plural, =0 {[text]}}'], '', ''],
]);
// one message for the element content and one message for the ICU
expect(extract('<div i18n="m|d">before{count, plural, =0 {text}}after</div>')).toEqual([
[['before', '<ph icu name="ICU">{count, plural, =0 {[text]}}</ph>', 'after'], 'm', 'd'],
[['{count, plural, =0 {[text]}}'], '', ''],
]);
});
it('should extract ICU messages from translatable block', () => {
// single message when ICU is the only children
expect(extract('<!-- i18n:m|d -->{count, plural, =0 {text}}<!-- /i18n -->')).toEqual([
[['{count, plural, =0 {[text]}}'], 'm', 'd'],
]);
// one message for the block content and one message for the ICU
expect(extract('<!-- i18n:m|d -->before{count, plural, =0 {text}}after<!-- /i18n -->'))
.toEqual([
[['{count, plural, =0 {[text]}}'], '', ''],
[
['before', '<ph icu name="ICU">{count, plural, =0 {[text]}}</ph>', 'after'], 'm',
'd'
],
]);
});
it('should not extract ICU messages outside of i18n sections',
() => { expect(extract('{count, plural, =0 {text}}')).toEqual([]); });
it('should ignore nested ICU messages', () => {
expect(extract('<div i18n="m|d">{count, plural, =0 { {sex, gender, =m {m}} }}</div>'))
.toEqual([
[['{count, plural, =0 {[{sex, gender, =m {[m]}}, ]}}'], 'm', 'd'],
]);
});
it('should ignore implicit elements in non translatable ICU messages', () => {
expect(
extract(
'<div i18n="m|d">{count, plural, =0 { {sex, gender, =m {<p>ignore</p>}} }}</div>',
['p']))
.toEqual([[
[
'{count, plural, =0 {[{sex, gender, =m {[<ph tag name="START_PARAGRAPH">ignore</ph name="CLOSE_PARAGRAPH">]}}, ]}}'
],
'm', 'd'
]]);
});
it('should ignore implicit elements in non translatable ICU messages', () => {
expect(extract('{count, plural, =0 { {sex, gender, =m {<p>ignore</p>}} }}', ['p']))
.toEqual([]);
});
});
describe('attributes', () => {
it('should extract from attributes outside of translatable sections', () => {
expect(extract('<div i18n-title="m|d" title="msg"></div>')).toEqual([
[['msg'], 'm', 'd'],
]);
});
it('should extract from attributes in translatable elements', () => {
expect(extract('<div i18n><p><b i18n-title="m|d" title="msg"></b></p></div>')).toEqual([
[
[
'<ph tag name="START_PARAGRAPH"><ph tag name="START_BOLD_TEXT"></ph name="CLOSE_BOLD_TEXT"></ph name="CLOSE_PARAGRAPH">'
],
'', ''
],
[['msg'], 'm', 'd'],
]);
});
it('should extract from attributes in translatable blocks', () => {
expect(extract('<!-- i18n --><p><b i18n-title="m|d" title="msg"></b></p><!-- /i18n -->'))
.toEqual([
[['msg'], 'm', 'd'],
[
[
'<ph tag name="START_PARAGRAPH"><ph tag name="START_BOLD_TEXT"></ph name="CLOSE_BOLD_TEXT"></ph name="CLOSE_PARAGRAPH">'
],
'', ''
],
]);
});
it('should extract from attributes in translatable ICUs', () => {
expect(
extract(
'<!-- i18n -->{count, plural, =0 {<p><b i18n-title="m|d" title="msg"></b></p>}}<!-- /i18n -->'))
.toEqual([
[['msg'], 'm', 'd'],
[
[
'{count, plural, =0 {[<ph tag name="START_PARAGRAPH"><ph tag name="START_BOLD_TEXT"></ph name="CLOSE_BOLD_TEXT"></ph name="CLOSE_PARAGRAPH">]}}'
],
'', ''
],
]);
});
it('should extract from attributes in non translatable ICUs', () => {
expect(extract('{count, plural, =0 {<p><b i18n-title="m|d" title="msg"></b></p>}}'))
.toEqual([
[['msg'], 'm', 'd'],
]);
});
it('should not create a message for empty attributes',
() => { expect(extract('<div i18n-title="m|d" title></div>')).toEqual([]); });
});
describe('implicit elements', () => {
it('should extract from implicit elements', () => {
expect(extract('<b>bold</b><i>italic</i>', ['b'])).toEqual([
[['bold'], '', ''],
]);
});
it('should allow nested implicit elements', () => {
let result: any[];
expect(() => {
result = extract('<div>outer<div>inner</div></div>', ['div']);
}).not.toThrow();
expect(result).toEqual([
[['outer', '<ph tag name="START_TAG_DIV">inner</ph name="CLOSE_TAG_DIV">'], '', ''],
]);
});
});
describe('implicit attributes', () => {
it('should extract implicit attributes', () => {
expect(extract('<b title="bb">bold</b><i title="ii">italic</i>', [], {'b': ['title']}))
.toEqual([
[['bb'], '', ''],
]);
});
});
describe('errors', () => {
describe('elements', () => {
it('should report nested translatable elements', () => {
expect(extractErrors(`<p i18n><b i18n></b></p>`)).toEqual([
['Could not mark an element as translatable inside a translatable section', '<b i18n>'],
]);
});
it('should report translatable elements in implicit elements', () => {
expect(extractErrors(`<p><b i18n></b></p>`, ['p'])).toEqual([
['Could not mark an element as translatable inside a translatable section', '<b i18n>'],
]);
});
it('should report translatable elements in translatable blocks', () => {
expect(extractErrors(`<!-- i18n --><b i18n></b><!-- /i18n -->`)).toEqual([
['Could not mark an element as translatable inside a translatable section', '<b i18n>'],
]);
});
});
describe('blocks', () => {
it('should report nested blocks', () => {
expect(extractErrors(`<!-- i18n --><!-- i18n --><!-- /i18n --><!-- /i18n -->`)).toEqual([
['Could not start a block inside a translatable section', '<!--'],
['Trying to close an unopened block', '<!--'],
]);
});
it('should report unclosed blocks', () => {
expect(extractErrors(`<!-- i18n -->`)).toEqual([
['Unclosed block', '<!--'],
]);
});
it('should report translatable blocks in translatable elements', () => {
expect(extractErrors(`<p i18n><!-- i18n --><!-- /i18n --></p>`)).toEqual([
['Could not start a block inside a translatable section', '<!--'],
['Trying to close an unopened block', '<!--'],
]);
});
it('should report translatable blocks in implicit elements', () => {
expect(extractErrors(`<p><!-- i18n --><!-- /i18n --></p>`, ['p'])).toEqual([
['Could not start a block inside a translatable section', '<!--'],
['Trying to close an unopened block', '<!--'],
]);
});
it('should report when start and end of a block are not at the same level', () => {
expect(extractErrors(`<!-- i18n --><p><!-- /i18n --></p>`)).toEqual([
['I18N blocks should not cross element boundaries', '<!--'],
['Unclosed block', '<p>'],
]);
expect(extractErrors(`<p><!-- i18n --></p><!-- /i18n -->`)).toEqual([
['I18N blocks should not cross element boundaries', '<!--'],
['Unclosed block', '<!--'],
]);
});
});
});
});
describe('Merger', () => {
describe('elements', () => {
it('should merge elements', () => {
const HTML = `<p i18n="m|d">foo</p>`;
expect(fakeTranslate(HTML)).toEqual('<p>**foo**</p>');
});
it('should merge nested elements', () => {
const HTML = `<div>before<p i18n="m|d">foo</p><!-- comment --></div>`;
expect(fakeTranslate(HTML)).toEqual('<div>before<p>**foo**</p></div>');
});
});
describe('blocks', () => {
it('should merge blocks', () => {
const HTML = `before<!-- i18n --><p>foo</p><span><i>bar</i></span><!-- /i18n -->after`;
expect(fakeTranslate(HTML))
.toEqual(
'before**<ph tag name="START_PARAGRAPH">foo</ph name="CLOSE_PARAGRAPH"><ph tag name="START_TAG_SPAN"><ph tag name="START_ITALIC_TEXT">bar</ph name="CLOSE_ITALIC_TEXT"></ph name="CLOSE_TAG_SPAN">**after');
});
it('should merge nested blocks', () => {
const HTML =
`<div>before<!-- i18n --><p>foo</p><span><i>bar</i></span><!-- /i18n -->after</div>`;
expect(fakeTranslate(HTML))
.toEqual(
'<div>before**<ph tag name="START_PARAGRAPH">foo</ph name="CLOSE_PARAGRAPH"><ph tag name="START_TAG_SPAN"><ph tag name="START_ITALIC_TEXT">bar</ph name="CLOSE_ITALIC_TEXT"></ph name="CLOSE_TAG_SPAN">**after</div>');
});
});
describe('attributes', () => {
it('should merge attributes', () => {
const HTML = `<p i18n-title="m|d" title="foo"></p>`;
expect(fakeTranslate(HTML)).toEqual('<p title="**foo**"></p>');
});
it('should merge nested attributes', () => {
const HTML = `<div>{count, plural, =0 {<p i18n-title title="foo"></p>}}</div>`;
expect(fakeTranslate(HTML))
.toEqual('<div>{count, plural, =0 {<p title="**foo**"></p>}}</div>');
});
it('should merge attributes without values', () => {
const HTML = `<p i18n-title="m|d" title=""></p>`;
expect(fakeTranslate(HTML)).toEqual('<p title=""></p>');
});
});
});
}
function parseHtml(html: string): html.Node[] {
const htmlParser = new HtmlParser();
const parseResult = htmlParser.parse(html, 'extractor spec', true);
if (parseResult.errors.length > 1) {
throw new Error(`unexpected parse errors: ${parseResult.errors.join('\n')}`);
}
return parseResult.rootNodes;
}
function fakeTranslate(
content: string, implicitTags: string[] = [],
implicitAttrs: {[k: string]: string[]} = {}): string {
const htmlNodes: html.Node[] = parseHtml(content);
const messages: i18n.Message[] =
extractMessages(htmlNodes, DEFAULT_INTERPOLATION_CONFIG, implicitTags, implicitAttrs)
.messages;
const i18nMsgMap: {[id: string]: html.Node[]} = {};
messages.forEach(message => {
const id = digestMessage(message);
const text = serializeI18nNodes(message.nodes).join('');
i18nMsgMap[id] = [new html.Text(`**${text}**`, null)];
});
const translations = new TranslationBundle(i18nMsgMap);
const translateNodes = mergeTranslations(
htmlNodes, translations, DEFAULT_INTERPOLATION_CONFIG, implicitTags, implicitAttrs);
return serializeHtmlNodes(translateNodes).join('');
}
function extract(
html: string, implicitTags: string[] = [],
implicitAttrs: {[k: string]: string[]} = {}): [string[], string, string][] {
const result =
extractMessages(parseHtml(html), DEFAULT_INTERPOLATION_CONFIG, implicitTags, implicitAttrs);
if (result.errors.length > 0) {
throw new Error(`unexpected errors: ${result.errors.join('\n')}`);
}
// clang-format off
// https://github.com/angular/clang-format/issues/35
return result.messages.map(
message => [serializeI18nNodes(message.nodes), message.meaning, message.description, ]) as [string[], string, string][];
// clang-format on
}
function extractErrors(
html: string, implicitTags: string[] = [], implicitAttrs: {[k: string]: string[]} = {}): any[] {
const errors =
extractMessages(parseHtml(html), DEFAULT_INTERPOLATION_CONFIG, implicitTags, implicitAttrs)
.errors;
return errors.map((e): [string, string] => [e.msg, e.span.toString()]);
}
| modules/@angular/compiler/test/i18n/extractor_merger_spec.ts | 1 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.9989959597587585,
0.04504961520433426,
0.00016071581922005862,
0.00017383164959028363,
0.20384712517261505
] |
{
"id": 1,
"code_window": [
"\n",
"export function mergeTranslations(\n",
" nodes: html.Node[], translations: TranslationBundle, interpolationConfig: InterpolationConfig,\n",
" implicitTags: string[], implicitAttrs: {[k: string]: string[]}): html.Node[] {\n",
" const visitor = new _Visitor(implicitTags, implicitAttrs);\n",
" return visitor.merge(nodes, translations, interpolationConfig);\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" implicitTags: string[], implicitAttrs: {[k: string]: string[]}): ParseTreeResult {\n"
],
"file_path": "modules/@angular/compiler/src/i18n/extractor_merger.ts",
"type": "replace",
"edit_start_line_idx": 33
} | import {Component} from '@angular/core';
import {bootstrap} from '@angular/platform-browser';
@Component({
selector: 'hello-app',
template: `
<h1>Hello, {{name}}!</h1>
<label> Say hello to: <input [value]="name" (input)="name = $event.target.value"></label>
`
})
class HelloCmp {
name = 'World';
}
bootstrap(HelloCmp);
| modules/payload_tests/hello_world/ts/systemjs/index.ts | 0 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.0001745559711707756,
0.0001727606577333063,
0.00017096534429583699,
0.0001727606577333063,
0.0000017953134374693036
] |
{
"id": 1,
"code_window": [
"\n",
"export function mergeTranslations(\n",
" nodes: html.Node[], translations: TranslationBundle, interpolationConfig: InterpolationConfig,\n",
" implicitTags: string[], implicitAttrs: {[k: string]: string[]}): html.Node[] {\n",
" const visitor = new _Visitor(implicitTags, implicitAttrs);\n",
" return visitor.merge(nodes, translations, interpolationConfig);\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" implicitTags: string[], implicitAttrs: {[k: string]: string[]}): ParseTreeResult {\n"
],
"file_path": "modules/@angular/compiler/src/i18n/extractor_merger.ts",
"type": "replace",
"edit_start_line_idx": 33
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {COMPILER_OPTIONS, Compiler, CompilerFactory, CompilerOptions, Component, Inject, Injectable, OptionalMetadata, PLATFORM_DIRECTIVES, PLATFORM_INITIALIZER, PLATFORM_PIPES, PlatformRef, Provider, ReflectiveInjector, Type, ViewEncapsulation, createPlatformFactory, isDevMode, platformCore} from '@angular/core';
export * from './template_parser/template_ast';
export {TEMPLATE_TRANSFORMS} from './template_parser/template_parser';
export {CompilerConfig, RenderTypes} from './config';
export * from './compile_metadata';
export * from './offline_compiler';
export {RuntimeCompiler} from './runtime_compiler';
export * from './url_resolver';
export * from './xhr';
export {DirectiveResolver} from './directive_resolver';
export {PipeResolver} from './pipe_resolver';
export {NgModuleResolver} from './ng_module_resolver';
import {stringify} from './facade/lang';
import {ListWrapper} from './facade/collection';
import {TemplateParser} from './template_parser/template_parser';
import {HtmlParser} from './ml_parser/html_parser';
import {DirectiveNormalizer} from './directive_normalizer';
import {CompileMetadataResolver} from './metadata_resolver';
import {StyleCompiler} from './style_compiler';
import {ViewCompiler} from './view_compiler/view_compiler';
import {NgModuleCompiler} from './ng_module_compiler';
import {CompilerConfig} from './config';
import {RuntimeCompiler} from './runtime_compiler';
import {ElementSchemaRegistry} from './schema/element_schema_registry';
import {DomElementSchemaRegistry} from './schema/dom_element_schema_registry';
import {UrlResolver, DEFAULT_PACKAGE_URL_PROVIDER} from './url_resolver';
import {Parser} from './expression_parser/parser';
import {Lexer} from './expression_parser/lexer';
import {DirectiveResolver} from './directive_resolver';
import {PipeResolver} from './pipe_resolver';
import {NgModuleResolver} from './ng_module_resolver';
import {Console, Reflector, reflector, ReflectorReader, ReflectionCapabilities} from '../core_private';
import {XHR} from './xhr';
import * as i18n from './i18n/index';
const _NO_XHR: XHR = {
get(url: string): Promise<string>{
throw new Error(`No XHR implementation has been provided. Can't read the url "${url}"`);}
};
/**
* A set of providers that provide `RuntimeCompiler` and its dependencies to use for
* template compilation.
*/
export const COMPILER_PROVIDERS: Array<any|Type<any>|{[k: string]: any}|any[]> = [
{provide: Reflector, useValue: reflector},
{provide: ReflectorReader, useExisting: Reflector},
{provide: XHR, useValue: _NO_XHR},
Console,
Lexer,
Parser,
HtmlParser,
{
provide: i18n.HtmlParser,
useFactory: (parser: HtmlParser, translations: string) =>
new i18n.HtmlParser(parser, translations),
deps: [HtmlParser, [new OptionalMetadata(), new Inject(i18n.TRANSLATIONS)]]
},
TemplateParser,
DirectiveNormalizer,
CompileMetadataResolver,
DEFAULT_PACKAGE_URL_PROVIDER,
StyleCompiler,
ViewCompiler,
NgModuleCompiler,
{provide: CompilerConfig, useValue: new CompilerConfig()},
RuntimeCompiler,
{provide: Compiler, useExisting: RuntimeCompiler},
DomElementSchemaRegistry,
{provide: ElementSchemaRegistry, useExisting: DomElementSchemaRegistry},
UrlResolver,
DirectiveResolver,
PipeResolver,
NgModuleResolver
];
export function analyzeAppProvidersForDeprecatedConfiguration(appProviders: any[] = []): {
compilerOptions: CompilerOptions,
moduleDeclarations: Type<any>[],
deprecationMessages: string[]
} {
let platformDirectives: any[] = [];
let platformPipes: any[] = [];
let compilerProviders: any[] = [];
let useDebug: boolean;
let useJit: boolean;
let defaultEncapsulation: ViewEncapsulation;
const deprecationMessages: string[] = [];
// Note: This is a hack to still support the old way
// of configuring platform directives / pipes and the compiler xhr.
// This will soon be deprecated!
const tempInj = ReflectiveInjector.resolveAndCreate(appProviders);
const compilerConfig: CompilerConfig = tempInj.get(CompilerConfig, null);
if (compilerConfig) {
platformDirectives = compilerConfig.platformDirectives;
platformPipes = compilerConfig.platformPipes;
useJit = compilerConfig.useJit;
useDebug = compilerConfig.genDebugInfo;
defaultEncapsulation = compilerConfig.defaultEncapsulation;
deprecationMessages.push(
`Passing CompilerConfig as a regular provider is deprecated. Use the "compilerOptions" parameter of "bootstrap()" or use a custom "CompilerFactory" platform provider instead.`);
} else {
// If nobody provided a CompilerConfig, use the
// PLATFORM_DIRECTIVES / PLATFORM_PIPES values directly if existing
platformDirectives = tempInj.get(PLATFORM_DIRECTIVES, []);
platformPipes = tempInj.get(PLATFORM_PIPES, []);
}
platformDirectives = ListWrapper.flatten(platformDirectives);
platformPipes = ListWrapper.flatten(platformPipes);
const xhr = tempInj.get(XHR, null);
if (xhr) {
compilerProviders.push([{provide: XHR, useValue: xhr}]);
deprecationMessages.push(
`Passing XHR as regular provider is deprecated. Pass the provider via "compilerOptions" instead.`);
}
if (platformDirectives.length > 0) {
deprecationMessages.push(
`The PLATFORM_DIRECTIVES provider and CompilerConfig.platformDirectives is deprecated. Add the directives to an NgModule instead! ` +
`(Directives: ${platformDirectives.map(type => stringify(type))})`);
}
if (platformPipes.length > 0) {
deprecationMessages.push(
`The PLATFORM_PIPES provider and CompilerConfig.platformPipes is deprecated. Add the pipes to an NgModule instead! ` +
`(Pipes: ${platformPipes.map(type => stringify(type))})`);
}
const compilerOptions: CompilerOptions = {
useJit: useJit,
useDebug: useDebug,
defaultEncapsulation: defaultEncapsulation,
providers: compilerProviders
};
// Declare a component that uses @Component.directives / pipes as these
// will be added to the module declarations only if they are not already
// imported by other modules.
@Component({directives: platformDirectives, pipes: platformPipes, template: ''})
class DynamicComponent {
}
return {
compilerOptions,
moduleDeclarations: [DynamicComponent],
deprecationMessages: deprecationMessages
};
}
@Injectable()
export class RuntimeCompilerFactory implements CompilerFactory {
private _defaultOptions: CompilerOptions[];
constructor(@Inject(COMPILER_OPTIONS) defaultOptions: CompilerOptions[]) {
this._defaultOptions = [<CompilerOptions>{
useDebug: isDevMode(),
useJit: true,
defaultEncapsulation: ViewEncapsulation.Emulated
}].concat(defaultOptions);
}
createCompiler(options: CompilerOptions[] = []): Compiler {
const mergedOptions = _mergeOptions(this._defaultOptions.concat(options));
const injector = ReflectiveInjector.resolveAndCreate([
COMPILER_PROVIDERS, {
provide: CompilerConfig,
useFactory: () => {
return new CompilerConfig({
// let explicit values from the compiler options overwrite options
// from the app providers. E.g. important for the testing platform.
genDebugInfo: mergedOptions.useDebug,
// let explicit values from the compiler options overwrite options
// from the app providers
useJit: mergedOptions.useJit,
// let explicit values from the compiler options overwrite options
// from the app providers
defaultEncapsulation: mergedOptions.defaultEncapsulation,
logBindingUpdate: mergedOptions.useDebug
});
},
deps: []
},
mergedOptions.providers
]);
return injector.get(Compiler);
}
}
function _initReflector() {
reflector.reflectionCapabilities = new ReflectionCapabilities();
}
/**
* A platform that included corePlatform and the compiler.
*
* @experimental
*/
export const platformCoreDynamic = createPlatformFactory(platformCore, 'coreDynamic', [
{provide: COMPILER_OPTIONS, useValue: {}, multi: true},
{provide: CompilerFactory, useClass: RuntimeCompilerFactory},
{provide: PLATFORM_INITIALIZER, useValue: _initReflector, multi: true},
]);
function _mergeOptions(optionsArr: CompilerOptions[]): CompilerOptions {
return {
useDebug: _lastDefined(optionsArr.map(options => options.useDebug)),
useJit: _lastDefined(optionsArr.map(options => options.useJit)),
defaultEncapsulation: _lastDefined(optionsArr.map(options => options.defaultEncapsulation)),
providers: _mergeArrays(optionsArr.map(options => options.providers))
};
}
function _lastDefined<T>(args: T[]): T {
for (var i = args.length - 1; i >= 0; i--) {
if (args[i] !== undefined) {
return args[i];
}
}
return undefined;
}
function _mergeArrays(parts: any[][]): any[] {
let result: any[] = [];
parts.forEach((part) => part && result.push(...part));
return result;
}
| modules/@angular/compiler/src/compiler.ts | 0 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.004026038572192192,
0.0003425648610573262,
0.0001650072226766497,
0.00017126207239925861,
0.0007696269894950092
] |
{
"id": 1,
"code_window": [
"\n",
"export function mergeTranslations(\n",
" nodes: html.Node[], translations: TranslationBundle, interpolationConfig: InterpolationConfig,\n",
" implicitTags: string[], implicitAttrs: {[k: string]: string[]}): html.Node[] {\n",
" const visitor = new _Visitor(implicitTags, implicitAttrs);\n",
" return visitor.merge(nodes, translations, interpolationConfig);\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" implicitTags: string[], implicitAttrs: {[k: string]: string[]}): ParseTreeResult {\n"
],
"file_path": "modules/@angular/compiler/src/i18n/extractor_merger.ts",
"type": "replace",
"edit_start_line_idx": 33
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {OnInit} from '@angular/core';
import {ReflectionInfo, Reflector} from '@angular/core/src/reflection/reflection';
import {ReflectionCapabilities} from '@angular/core/src/reflection/reflection_capabilities';
import {beforeEach, ddescribe, describe, expect, iit, it} from '@angular/core/testing/testing_internal';
import {browserDetection} from '@angular/platform-browser/testing/browser_util';
import {ClassDecorator, HasGetterAndSetterDecorators, ParamDecorator, PropDecorator, classDecorator, paramDecorator, propDecorator} from './reflector_common';
class AType {
value: any /** TODO #9100 */;
constructor(value: any /** TODO #9100 */) { this.value = value; }
}
@ClassDecorator('class')
class ClassWithDecorators {
@PropDecorator('p1') @PropDecorator('p2') a: any /** TODO #9100 */;
b: any /** TODO #9100 */;
@PropDecorator('p3')
set c(value: any /** TODO #9100 */) {}
@PropDecorator('p4')
someMethod() {}
constructor(@ParamDecorator('a') a: AType, @ParamDecorator('b') b: AType) {
this.a = a;
this.b = b;
}
}
class ClassWithoutDecorators {
constructor(a: any /** TODO #9100 */, b: any /** TODO #9100 */) {}
}
class TestObj {
a: any /** TODO #9100 */;
b: any /** TODO #9100 */;
constructor(a: any /** TODO #9100 */, b: any /** TODO #9100 */) {
this.a = a;
this.b = b;
}
identity(arg: any /** TODO #9100 */) { return arg; }
}
class Interface {}
class Interface2 {}
class SuperClassImplementingInterface implements Interface2 {}
class ClassImplementingInterface extends SuperClassImplementingInterface implements Interface {}
// Classes used to test our runtime check for classes that implement lifecycle interfaces but do not
// declare them.
// See https://github.com/angular/angular/pull/6879 and https://goo.gl/b07Kii for details.
class ClassDoesNotDeclareOnInit {
ngOnInit() {}
}
class SuperClassImplementingOnInit implements OnInit {
ngOnInit() {}
}
class SubClassDoesNotDeclareOnInit extends SuperClassImplementingOnInit {}
export function main() {
describe('Reflector', () => {
var reflector: any /** TODO #9100 */;
beforeEach(() => { reflector = new Reflector(new ReflectionCapabilities()); });
describe('usage tracking', () => {
beforeEach(() => { reflector = new Reflector(null); });
it('should be disabled by default', () => {
expect(() => reflector.listUnusedKeys()).toThrowError('Usage tracking is disabled');
});
it('should report unused keys', () => {
reflector.trackUsage();
expect(reflector.listUnusedKeys()).toEqual([]);
reflector.registerType(AType, new ReflectionInfo(null, null, () => 'AType'));
reflector.registerType(TestObj, new ReflectionInfo(null, null, () => 'TestObj'));
expect(reflector.listUnusedKeys()).toEqual([AType, TestObj]);
reflector.factory(AType);
expect(reflector.listUnusedKeys()).toEqual([TestObj]);
reflector.factory(TestObj);
expect(reflector.listUnusedKeys()).toEqual([]);
});
});
describe('factory', () => {
it('should create a factory for the given type', () => {
var obj = reflector.factory(TestObj)(1, 2);
expect(obj.a).toEqual(1);
expect(obj.b).toEqual(2);
});
it('should check args from no to max', () => {
var f = (t: any /** TODO #9100 */) => reflector.factory(t);
var checkArgs = (obj: any /** TODO #9100 */, args: any /** TODO #9100 */) =>
expect(obj.args).toEqual(args);
// clang-format off
checkArgs(f(TestObjWith00Args)(), []);
checkArgs(f(TestObjWith01Args)(1), [1]);
checkArgs(f(TestObjWith02Args)(1, 2), [1, 2]);
checkArgs(f(TestObjWith03Args)(1, 2, 3), [1, 2, 3]);
checkArgs(f(TestObjWith04Args)(1, 2, 3, 4), [1, 2, 3, 4]);
checkArgs(f(TestObjWith05Args)(1, 2, 3, 4, 5), [1, 2, 3, 4, 5]);
checkArgs(f(TestObjWith06Args)(1, 2, 3, 4, 5, 6), [1, 2, 3, 4, 5, 6]);
checkArgs(f(TestObjWith07Args)(1, 2, 3, 4, 5, 6, 7), [1, 2, 3, 4, 5, 6, 7]);
checkArgs(f(TestObjWith08Args)(1, 2, 3, 4, 5, 6, 7, 8), [1, 2, 3, 4, 5, 6, 7, 8]);
checkArgs(f(TestObjWith09Args)(1, 2, 3, 4, 5, 6, 7, 8, 9), [1, 2, 3, 4, 5, 6, 7, 8, 9]);
checkArgs(f(TestObjWith10Args)(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
checkArgs(f(TestObjWith11Args)(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
checkArgs(f(TestObjWith12Args)(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
checkArgs(f(TestObjWith13Args)(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]);
checkArgs(f(TestObjWith14Args)(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]);
checkArgs(f(TestObjWith15Args)(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);
checkArgs(f(TestObjWith16Args)(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
checkArgs(f(TestObjWith17Args)(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]);
checkArgs(f(TestObjWith18Args)(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]);
checkArgs(f(TestObjWith19Args)(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]);
checkArgs(f(TestObjWith20Args)(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]);
// clang-format on
});
it('should return a registered factory if available', () => {
reflector.registerType(TestObj, new ReflectionInfo(null, null, () => 'fake'));
expect(reflector.factory(TestObj)()).toEqual('fake');
});
});
describe('parameters', () => {
it('should return an array of parameters for a type', () => {
var p = reflector.parameters(ClassWithDecorators);
expect(p).toEqual([[AType, paramDecorator('a')], [AType, paramDecorator('b')]]);
});
it('should work for a class without annotations', () => {
var p = reflector.parameters(ClassWithoutDecorators);
expect(p.length).toEqual(2);
});
it('should return registered parameters if available', () => {
reflector.registerType(TestObj, new ReflectionInfo(null, [[1], [2]]));
expect(reflector.parameters(TestObj)).toEqual([[1], [2]]);
});
it('should return an empty list when no parameters field in the stored type info', () => {
reflector.registerType(TestObj, new ReflectionInfo());
expect(reflector.parameters(TestObj)).toEqual([]);
});
});
describe('propMetadata', () => {
it('should return a string map of prop metadata for the given class', () => {
var p = reflector.propMetadata(ClassWithDecorators);
expect(p['a']).toEqual([propDecorator('p1'), propDecorator('p2')]);
expect(p['c']).toEqual([propDecorator('p3')]);
expect(p['someMethod']).toEqual([propDecorator('p4')]);
});
it('should return registered meta if available', () => {
reflector.registerType(TestObj, new ReflectionInfo(null, null, null, null, {'a': [1, 2]}));
expect(reflector.propMetadata(TestObj)).toEqual({'a': [1, 2]});
});
});
describe('annotations', () => {
it('should return an array of annotations for a type', () => {
var p = reflector.annotations(ClassWithDecorators);
expect(p).toEqual([classDecorator('class')]);
});
it('should return registered annotations if available', () => {
reflector.registerType(TestObj, new ReflectionInfo([1, 2]));
expect(reflector.annotations(TestObj)).toEqual([1, 2]);
});
it('should work for a class without annotations', () => {
var p = reflector.annotations(ClassWithoutDecorators);
expect(p).toEqual([]);
});
});
describe('getter', () => {
it('returns a function reading a property', () => {
var getA = reflector.getter('a');
expect(getA(new TestObj(1, 2))).toEqual(1);
});
it('should return a registered getter if available', () => {
reflector.registerGetters({'abc': (obj: any /** TODO #9100 */) => 'fake'});
expect(reflector.getter('abc')('anything')).toEqual('fake');
});
});
describe('setter', () => {
it('returns a function setting a property', () => {
var setA = reflector.setter('a');
var obj = new TestObj(1, 2);
setA(obj, 100);
expect(obj.a).toEqual(100);
});
it('should return a registered setter if available', () => {
var updateMe: any /** TODO #9100 */;
reflector.registerSetters({
'abc': (obj: any /** TODO #9100 */, value: any /** TODO #9100 */) => { updateMe = value; }
});
reflector.setter('abc')('anything', 'fake');
expect(updateMe).toEqual('fake');
});
});
describe('method', () => {
it('returns a function invoking a method', () => {
var func = reflector.method('identity');
var obj = new TestObj(1, 2);
expect(func(obj, ['value'])).toEqual('value');
});
it('should return a registered method if available', () => {
reflector.registerMethods(
{'abc': (obj: any /** TODO #9100 */, args: any /** TODO #9100 */) => args});
expect(reflector.method('abc')('anything', ['fake'])).toEqual(['fake']);
});
});
});
}
class TestObjWith00Args {
args: any[];
constructor() { this.args = []; }
}
class TestObjWith01Args {
args: any[];
constructor(a1: any) { this.args = [a1]; }
}
class TestObjWith02Args {
args: any[];
constructor(a1: any, a2: any) { this.args = [a1, a2]; }
}
class TestObjWith03Args {
args: any[];
constructor(a1: any, a2: any, a3: any) { this.args = [a1, a2, a3]; }
}
class TestObjWith04Args {
args: any[];
constructor(a1: any, a2: any, a3: any, a4: any) { this.args = [a1, a2, a3, a4]; }
}
class TestObjWith05Args {
args: any[];
constructor(a1: any, a2: any, a3: any, a4: any, a5: any) { this.args = [a1, a2, a3, a4, a5]; }
}
class TestObjWith06Args {
args: any[];
constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any) {
this.args = [a1, a2, a3, a4, a5, a6];
}
}
class TestObjWith07Args {
args: any[];
constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any) {
this.args = [a1, a2, a3, a4, a5, a6, a7];
}
}
class TestObjWith08Args {
args: any[];
constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any) {
this.args = [a1, a2, a3, a4, a5, a6, a7, a8];
}
}
class TestObjWith09Args {
args: any[];
constructor(a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any) {
this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9];
}
}
class TestObjWith10Args {
args: any[];
constructor(
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any) {
this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10];
}
}
class TestObjWith11Args {
args: any[];
constructor(
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any,
a11: any) {
this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11];
}
}
class TestObjWith12Args {
args: any[];
constructor(
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any,
a11: any, a12: any) {
this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12];
}
}
class TestObjWith13Args {
args: any[];
constructor(
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any,
a11: any, a12: any, a13: any) {
this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13];
}
}
class TestObjWith14Args {
args: any[];
constructor(
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any,
a11: any, a12: any, a13: any, a14: any) {
this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14];
}
}
class TestObjWith15Args {
args: any[];
constructor(
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any,
a11: any, a12: any, a13: any, a14: any, a15: any) {
this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15];
}
}
class TestObjWith16Args {
args: any[];
constructor(
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any,
a11: any, a12: any, a13: any, a14: any, a15: any, a16: any) {
this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16];
}
}
class TestObjWith17Args {
args: any[];
constructor(
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any,
a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any) {
this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17];
}
}
class TestObjWith18Args {
args: any[];
constructor(
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any,
a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any, a18: any) {
this.args = [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18];
}
}
class TestObjWith19Args {
args: any[];
constructor(
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any,
a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any, a18: any, a19: any) {
this.args =
[a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19];
}
}
class TestObjWith20Args {
args: any[];
constructor(
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any,
a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any, a18: any, a19: any,
a20: any) {
this.args =
[a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20];
}
}
class TestObjWith21Args {
args: any[];
constructor(
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any, a10: any,
a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any, a18: any, a19: any,
a20: any, a21: any) {
this.args = [
a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11,
a12, a13, a14, a15, a16, a17, a18, a19, a20, a21
];
}
}
| modules/@angular/core/test/reflection/reflector_spec.ts | 0 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.00018450798233971,
0.00017418860807083547,
0.00016634335042908788,
0.00017487267905380577,
0.000004281220299162669
] |
{
"id": 2,
"code_window": [
" */\n",
" merge(\n",
" nodes: html.Node[], translations: TranslationBundle,\n",
" interpolationConfig: InterpolationConfig): html.Node[] {\n",
" this._init(_VisitorMode.Merge, interpolationConfig);\n",
" this._translations = translations;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" interpolationConfig: InterpolationConfig): ParseTreeResult {\n"
],
"file_path": "modules/@angular/compiler/src/i18n/extractor_merger.ts",
"type": "replace",
"edit_start_line_idx": 104
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as html from '../ml_parser/ast';
import {InterpolationConfig} from '../ml_parser/interpolation_config';
import {digestMessage} from './digest';
import * as i18n from './i18n_ast';
import {createI18nMessageFactory} from './i18n_parser';
import {I18nError} from './parse_util';
import {TranslationBundle} from './translation_bundle';
const _I18N_ATTR = 'i18n';
const _I18N_ATTR_PREFIX = 'i18n-';
const _I18N_COMMENT_PREFIX_REGEXP = /^i18n:?/;
/**
* Extract translatable messages from an html AST
*/
export function extractMessages(
nodes: html.Node[], interpolationConfig: InterpolationConfig, implicitTags: string[],
implicitAttrs: {[k: string]: string[]}): ExtractionResult {
const visitor = new _Visitor(implicitTags, implicitAttrs);
return visitor.extract(nodes, interpolationConfig);
}
export function mergeTranslations(
nodes: html.Node[], translations: TranslationBundle, interpolationConfig: InterpolationConfig,
implicitTags: string[], implicitAttrs: {[k: string]: string[]}): html.Node[] {
const visitor = new _Visitor(implicitTags, implicitAttrs);
return visitor.merge(nodes, translations, interpolationConfig);
}
export class ExtractionResult {
constructor(public messages: i18n.Message[], public errors: I18nError[]) {}
}
enum _VisitorMode {
Extract,
Merge
}
/**
* This Visitor is used:
* 1. to extract all the translatable strings from an html AST (see `extract()`),
* 2. to replace the translatable strings with the actual translations (see `merge()`)
*
* @internal
*/
class _Visitor implements html.Visitor {
// <el i18n>...</el>
private _inI18nNode: boolean;
private _depth: number;
private _inImplicitNode: boolean;
// <!--i18n-->...<!--/i18n-->
private _blockMeaningAndDesc: string;
private _blockChildren: html.Node[];
private _blockStartDepth: number;
private _inI18nBlock: boolean;
// {<icu message>}
private _inIcu: boolean;
private _msgCountAtSectionStart: number;
private _errors: I18nError[];
private _mode: _VisitorMode;
// _VisitorMode.Extract only
private _messages: i18n.Message[];
// _VisitorMode.Merge only
private _translations: TranslationBundle;
private _createI18nMessage:
(msg: html.Node[], meaning: string, description: string) => i18n.Message;
constructor(private _implicitTags: string[], private _implicitAttrs: {[k: string]: string[]}) {}
/**
* Extracts the messages from the tree
*/
extract(nodes: html.Node[], interpolationConfig: InterpolationConfig): ExtractionResult {
this._init(_VisitorMode.Extract, interpolationConfig);
nodes.forEach(node => node.visit(this, null));
if (this._inI18nBlock) {
this._reportError(nodes[nodes.length - 1], 'Unclosed block');
}
return new ExtractionResult(this._messages, this._errors);
}
/**
* Returns a tree where all translatable nodes are translated
*/
merge(
nodes: html.Node[], translations: TranslationBundle,
interpolationConfig: InterpolationConfig): html.Node[] {
this._init(_VisitorMode.Merge, interpolationConfig);
this._translations = translations;
// Construct a single fake root element
const wrapper = new html.Element('wrapper', [], nodes, null, null, null);
const translatedNode = wrapper.visit(this, null);
// TODO(vicb): return MergeResult with errors
if (this._inI18nBlock) {
this._reportError(nodes[nodes.length - 1], 'Unclosed block');
}
return translatedNode.children;
}
visitExpansionCase(icuCase: html.ExpansionCase, context: any): any {
// Parse cases for translatable html attributes
const expression = html.visitAll(this, icuCase.expression, context);
if (this._mode === _VisitorMode.Merge) {
return new html.ExpansionCase(
icuCase.value, expression, icuCase.sourceSpan, icuCase.valueSourceSpan,
icuCase.expSourceSpan);
}
}
visitExpansion(icu: html.Expansion, context: any): html.Expansion {
this._mayBeAddBlockChildren(icu);
const wasInIcu = this._inIcu;
if (!this._inIcu) {
// nested ICU messages should not be extracted but top-level translated as a whole
if (this._isInTranslatableSection) {
this._addMessage([icu]);
}
this._inIcu = true;
}
const cases = html.visitAll(this, icu.cases, context);
if (this._mode === _VisitorMode.Merge) {
icu = new html.Expansion(
icu.switchValue, icu.type, cases, icu.sourceSpan, icu.switchValueSourceSpan);
}
this._inIcu = wasInIcu;
return icu;
}
visitComment(comment: html.Comment, context: any): any {
const isOpening = _isOpeningComment(comment);
if (isOpening && this._isInTranslatableSection) {
this._reportError(comment, 'Could not start a block inside a translatable section');
return;
}
const isClosing = _isClosingComment(comment);
if (isClosing && !this._inI18nBlock) {
this._reportError(comment, 'Trying to close an unopened block');
return;
}
if (!this._inI18nNode && !this._inIcu) {
if (!this._inI18nBlock) {
if (isOpening) {
this._inI18nBlock = true;
this._blockStartDepth = this._depth;
this._blockChildren = [];
this._blockMeaningAndDesc = comment.value.replace(_I18N_COMMENT_PREFIX_REGEXP, '').trim();
this._openTranslatableSection(comment);
}
} else {
if (isClosing) {
if (this._depth == this._blockStartDepth) {
this._closeTranslatableSection(comment, this._blockChildren);
this._inI18nBlock = false;
const message = this._addMessage(this._blockChildren, this._blockMeaningAndDesc);
// merge attributes in sections
const nodes = this._translateMessage(comment, message);
return html.visitAll(this, nodes);
} else {
this._reportError(comment, 'I18N blocks should not cross element boundaries');
return;
}
}
}
}
}
visitText(text: html.Text, context: any): html.Text {
if (this._isInTranslatableSection) {
this._mayBeAddBlockChildren(text);
}
return text;
}
visitElement(el: html.Element, context: any): html.Element {
this._mayBeAddBlockChildren(el);
this._depth++;
const wasInI18nNode = this._inI18nNode;
const wasInImplicitNode = this._inImplicitNode;
let childNodes: html.Node[];
// Extract only top level nodes with the (implicit) "i18n" attribute if not in a block or an ICU
// message
const i18nAttr = _getI18nAttr(el);
const isImplicit = this._implicitTags.some((tag: string): boolean => el.name === tag) &&
!this._inIcu && !this._isInTranslatableSection;
const isTopLevelImplicit = !wasInImplicitNode && isImplicit;
this._inImplicitNode = this._inImplicitNode || isImplicit;
if (!this._isInTranslatableSection && !this._inIcu) {
if (i18nAttr) {
// explicit translation
this._inI18nNode = true;
const message = this._addMessage(el.children, i18nAttr.value);
childNodes = this._translateMessage(el, message);
} else if (isTopLevelImplicit) {
// implicit translation
this._inI18nNode = true;
const message = this._addMessage(el.children);
childNodes = this._translateMessage(el, message);
}
if (this._mode == _VisitorMode.Extract) {
const isTranslatable = i18nAttr || isTopLevelImplicit;
if (isTranslatable) {
this._openTranslatableSection(el);
}
html.visitAll(this, el.children);
if (isTranslatable) {
this._closeTranslatableSection(el, el.children);
}
}
if (this._mode === _VisitorMode.Merge && !i18nAttr && !isTopLevelImplicit) {
childNodes = [];
el.children.forEach(child => {
const visited = child.visit(this, context);
if (visited && !this._isInTranslatableSection) {
// Do not add the children from translatable sections (= i18n blocks here)
// They will be added when the section is close (i.e. on `<!-- /i18n -->`)
childNodes = childNodes.concat(visited);
}
});
}
} else {
if (i18nAttr || isTopLevelImplicit) {
this._reportError(
el, 'Could not mark an element as translatable inside a translatable section');
}
if (this._mode == _VisitorMode.Extract) {
// Descend into child nodes for extraction
html.visitAll(this, el.children);
}
if (this._mode == _VisitorMode.Merge) {
// Translate attributes in ICU messages
childNodes = [];
el.children.forEach(child => {
const visited = child.visit(this, context);
if (visited && !this._isInTranslatableSection) {
// Do not add the children from translatable sections (= i18n blocks here)
// They will be added when the section is close (i.e. on `<!-- /i18n -->`)
childNodes = childNodes.concat(visited);
}
});
}
}
this._visitAttributesOf(el);
this._depth--;
this._inI18nNode = wasInI18nNode;
this._inImplicitNode = wasInImplicitNode;
if (this._mode === _VisitorMode.Merge) {
// There are no childNodes in translatable sections - those nodes will be replace anyway
const translatedAttrs = this._translateAttributes(el);
return new html.Element(
el.name, translatedAttrs, childNodes, el.sourceSpan, el.startSourceSpan,
el.endSourceSpan);
}
}
visitAttribute(attribute: html.Attribute, context: any): any {
throw new Error('unreachable code');
}
private _init(mode: _VisitorMode, interpolationConfig: InterpolationConfig): void {
this._mode = mode;
this._inI18nBlock = false;
this._inI18nNode = false;
this._depth = 0;
this._inIcu = false;
this._msgCountAtSectionStart = void 0;
this._errors = [];
this._messages = [];
this._inImplicitNode = false;
this._createI18nMessage = createI18nMessageFactory(interpolationConfig);
}
// looks for translatable attributes
private _visitAttributesOf(el: html.Element): void {
const explicitAttrNameToValue: {[k: string]: string} = {};
const implicitAttrNames: string[] = this._implicitAttrs[el.name] || [];
el.attrs.filter(attr => attr.name.startsWith(_I18N_ATTR_PREFIX))
.forEach(
attr => explicitAttrNameToValue[attr.name.slice(_I18N_ATTR_PREFIX.length)] =
attr.value);
el.attrs.forEach(attr => {
if (attr.name in explicitAttrNameToValue) {
this._addMessage([attr], explicitAttrNameToValue[attr.name]);
} else if (implicitAttrNames.some(name => attr.name === name)) {
this._addMessage([attr]);
}
});
}
// add a translatable message
private _addMessage(ast: html.Node[], meaningAndDesc?: string): i18n.Message {
if (ast.length == 0 ||
ast.length == 1 && ast[0] instanceof html.Attribute && !(<html.Attribute>ast[0]).value) {
// Do not create empty messages
return;
}
const [meaning, description] = _splitMeaningAndDesc(meaningAndDesc);
const message = this._createI18nMessage(ast, meaning, description);
this._messages.push(message);
return message;
}
// Translates the given message given the `TranslationBundle`
// no-op when called in extraction mode (returns [])
private _translateMessage(el: html.Node, message: i18n.Message): html.Node[] {
if (message && this._mode === _VisitorMode.Merge) {
const id = digestMessage(message);
const nodes = this._translations.get(id);
if (nodes) {
return nodes;
}
this._reportError(el, `Translation unavailable for message id="${id}"`);
}
return [];
}
// translate the attributes of an element and remove i18n specific attributes
private _translateAttributes(el: html.Element): html.Attribute[] {
const attributes = el.attrs;
const i18nAttributeMeanings: {[name: string]: string} = {};
attributes.forEach(attr => {
if (attr.name.startsWith(_I18N_ATTR_PREFIX)) {
i18nAttributeMeanings[attr.name.slice(_I18N_ATTR_PREFIX.length)] =
_splitMeaningAndDesc(attr.value)[0];
}
});
const translatedAttributes: html.Attribute[] = [];
attributes.forEach((attr) => {
if (attr.name === _I18N_ATTR || attr.name.startsWith(_I18N_ATTR_PREFIX)) {
// strip i18n specific attributes
return;
}
if (attr.value && attr.value != '' && i18nAttributeMeanings.hasOwnProperty(attr.name)) {
const meaning = i18nAttributeMeanings[attr.name];
const message: i18n.Message = this._createI18nMessage([attr], meaning, '');
const id = digestMessage(message);
const nodes = this._translations.get(id);
if (nodes) {
if (nodes[0] instanceof html.Text) {
const value = (nodes[0] as html.Text).value;
translatedAttributes.push(new html.Attribute(attr.name, value, attr.sourceSpan));
} else {
this._reportError(
el, `Unexpected translation for attribute "${attr.name}" (id="${id}")`);
}
} else {
this._reportError(
el, `Translation unavailable for attribute "${attr.name}" (id="${id}")`);
}
} else {
translatedAttributes.push(attr);
}
});
return translatedAttributes;
}
/**
* Add the node as a child of the block when:
* - we are in a block,
* - we are not inside a ICU message (those are handled separately),
* - the node is a "direct child" of the block
*/
private _mayBeAddBlockChildren(node: html.Node): void {
if (this._inI18nBlock && !this._inIcu && this._depth == this._blockStartDepth) {
this._blockChildren.push(node);
}
}
/**
* Marks the start of a section, see `_endSection`
*/
private _openTranslatableSection(node: html.Node): void {
if (this._isInTranslatableSection) {
this._reportError(node, 'Unexpected section start');
} else {
this._msgCountAtSectionStart = this._messages.length;
}
}
/**
* A translatable section could be:
* - a translatable element,
* - nodes between `<!-- i18n -->` and `<!-- /i18n -->` comments
*/
private get _isInTranslatableSection(): boolean {
return this._msgCountAtSectionStart !== void 0;
}
/**
* Terminates a section.
*
* If a section has only one significant children (comments not significant) then we should not
* keep the message from this children:
*
* `<p i18n="meaning|description">{ICU message}</p>` would produce two messages:
* - one for the <p> content with meaning and description,
* - another one for the ICU message.
*
* In this case the last message is discarded as it contains less information (the AST is
* otherwise identical).
*
* Note that we should still keep messages extracted from attributes inside the section (ie in the
* ICU message here)
*/
private _closeTranslatableSection(node: html.Node, directChildren: html.Node[]): void {
if (!this._isInTranslatableSection) {
this._reportError(node, 'Unexpected section end');
return;
}
const startIndex = this._msgCountAtSectionStart;
const significantChildren: number = directChildren.reduce(
(count: number, node: html.Node): number => count + (node instanceof html.Comment ? 0 : 1),
0);
if (significantChildren == 1) {
for (let i = this._messages.length - 1; i >= startIndex; i--) {
const ast = this._messages[i].nodes;
if (!(ast.length == 1 && ast[0] instanceof i18n.Text)) {
this._messages.splice(i, 1);
break;
}
}
}
this._msgCountAtSectionStart = void 0;
}
private _reportError(node: html.Node, msg: string): void {
this._errors.push(new I18nError(node.sourceSpan, msg));
}
}
function _isOpeningComment(n: html.Node): boolean {
return n instanceof html.Comment && n.value && n.value.startsWith('i18n');
}
function _isClosingComment(n: html.Node): boolean {
return n instanceof html.Comment && n.value && n.value === '/i18n';
}
function _getI18nAttr(p: html.Element): html.Attribute {
return p.attrs.find(attr => attr.name === _I18N_ATTR) || null;
}
function _splitMeaningAndDesc(i18n: string): [string, string] {
if (!i18n) return ['', ''];
const pipeIndex = i18n.indexOf('|');
return pipeIndex == -1 ? ['', i18n] : [i18n.slice(0, pipeIndex), i18n.slice(pipeIndex + 1)];
}
| modules/@angular/compiler/src/i18n/extractor_merger.ts | 1 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.9942660927772522,
0.03864646330475807,
0.00016313506057485938,
0.0003013854438904673,
0.18371164798736572
] |
{
"id": 2,
"code_window": [
" */\n",
" merge(\n",
" nodes: html.Node[], translations: TranslationBundle,\n",
" interpolationConfig: InterpolationConfig): html.Node[] {\n",
" this._init(_VisitorMode.Merge, interpolationConfig);\n",
" this._translations = translations;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" interpolationConfig: InterpolationConfig): ParseTreeResult {\n"
],
"file_path": "modules/@angular/compiler/src/i18n/extractor_merger.ts",
"type": "replace",
"edit_start_line_idx": 104
} | <!doctype html>
<html>
<title>Todo Angular 2 - WebWorker</title>
<link rel="stylesheet" href="css/main.css" media="screen" title="no title" charset="utf-8">
<body>
<todo-app>
Loading...
</todo-app>
<script src="../../bootstrap.js"></script>
</body>
</html>
| modules/playground/src/web_workers/todo/index.html | 0 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.00016858345770742744,
0.00016756856348365545,
0.00016655365470796824,
0.00016756856348365545,
0.0000010149014997296035
] |
{
"id": 2,
"code_window": [
" */\n",
" merge(\n",
" nodes: html.Node[], translations: TranslationBundle,\n",
" interpolationConfig: InterpolationConfig): html.Node[] {\n",
" this._init(_VisitorMode.Merge, interpolationConfig);\n",
" this._translations = translations;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" interpolationConfig: InterpolationConfig): ParseTreeResult {\n"
],
"file_path": "modules/@angular/compiler/src/i18n/extractor_merger.ts",
"type": "replace",
"edit_start_line_idx": 104
} | {
"compilerOptions": {
"baseUrl": ".",
"declaration": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"module": "commonjs",
"moduleResolution": "node",
"outDir": "../dist/tools/",
"noImplicitAny": true,
"noFallthroughCasesInSwitch": true,
"paths": {
},
"rootDir": ".",
"sourceMap": true,
"inlineSources": true,
"lib": ["es6", "dom"],
"target": "es5"
},
"exclude": [
"node_modules",
"typings-test",
"public_api_guard"
]
}
| tools/tsconfig.json | 0 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.00017313026182819158,
0.0001727573835523799,
0.00017243882757611573,
0.00017270307580474764,
2.848774443009461e-7
] |
{
"id": 2,
"code_window": [
" */\n",
" merge(\n",
" nodes: html.Node[], translations: TranslationBundle,\n",
" interpolationConfig: InterpolationConfig): html.Node[] {\n",
" this._init(_VisitorMode.Merge, interpolationConfig);\n",
" this._translations = translations;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" interpolationConfig: InterpolationConfig): ParseTreeResult {\n"
],
"file_path": "modules/@angular/compiler/src/i18n/extractor_merger.ts",
"type": "replace",
"edit_start_line_idx": 104
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {verifyNoBrowserErrors} from 'e2e_util/e2e_util';
describe('SVG', function() {
var URL = 'all/playground/src/svg/index.html';
afterEach(verifyNoBrowserErrors);
beforeEach(() => { browser.get(URL); });
it('should display SVG component contents', function() {
var svgText = element.all(by.css('g text')).get(0);
expect(svgText.getText()).toEqual('Hello');
});
});
| modules/playground/e2e_test/svg/svg_spec.ts | 0 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.00017751970153767616,
0.00017504651623312384,
0.00017329808906652033,
0.00017432178719900548,
0.0000017980429447561619
] |
{
"id": 3,
"code_window": [
" const wrapper = new html.Element('wrapper', [], nodes, null, null, null);\n",
"\n",
" const translatedNode = wrapper.visit(this, null);\n",
"\n",
" // TODO(vicb): return MergeResult with errors\n",
" if (this._inI18nBlock) {\n",
" this._reportError(nodes[nodes.length - 1], 'Unclosed block');\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "modules/@angular/compiler/src/i18n/extractor_merger.ts",
"type": "replace",
"edit_start_line_idx": 113
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {HtmlParser as BaseHtmlParser} from '../ml_parser/html_parser';
import {DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig} from '../ml_parser/interpolation_config';
import {ParseTreeResult} from '../ml_parser/parser';
import {mergeTranslations} from './extractor_merger';
import {MessageBundle} from './message_bundle';
import {Xtb} from './serializers/xtb';
import {TranslationBundle} from './translation_bundle';
export class HtmlParser implements BaseHtmlParser {
// @override
public getTagDefinition: any;
// TODO(vicb): transB.load() should not need a msgB & add transB.resolve(msgB,
// interpolationConfig)
// TODO(vicb): remove the interpolationConfig from the Xtb serializer
constructor(private _htmlParser: BaseHtmlParser, private _translations?: string) {}
parse(
source: string, url: string, parseExpansionForms: boolean = false,
interpolationConfig: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG): ParseTreeResult {
const parseResult =
this._htmlParser.parse(source, url, parseExpansionForms, interpolationConfig);
if (!this._translations || this._translations === '') {
// Do not enable i18n when no translation bundle is provided
return parseResult;
}
// TODO(vicb): add support for implicit tags / attributes
const messageBundle = new MessageBundle(this._htmlParser, [], {});
const errors = messageBundle.updateFromTemplate(source, url, interpolationConfig);
if (errors && errors.length) {
return new ParseTreeResult(parseResult.rootNodes, parseResult.errors.concat(errors));
}
const xtb = new Xtb(this._htmlParser, interpolationConfig);
const translationBundle = TranslationBundle.load(this._translations, url, messageBundle, xtb);
const translatedNodes =
mergeTranslations(parseResult.rootNodes, translationBundle, interpolationConfig, [], {});
return new ParseTreeResult(translatedNodes, []);
}
} | modules/@angular/compiler/src/i18n/html_parser.ts | 1 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.015836574137210846,
0.005734235048294067,
0.0001683208392933011,
0.003040072973817587,
0.006171032320708036
] |
{
"id": 3,
"code_window": [
" const wrapper = new html.Element('wrapper', [], nodes, null, null, null);\n",
"\n",
" const translatedNode = wrapper.visit(this, null);\n",
"\n",
" // TODO(vicb): return MergeResult with errors\n",
" if (this._inI18nBlock) {\n",
" this._reportError(nodes[nodes.length - 1], 'Unclosed block');\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "modules/@angular/compiler/src/i18n/extractor_merger.ts",
"type": "replace",
"edit_start_line_idx": 113
} | import {Component} from '@angular/core';
import {bootstrap} from '@angular/platform-browser';
@Component({
selector: 'hello-app',
template: `
<h1>Hello, {{name}}!</h1>
<label> Say hello to: <input [value]="name" (input)="name = $event.target.value"></label>
`
})
export class HelloCmp {
name = 'World';
}
bootstrap(HelloCmp);
| modules/payload_tests/hello_world/ts/webpack/index.ts | 0 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.00017479831876698881,
0.00017007255519274622,
0.00016534679161850363,
0.00017007255519274622,
0.000004725763574242592
] |
{
"id": 3,
"code_window": [
" const wrapper = new html.Element('wrapper', [], nodes, null, null, null);\n",
"\n",
" const translatedNode = wrapper.visit(this, null);\n",
"\n",
" // TODO(vicb): return MergeResult with errors\n",
" if (this._inI18nBlock) {\n",
" this._reportError(nodes[nodes.length - 1], 'Unclosed block');\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "modules/@angular/compiler/src/i18n/extractor_merger.ts",
"type": "replace",
"edit_start_line_idx": 113
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Public Test Library for unit testing Angular2 Applications. Assumes that you are running
* with Jasmine, Mocha, or a similar framework which exports a beforeEach function and
* allows tests to be asynchronous by either returning a promise or using a 'done' parameter.
*/
import {SchemaMetadata} from '../index';
import {resetFakeAsyncZone} from './fake_async';
import {TestBed, TestModuleMetadata, getTestBed} from './test_bed';
declare var global: any;
var _global = <any>(typeof window === 'undefined' ? global : window);
// Reset the test providers and the fake async zone before each test.
if (_global.beforeEach) {
_global.beforeEach(() => {
TestBed.resetTestingModule();
resetFakeAsyncZone();
});
}
/**
* Allows overriding default providers of the test injector,
* which are defined in test_injector.js
*
* @deprecated Use `TestBed.configureTestingModule instead.
*/
export function addProviders(providers: Array<any>): void {
if (!providers) return;
TestBed.configureTestingModule({providers: providers});
}
| modules/@angular/core/testing/testing.ts | 0 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.000177428315510042,
0.00017465880955569446,
0.00016983432578854263,
0.00017622530867811292,
0.0000028757335712725762
] |
{
"id": 3,
"code_window": [
" const wrapper = new html.Element('wrapper', [], nodes, null, null, null);\n",
"\n",
" const translatedNode = wrapper.visit(this, null);\n",
"\n",
" // TODO(vicb): return MergeResult with errors\n",
" if (this._inI18nBlock) {\n",
" this._reportError(nodes[nodes.length - 1], 'Unclosed block');\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "modules/@angular/compiler/src/i18n/extractor_merger.ts",
"type": "replace",
"edit_start_line_idx": 113
} | export declare class MockDirectiveResolver extends DirectiveResolver {
constructor(_injector: Injector);
resolve(type: Type): DirectiveMetadata;
setProvidersOverride(type: Type, providers: any[]): void;
setViewProvidersOverride(type: Type, viewProviders: any[]): void;
}
export declare class MockSchemaRegistry implements ElementSchemaRegistry {
attrPropMapping: {
[key: string]: string;
};
existingProperties: {
[key: string]: boolean;
};
constructor(existingProperties: {
[key: string]: boolean;
}, attrPropMapping: {
[key: string]: string;
});
getMappedPropName(attrName: string): string;
hasProperty(tagName: string, property: string): boolean;
securityContext(tagName: string, property: string): SecurityContext;
}
export declare class MockViewResolver extends ViewResolver {
constructor(_injector: Injector);
overrideViewDirective(component: Type, from: Type, to: Type): void;
resolve(component: Type): ViewMetadata;
setAnimations(component: Type, animations: AnimationEntryMetadata[]): void;
setInlineTemplate(component: Type, template: string): void;
setView(component: Type, view: ViewMetadata): void;
}
export declare class OverridingTestComponentBuilder extends TestComponentBuilder {
constructor(injector: Injector);
createAsync<T>(rootComponentType: ConcreteType<T>): Promise<ComponentFixture<T>>;
createSync<T>(rootComponentType: ConcreteType<T>): ComponentFixture<T>;
overrideAnimations(componentType: Type, animations: AnimationEntryMetadata[]): TestComponentBuilder;
overrideDirective(componentType: Type, from: Type, to: Type): OverridingTestComponentBuilder;
overrideProviders(type: Type, providers: any[]): OverridingTestComponentBuilder;
overrideTemplate(componentType: Type, template: string): OverridingTestComponentBuilder;
overrideView(componentType: Type, view: ViewMetadata): OverridingTestComponentBuilder;
overrideViewProviders(type: Type, providers: any[]): OverridingTestComponentBuilder;
}
| tools/public_api_guard/compiler/testing.d.ts | 0 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.0001785404165275395,
0.00017369663692079484,
0.00017101081903092563,
0.000172698637470603,
0.000002626613650136278
] |
{
"id": 4,
"code_window": [
" if (this._inI18nBlock) {\n",
" this._reportError(nodes[nodes.length - 1], 'Unclosed block');\n",
" }\n",
"\n",
" return translatedNode.children;\n",
" }\n",
"\n",
" visitExpansionCase(icuCase: html.ExpansionCase, context: any): any {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return new ParseTreeResult(translatedNode.children, this._errors);\n"
],
"file_path": "modules/@angular/compiler/src/i18n/extractor_merger.ts",
"type": "replace",
"edit_start_line_idx": 118
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as html from '../ml_parser/ast';
import {InterpolationConfig} from '../ml_parser/interpolation_config';
import {digestMessage} from './digest';
import * as i18n from './i18n_ast';
import {createI18nMessageFactory} from './i18n_parser';
import {I18nError} from './parse_util';
import {TranslationBundle} from './translation_bundle';
const _I18N_ATTR = 'i18n';
const _I18N_ATTR_PREFIX = 'i18n-';
const _I18N_COMMENT_PREFIX_REGEXP = /^i18n:?/;
/**
* Extract translatable messages from an html AST
*/
export function extractMessages(
nodes: html.Node[], interpolationConfig: InterpolationConfig, implicitTags: string[],
implicitAttrs: {[k: string]: string[]}): ExtractionResult {
const visitor = new _Visitor(implicitTags, implicitAttrs);
return visitor.extract(nodes, interpolationConfig);
}
export function mergeTranslations(
nodes: html.Node[], translations: TranslationBundle, interpolationConfig: InterpolationConfig,
implicitTags: string[], implicitAttrs: {[k: string]: string[]}): html.Node[] {
const visitor = new _Visitor(implicitTags, implicitAttrs);
return visitor.merge(nodes, translations, interpolationConfig);
}
export class ExtractionResult {
constructor(public messages: i18n.Message[], public errors: I18nError[]) {}
}
enum _VisitorMode {
Extract,
Merge
}
/**
* This Visitor is used:
* 1. to extract all the translatable strings from an html AST (see `extract()`),
* 2. to replace the translatable strings with the actual translations (see `merge()`)
*
* @internal
*/
class _Visitor implements html.Visitor {
// <el i18n>...</el>
private _inI18nNode: boolean;
private _depth: number;
private _inImplicitNode: boolean;
// <!--i18n-->...<!--/i18n-->
private _blockMeaningAndDesc: string;
private _blockChildren: html.Node[];
private _blockStartDepth: number;
private _inI18nBlock: boolean;
// {<icu message>}
private _inIcu: boolean;
private _msgCountAtSectionStart: number;
private _errors: I18nError[];
private _mode: _VisitorMode;
// _VisitorMode.Extract only
private _messages: i18n.Message[];
// _VisitorMode.Merge only
private _translations: TranslationBundle;
private _createI18nMessage:
(msg: html.Node[], meaning: string, description: string) => i18n.Message;
constructor(private _implicitTags: string[], private _implicitAttrs: {[k: string]: string[]}) {}
/**
* Extracts the messages from the tree
*/
extract(nodes: html.Node[], interpolationConfig: InterpolationConfig): ExtractionResult {
this._init(_VisitorMode.Extract, interpolationConfig);
nodes.forEach(node => node.visit(this, null));
if (this._inI18nBlock) {
this._reportError(nodes[nodes.length - 1], 'Unclosed block');
}
return new ExtractionResult(this._messages, this._errors);
}
/**
* Returns a tree where all translatable nodes are translated
*/
merge(
nodes: html.Node[], translations: TranslationBundle,
interpolationConfig: InterpolationConfig): html.Node[] {
this._init(_VisitorMode.Merge, interpolationConfig);
this._translations = translations;
// Construct a single fake root element
const wrapper = new html.Element('wrapper', [], nodes, null, null, null);
const translatedNode = wrapper.visit(this, null);
// TODO(vicb): return MergeResult with errors
if (this._inI18nBlock) {
this._reportError(nodes[nodes.length - 1], 'Unclosed block');
}
return translatedNode.children;
}
visitExpansionCase(icuCase: html.ExpansionCase, context: any): any {
// Parse cases for translatable html attributes
const expression = html.visitAll(this, icuCase.expression, context);
if (this._mode === _VisitorMode.Merge) {
return new html.ExpansionCase(
icuCase.value, expression, icuCase.sourceSpan, icuCase.valueSourceSpan,
icuCase.expSourceSpan);
}
}
visitExpansion(icu: html.Expansion, context: any): html.Expansion {
this._mayBeAddBlockChildren(icu);
const wasInIcu = this._inIcu;
if (!this._inIcu) {
// nested ICU messages should not be extracted but top-level translated as a whole
if (this._isInTranslatableSection) {
this._addMessage([icu]);
}
this._inIcu = true;
}
const cases = html.visitAll(this, icu.cases, context);
if (this._mode === _VisitorMode.Merge) {
icu = new html.Expansion(
icu.switchValue, icu.type, cases, icu.sourceSpan, icu.switchValueSourceSpan);
}
this._inIcu = wasInIcu;
return icu;
}
visitComment(comment: html.Comment, context: any): any {
const isOpening = _isOpeningComment(comment);
if (isOpening && this._isInTranslatableSection) {
this._reportError(comment, 'Could not start a block inside a translatable section');
return;
}
const isClosing = _isClosingComment(comment);
if (isClosing && !this._inI18nBlock) {
this._reportError(comment, 'Trying to close an unopened block');
return;
}
if (!this._inI18nNode && !this._inIcu) {
if (!this._inI18nBlock) {
if (isOpening) {
this._inI18nBlock = true;
this._blockStartDepth = this._depth;
this._blockChildren = [];
this._blockMeaningAndDesc = comment.value.replace(_I18N_COMMENT_PREFIX_REGEXP, '').trim();
this._openTranslatableSection(comment);
}
} else {
if (isClosing) {
if (this._depth == this._blockStartDepth) {
this._closeTranslatableSection(comment, this._blockChildren);
this._inI18nBlock = false;
const message = this._addMessage(this._blockChildren, this._blockMeaningAndDesc);
// merge attributes in sections
const nodes = this._translateMessage(comment, message);
return html.visitAll(this, nodes);
} else {
this._reportError(comment, 'I18N blocks should not cross element boundaries');
return;
}
}
}
}
}
visitText(text: html.Text, context: any): html.Text {
if (this._isInTranslatableSection) {
this._mayBeAddBlockChildren(text);
}
return text;
}
visitElement(el: html.Element, context: any): html.Element {
this._mayBeAddBlockChildren(el);
this._depth++;
const wasInI18nNode = this._inI18nNode;
const wasInImplicitNode = this._inImplicitNode;
let childNodes: html.Node[];
// Extract only top level nodes with the (implicit) "i18n" attribute if not in a block or an ICU
// message
const i18nAttr = _getI18nAttr(el);
const isImplicit = this._implicitTags.some((tag: string): boolean => el.name === tag) &&
!this._inIcu && !this._isInTranslatableSection;
const isTopLevelImplicit = !wasInImplicitNode && isImplicit;
this._inImplicitNode = this._inImplicitNode || isImplicit;
if (!this._isInTranslatableSection && !this._inIcu) {
if (i18nAttr) {
// explicit translation
this._inI18nNode = true;
const message = this._addMessage(el.children, i18nAttr.value);
childNodes = this._translateMessage(el, message);
} else if (isTopLevelImplicit) {
// implicit translation
this._inI18nNode = true;
const message = this._addMessage(el.children);
childNodes = this._translateMessage(el, message);
}
if (this._mode == _VisitorMode.Extract) {
const isTranslatable = i18nAttr || isTopLevelImplicit;
if (isTranslatable) {
this._openTranslatableSection(el);
}
html.visitAll(this, el.children);
if (isTranslatable) {
this._closeTranslatableSection(el, el.children);
}
}
if (this._mode === _VisitorMode.Merge && !i18nAttr && !isTopLevelImplicit) {
childNodes = [];
el.children.forEach(child => {
const visited = child.visit(this, context);
if (visited && !this._isInTranslatableSection) {
// Do not add the children from translatable sections (= i18n blocks here)
// They will be added when the section is close (i.e. on `<!-- /i18n -->`)
childNodes = childNodes.concat(visited);
}
});
}
} else {
if (i18nAttr || isTopLevelImplicit) {
this._reportError(
el, 'Could not mark an element as translatable inside a translatable section');
}
if (this._mode == _VisitorMode.Extract) {
// Descend into child nodes for extraction
html.visitAll(this, el.children);
}
if (this._mode == _VisitorMode.Merge) {
// Translate attributes in ICU messages
childNodes = [];
el.children.forEach(child => {
const visited = child.visit(this, context);
if (visited && !this._isInTranslatableSection) {
// Do not add the children from translatable sections (= i18n blocks here)
// They will be added when the section is close (i.e. on `<!-- /i18n -->`)
childNodes = childNodes.concat(visited);
}
});
}
}
this._visitAttributesOf(el);
this._depth--;
this._inI18nNode = wasInI18nNode;
this._inImplicitNode = wasInImplicitNode;
if (this._mode === _VisitorMode.Merge) {
// There are no childNodes in translatable sections - those nodes will be replace anyway
const translatedAttrs = this._translateAttributes(el);
return new html.Element(
el.name, translatedAttrs, childNodes, el.sourceSpan, el.startSourceSpan,
el.endSourceSpan);
}
}
visitAttribute(attribute: html.Attribute, context: any): any {
throw new Error('unreachable code');
}
private _init(mode: _VisitorMode, interpolationConfig: InterpolationConfig): void {
this._mode = mode;
this._inI18nBlock = false;
this._inI18nNode = false;
this._depth = 0;
this._inIcu = false;
this._msgCountAtSectionStart = void 0;
this._errors = [];
this._messages = [];
this._inImplicitNode = false;
this._createI18nMessage = createI18nMessageFactory(interpolationConfig);
}
// looks for translatable attributes
private _visitAttributesOf(el: html.Element): void {
const explicitAttrNameToValue: {[k: string]: string} = {};
const implicitAttrNames: string[] = this._implicitAttrs[el.name] || [];
el.attrs.filter(attr => attr.name.startsWith(_I18N_ATTR_PREFIX))
.forEach(
attr => explicitAttrNameToValue[attr.name.slice(_I18N_ATTR_PREFIX.length)] =
attr.value);
el.attrs.forEach(attr => {
if (attr.name in explicitAttrNameToValue) {
this._addMessage([attr], explicitAttrNameToValue[attr.name]);
} else if (implicitAttrNames.some(name => attr.name === name)) {
this._addMessage([attr]);
}
});
}
// add a translatable message
private _addMessage(ast: html.Node[], meaningAndDesc?: string): i18n.Message {
if (ast.length == 0 ||
ast.length == 1 && ast[0] instanceof html.Attribute && !(<html.Attribute>ast[0]).value) {
// Do not create empty messages
return;
}
const [meaning, description] = _splitMeaningAndDesc(meaningAndDesc);
const message = this._createI18nMessage(ast, meaning, description);
this._messages.push(message);
return message;
}
// Translates the given message given the `TranslationBundle`
// no-op when called in extraction mode (returns [])
private _translateMessage(el: html.Node, message: i18n.Message): html.Node[] {
if (message && this._mode === _VisitorMode.Merge) {
const id = digestMessage(message);
const nodes = this._translations.get(id);
if (nodes) {
return nodes;
}
this._reportError(el, `Translation unavailable for message id="${id}"`);
}
return [];
}
// translate the attributes of an element and remove i18n specific attributes
private _translateAttributes(el: html.Element): html.Attribute[] {
const attributes = el.attrs;
const i18nAttributeMeanings: {[name: string]: string} = {};
attributes.forEach(attr => {
if (attr.name.startsWith(_I18N_ATTR_PREFIX)) {
i18nAttributeMeanings[attr.name.slice(_I18N_ATTR_PREFIX.length)] =
_splitMeaningAndDesc(attr.value)[0];
}
});
const translatedAttributes: html.Attribute[] = [];
attributes.forEach((attr) => {
if (attr.name === _I18N_ATTR || attr.name.startsWith(_I18N_ATTR_PREFIX)) {
// strip i18n specific attributes
return;
}
if (attr.value && attr.value != '' && i18nAttributeMeanings.hasOwnProperty(attr.name)) {
const meaning = i18nAttributeMeanings[attr.name];
const message: i18n.Message = this._createI18nMessage([attr], meaning, '');
const id = digestMessage(message);
const nodes = this._translations.get(id);
if (nodes) {
if (nodes[0] instanceof html.Text) {
const value = (nodes[0] as html.Text).value;
translatedAttributes.push(new html.Attribute(attr.name, value, attr.sourceSpan));
} else {
this._reportError(
el, `Unexpected translation for attribute "${attr.name}" (id="${id}")`);
}
} else {
this._reportError(
el, `Translation unavailable for attribute "${attr.name}" (id="${id}")`);
}
} else {
translatedAttributes.push(attr);
}
});
return translatedAttributes;
}
/**
* Add the node as a child of the block when:
* - we are in a block,
* - we are not inside a ICU message (those are handled separately),
* - the node is a "direct child" of the block
*/
private _mayBeAddBlockChildren(node: html.Node): void {
if (this._inI18nBlock && !this._inIcu && this._depth == this._blockStartDepth) {
this._blockChildren.push(node);
}
}
/**
* Marks the start of a section, see `_endSection`
*/
private _openTranslatableSection(node: html.Node): void {
if (this._isInTranslatableSection) {
this._reportError(node, 'Unexpected section start');
} else {
this._msgCountAtSectionStart = this._messages.length;
}
}
/**
* A translatable section could be:
* - a translatable element,
* - nodes between `<!-- i18n -->` and `<!-- /i18n -->` comments
*/
private get _isInTranslatableSection(): boolean {
return this._msgCountAtSectionStart !== void 0;
}
/**
* Terminates a section.
*
* If a section has only one significant children (comments not significant) then we should not
* keep the message from this children:
*
* `<p i18n="meaning|description">{ICU message}</p>` would produce two messages:
* - one for the <p> content with meaning and description,
* - another one for the ICU message.
*
* In this case the last message is discarded as it contains less information (the AST is
* otherwise identical).
*
* Note that we should still keep messages extracted from attributes inside the section (ie in the
* ICU message here)
*/
private _closeTranslatableSection(node: html.Node, directChildren: html.Node[]): void {
if (!this._isInTranslatableSection) {
this._reportError(node, 'Unexpected section end');
return;
}
const startIndex = this._msgCountAtSectionStart;
const significantChildren: number = directChildren.reduce(
(count: number, node: html.Node): number => count + (node instanceof html.Comment ? 0 : 1),
0);
if (significantChildren == 1) {
for (let i = this._messages.length - 1; i >= startIndex; i--) {
const ast = this._messages[i].nodes;
if (!(ast.length == 1 && ast[0] instanceof i18n.Text)) {
this._messages.splice(i, 1);
break;
}
}
}
this._msgCountAtSectionStart = void 0;
}
private _reportError(node: html.Node, msg: string): void {
this._errors.push(new I18nError(node.sourceSpan, msg));
}
}
function _isOpeningComment(n: html.Node): boolean {
return n instanceof html.Comment && n.value && n.value.startsWith('i18n');
}
function _isClosingComment(n: html.Node): boolean {
return n instanceof html.Comment && n.value && n.value === '/i18n';
}
function _getI18nAttr(p: html.Element): html.Attribute {
return p.attrs.find(attr => attr.name === _I18N_ATTR) || null;
}
function _splitMeaningAndDesc(i18n: string): [string, string] {
if (!i18n) return ['', ''];
const pipeIndex = i18n.indexOf('|');
return pipeIndex == -1 ? ['', i18n] : [i18n.slice(0, pipeIndex), i18n.slice(pipeIndex + 1)];
}
| modules/@angular/compiler/src/i18n/extractor_merger.ts | 1 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.9941996335983276,
0.08113884180784225,
0.00016554917965549976,
0.004102082923054695,
0.2240619659423828
] |
{
"id": 4,
"code_window": [
" if (this._inI18nBlock) {\n",
" this._reportError(nodes[nodes.length - 1], 'Unclosed block');\n",
" }\n",
"\n",
" return translatedNode.children;\n",
" }\n",
"\n",
" visitExpansionCase(icuCase: html.ExpansionCase, context: any): any {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return new ParseTreeResult(translatedNode.children, this._errors);\n"
],
"file_path": "modules/@angular/compiler/src/i18n/extractor_merger.ts",
"type": "replace",
"edit_start_line_idx": 118
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injector, OpaqueToken} from '@angular/core/src/di';
import {BaseException, WrappedException} from '@angular/facade/src/exceptions';
import {isBlank, isPresent} from '@angular/facade/src/lang';
import {Options} from './common_options';
/**
* A WebDriverExtension implements extended commands of the webdriver protocol
* for a given browser, independent of the WebDriverAdapter.
* Needs one implementation for every supported Browser.
*/
export abstract class WebDriverExtension {
static bindTo(childTokens: any[]): any[] {
var res = [
{
provide: _CHILDREN,
useFactory: (injector: Injector) => childTokens.map(token => injector.get(token)),
deps: [Injector]
},
{
provide: WebDriverExtension,
useFactory: (children: WebDriverExtension[], capabilities) => {
var delegate;
children.forEach(extension => {
if (extension.supports(capabilities)) {
delegate = extension;
}
});
if (isBlank(delegate)) {
throw new BaseException('Could not find a delegate for given capabilities!');
}
return delegate;
},
deps: [_CHILDREN, Options.CAPABILITIES]
}
];
return res;
}
gc(): Promise<any> { throw new BaseException('NYI'); }
timeBegin(name: string): Promise<any> { throw new BaseException('NYI'); }
timeEnd(name: string, restartName: string): Promise<any> { throw new BaseException('NYI'); }
/**
* Format:
* - cat: category of the event
* - name: event name: 'script', 'gc', 'render', ...
* - ph: phase: 'B' (begin), 'E' (end), 'b' (nestable start), 'e' (nestable end), 'X' (Complete
*event)
* - ts: timestamp in ms, e.g. 12345
* - pid: process id
* - args: arguments, e.g. {heapSize: 1234}
*
* Based on [Chrome Trace Event
*Format](https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/edit)
**/
readPerfLog(): Promise<any[]> { throw new BaseException('NYI'); }
perfLogFeatures(): PerfLogFeatures { throw new BaseException('NYI'); }
supports(capabilities: {[key: string]: any}): boolean { return true; }
}
export class PerfLogFeatures {
render: boolean;
gc: boolean;
frameCapture: boolean;
userTiming: boolean;
constructor(
{render = false, gc = false, frameCapture = false, userTiming = false}:
{render?: boolean, gc?: boolean, frameCapture?: boolean, userTiming?: boolean} = {}) {
this.render = render;
this.gc = gc;
this.frameCapture = frameCapture;
this.userTiming = userTiming;
}
}
var _CHILDREN = new OpaqueToken('WebDriverExtension.children');
| modules/benchpress/src/web_driver_extension.ts | 0 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.00019012198026757687,
0.0001708056515781209,
0.00016272383800242096,
0.00016677487292326987,
0.000007969913895067293
] |
{
"id": 4,
"code_window": [
" if (this._inI18nBlock) {\n",
" this._reportError(nodes[nodes.length - 1], 'Unclosed block');\n",
" }\n",
"\n",
" return translatedNode.children;\n",
" }\n",
"\n",
" visitExpansionCase(icuCase: html.ExpansionCase, context: any): any {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return new ParseTreeResult(translatedNode.children, this._errors);\n"
],
"file_path": "modules/@angular/compiler/src/i18n/extractor_merger.ts",
"type": "replace",
"edit_start_line_idx": 118
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @module
* @description
* Common directives shipped with Angular.
*/
export {CORE_DIRECTIVES} from './directives/core_directives';
export {NgClass} from './directives/ng_class';
export {NgFor} from './directives/ng_for';
export {NgIf} from './directives/ng_if';
export {NgPlural, NgPluralCase} from './directives/ng_plural';
export {NgStyle} from './directives/ng_style';
export {NgSwitch, NgSwitchCase, NgSwitchDefault} from './directives/ng_switch';
export {NgTemplateOutlet} from './directives/ng_template_outlet';
| modules/@angular/common/src/directives.ts | 0 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.00017728643433656543,
0.00017488420417066664,
0.00017242977628484368,
0.00017493638733867556,
0.0000019830658857245
] |
{
"id": 4,
"code_window": [
" if (this._inI18nBlock) {\n",
" this._reportError(nodes[nodes.length - 1], 'Unclosed block');\n",
" }\n",
"\n",
" return translatedNode.children;\n",
" }\n",
"\n",
" visitExpansionCase(icuCase: html.ExpansionCase, context: any): any {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return new ParseTreeResult(translatedNode.children, this._errors);\n"
],
"file_path": "modules/@angular/compiler/src/i18n/extractor_merger.ts",
"type": "replace",
"edit_start_line_idx": 118
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {OptionalMetadata, Provider, SkipSelfMetadata} from '../../di';
import {ListWrapper} from '../../facade/collection';
import {BaseException} from '../../facade/exceptions';
import {isBlank, isPresent} from '../../facade/lang';
import {ChangeDetectorRef} from '../change_detector_ref';
/**
* A differ that tracks changes made to an object over time.
*
* @stable
*/
export interface KeyValueDiffer {
diff(object: any): any /** TODO #9100 */;
onDestroy(): any /** TODO #9100 */;
}
/**
* Provides a factory for {@link KeyValueDiffer}.
*
* @stable
*/
export interface KeyValueDifferFactory {
supports(objects: any): boolean;
create(cdRef: ChangeDetectorRef): KeyValueDiffer;
}
/**
* A repository of different Map diffing strategies used by NgClass, NgStyle, and others.
* @stable
*/
export class KeyValueDiffers {
constructor(public factories: KeyValueDifferFactory[]) {}
static create(factories: KeyValueDifferFactory[], parent?: KeyValueDiffers): KeyValueDiffers {
if (isPresent(parent)) {
var copied = ListWrapper.clone(parent.factories);
factories = factories.concat(copied);
return new KeyValueDiffers(factories);
} else {
return new KeyValueDiffers(factories);
}
}
/**
* Takes an array of {@link KeyValueDifferFactory} and returns a provider used to extend the
* inherited {@link KeyValueDiffers} instance with the provided factories and return a new
* {@link KeyValueDiffers} instance.
*
* The following example shows how to extend an existing list of factories,
* which will only be applied to the injector for this component and its children.
* This step is all that's required to make a new {@link KeyValueDiffer} available.
*
* ### Example
*
* ```
* @Component({
* viewProviders: [
* KeyValueDiffers.extend([new ImmutableMapDiffer()])
* ]
* })
* ```
*/
static extend(factories: KeyValueDifferFactory[]): Provider {
return new Provider(KeyValueDiffers, {
useFactory: (parent: KeyValueDiffers) => {
if (isBlank(parent)) {
// Typically would occur when calling KeyValueDiffers.extend inside of dependencies passed
// to
// bootstrap(), which would override default pipes instead of extending them.
throw new BaseException('Cannot extend KeyValueDiffers without a parent injector');
}
return KeyValueDiffers.create(factories, parent);
},
// Dependency technically isn't optional, but we can provide a better error message this way.
deps: [[KeyValueDiffers, new SkipSelfMetadata(), new OptionalMetadata()]]
});
}
find(kv: Object): KeyValueDifferFactory {
var factory = this.factories.find(f => f.supports(kv));
if (isPresent(factory)) {
return factory;
} else {
throw new BaseException(`Cannot find a differ supporting object '${kv}'`);
}
}
}
| modules/@angular/core/src/change_detection/differs/keyvalue_differs.ts | 0 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.0003667515702545643,
0.00019725221500266343,
0.00016381312161684036,
0.00017344485968351364,
0.000059798472648253664
] |
{
"id": 5,
"code_window": [
" const xtb = new Xtb(this._htmlParser, interpolationConfig);\n",
" const translationBundle = TranslationBundle.load(this._translations, url, messageBundle, xtb);\n",
"\n",
" const translatedNodes =\n",
" mergeTranslations(parseResult.rootNodes, translationBundle, interpolationConfig, [], {});\n",
"\n",
" return new ParseTreeResult(translatedNodes, []);\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" return mergeTranslations(parseResult.rootNodes, translationBundle, interpolationConfig, [], {});\n"
],
"file_path": "modules/@angular/compiler/src/i18n/html_parser.ts",
"type": "replace",
"edit_start_line_idx": 48
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {HtmlParser as BaseHtmlParser} from '../ml_parser/html_parser';
import {DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig} from '../ml_parser/interpolation_config';
import {ParseTreeResult} from '../ml_parser/parser';
import {mergeTranslations} from './extractor_merger';
import {MessageBundle} from './message_bundle';
import {Xtb} from './serializers/xtb';
import {TranslationBundle} from './translation_bundle';
export class HtmlParser implements BaseHtmlParser {
// @override
public getTagDefinition: any;
// TODO(vicb): transB.load() should not need a msgB & add transB.resolve(msgB,
// interpolationConfig)
// TODO(vicb): remove the interpolationConfig from the Xtb serializer
constructor(private _htmlParser: BaseHtmlParser, private _translations?: string) {}
parse(
source: string, url: string, parseExpansionForms: boolean = false,
interpolationConfig: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG): ParseTreeResult {
const parseResult =
this._htmlParser.parse(source, url, parseExpansionForms, interpolationConfig);
if (!this._translations || this._translations === '') {
// Do not enable i18n when no translation bundle is provided
return parseResult;
}
// TODO(vicb): add support for implicit tags / attributes
const messageBundle = new MessageBundle(this._htmlParser, [], {});
const errors = messageBundle.updateFromTemplate(source, url, interpolationConfig);
if (errors && errors.length) {
return new ParseTreeResult(parseResult.rootNodes, parseResult.errors.concat(errors));
}
const xtb = new Xtb(this._htmlParser, interpolationConfig);
const translationBundle = TranslationBundle.load(this._translations, url, messageBundle, xtb);
const translatedNodes =
mergeTranslations(parseResult.rootNodes, translationBundle, interpolationConfig, [], {});
return new ParseTreeResult(translatedNodes, []);
}
} | modules/@angular/compiler/src/i18n/html_parser.ts | 1 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.9985195994377136,
0.33400651812553406,
0.00017064808344002813,
0.0025365245528519154,
0.46970972418785095
] |
{
"id": 5,
"code_window": [
" const xtb = new Xtb(this._htmlParser, interpolationConfig);\n",
" const translationBundle = TranslationBundle.load(this._translations, url, messageBundle, xtb);\n",
"\n",
" const translatedNodes =\n",
" mergeTranslations(parseResult.rootNodes, translationBundle, interpolationConfig, [], {});\n",
"\n",
" return new ParseTreeResult(translatedNodes, []);\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" return mergeTranslations(parseResult.rootNodes, translationBundle, interpolationConfig, [], {});\n"
],
"file_path": "modules/@angular/compiler/src/i18n/html_parser.ts",
"type": "replace",
"edit_start_line_idx": 48
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {BaseException} from '@angular/core';
import {AbstractControlDirective} from './abstract_control_directive';
import {ControlValueAccessor} from './control_value_accessor';
import {AsyncValidatorFn, ValidatorFn} from './validators';
function unimplemented(): any {
throw new BaseException('unimplemented');
}
/**
* A base class that all control directive extend.
* It binds a {@link Control} object to a DOM element.
*
* Used internally by Angular forms.
*
* @experimental
*/
export abstract class NgControl extends AbstractControlDirective {
name: string = null;
valueAccessor: ControlValueAccessor = null;
get validator(): ValidatorFn { return <ValidatorFn>unimplemented(); }
get asyncValidator(): AsyncValidatorFn { return <AsyncValidatorFn>unimplemented(); }
abstract viewToModelUpdate(newValue: any): void;
}
| modules/@angular/forms/src/directives/ng_control.ts | 0 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.00017794608720578253,
0.00017140776617452502,
0.0001623710704734549,
0.0001726569898892194,
0.00000579831748837023
] |
{
"id": 5,
"code_window": [
" const xtb = new Xtb(this._htmlParser, interpolationConfig);\n",
" const translationBundle = TranslationBundle.load(this._translations, url, messageBundle, xtb);\n",
"\n",
" const translatedNodes =\n",
" mergeTranslations(parseResult.rootNodes, translationBundle, interpolationConfig, [], {});\n",
"\n",
" return new ParseTreeResult(translatedNodes, []);\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" return mergeTranslations(parseResult.rootNodes, translationBundle, interpolationConfig, [], {});\n"
],
"file_path": "modules/@angular/compiler/src/i18n/html_parser.ts",
"type": "replace",
"edit_start_line_idx": 48
} | <!doctype html>
<html>
<title>Zippy Angular 2.0</title>
<body>
<zippy-app>
Loading...
</zippy-app>
<script src="../bootstrap.js"></script>
</body>
</html>
| modules/playground/src/zippy_component/index.html | 0 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.00017212833336088806,
0.0001704904716461897,
0.0001688525953795761,
0.0001704904716461897,
0.0000016378689906559885
] |
{
"id": 5,
"code_window": [
" const xtb = new Xtb(this._htmlParser, interpolationConfig);\n",
" const translationBundle = TranslationBundle.load(this._translations, url, messageBundle, xtb);\n",
"\n",
" const translatedNodes =\n",
" mergeTranslations(parseResult.rootNodes, translationBundle, interpolationConfig, [], {});\n",
"\n",
" return new ParseTreeResult(translatedNodes, []);\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
" return mergeTranslations(parseResult.rootNodes, translationBundle, interpolationConfig, [], {});\n"
],
"file_path": "modules/@angular/compiler/src/i18n/html_parser.ts",
"type": "replace",
"edit_start_line_idx": 48
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injector, NgZone, PLATFORM_INITIALIZER} from '@angular/core';
import {BrowserPlatformLocation} from '../../browser/location/browser_platform_location';
import {MessageBasedPlatformLocation} from './platform_location';
/**
* A list of {@link Provider}s. To use the router in a Worker enabled application you must
* include these providers when setting up the render thread.
* @experimental
*/
export const WORKER_UI_LOCATION_PROVIDERS = [
MessageBasedPlatformLocation, BrowserPlatformLocation,
{provide: PLATFORM_INITIALIZER, useFactory: initUiLocation, multi: true, deps: [Injector]}
];
function initUiLocation(injector: Injector): () => void {
return () => {
let zone = injector.get(NgZone);
zone.runGuarded(() => injector.get(MessageBasedPlatformLocation).start());
};
}
| modules/@angular/platform-browser/src/web_workers/ui/location_providers.ts | 0 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.00029241867014206946,
0.000201358474441804,
0.0001617068483028561,
0.00017565420421306044,
0.000052890583901898935
] |
{
"id": 6,
"code_window": [
"\n",
" const translations = new TranslationBundle(i18nMsgMap);\n",
"\n",
" const translateNodes = mergeTranslations(\n",
" htmlNodes, translations, DEFAULT_INTERPOLATION_CONFIG, implicitTags, implicitAttrs);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
" const translatedNodes =\n",
" mergeTranslations(\n",
" htmlNodes, translations, DEFAULT_INTERPOLATION_CONFIG, implicitTags, implicitAttrs)\n",
" .rootNodes;\n"
],
"file_path": "modules/@angular/compiler/test/i18n/extractor_merger_spec.ts",
"type": "replace",
"edit_start_line_idx": 412
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as html from '../ml_parser/ast';
import {InterpolationConfig} from '../ml_parser/interpolation_config';
import {digestMessage} from './digest';
import * as i18n from './i18n_ast';
import {createI18nMessageFactory} from './i18n_parser';
import {I18nError} from './parse_util';
import {TranslationBundle} from './translation_bundle';
const _I18N_ATTR = 'i18n';
const _I18N_ATTR_PREFIX = 'i18n-';
const _I18N_COMMENT_PREFIX_REGEXP = /^i18n:?/;
/**
* Extract translatable messages from an html AST
*/
export function extractMessages(
nodes: html.Node[], interpolationConfig: InterpolationConfig, implicitTags: string[],
implicitAttrs: {[k: string]: string[]}): ExtractionResult {
const visitor = new _Visitor(implicitTags, implicitAttrs);
return visitor.extract(nodes, interpolationConfig);
}
export function mergeTranslations(
nodes: html.Node[], translations: TranslationBundle, interpolationConfig: InterpolationConfig,
implicitTags: string[], implicitAttrs: {[k: string]: string[]}): html.Node[] {
const visitor = new _Visitor(implicitTags, implicitAttrs);
return visitor.merge(nodes, translations, interpolationConfig);
}
export class ExtractionResult {
constructor(public messages: i18n.Message[], public errors: I18nError[]) {}
}
enum _VisitorMode {
Extract,
Merge
}
/**
* This Visitor is used:
* 1. to extract all the translatable strings from an html AST (see `extract()`),
* 2. to replace the translatable strings with the actual translations (see `merge()`)
*
* @internal
*/
class _Visitor implements html.Visitor {
// <el i18n>...</el>
private _inI18nNode: boolean;
private _depth: number;
private _inImplicitNode: boolean;
// <!--i18n-->...<!--/i18n-->
private _blockMeaningAndDesc: string;
private _blockChildren: html.Node[];
private _blockStartDepth: number;
private _inI18nBlock: boolean;
// {<icu message>}
private _inIcu: boolean;
private _msgCountAtSectionStart: number;
private _errors: I18nError[];
private _mode: _VisitorMode;
// _VisitorMode.Extract only
private _messages: i18n.Message[];
// _VisitorMode.Merge only
private _translations: TranslationBundle;
private _createI18nMessage:
(msg: html.Node[], meaning: string, description: string) => i18n.Message;
constructor(private _implicitTags: string[], private _implicitAttrs: {[k: string]: string[]}) {}
/**
* Extracts the messages from the tree
*/
extract(nodes: html.Node[], interpolationConfig: InterpolationConfig): ExtractionResult {
this._init(_VisitorMode.Extract, interpolationConfig);
nodes.forEach(node => node.visit(this, null));
if (this._inI18nBlock) {
this._reportError(nodes[nodes.length - 1], 'Unclosed block');
}
return new ExtractionResult(this._messages, this._errors);
}
/**
* Returns a tree where all translatable nodes are translated
*/
merge(
nodes: html.Node[], translations: TranslationBundle,
interpolationConfig: InterpolationConfig): html.Node[] {
this._init(_VisitorMode.Merge, interpolationConfig);
this._translations = translations;
// Construct a single fake root element
const wrapper = new html.Element('wrapper', [], nodes, null, null, null);
const translatedNode = wrapper.visit(this, null);
// TODO(vicb): return MergeResult with errors
if (this._inI18nBlock) {
this._reportError(nodes[nodes.length - 1], 'Unclosed block');
}
return translatedNode.children;
}
visitExpansionCase(icuCase: html.ExpansionCase, context: any): any {
// Parse cases for translatable html attributes
const expression = html.visitAll(this, icuCase.expression, context);
if (this._mode === _VisitorMode.Merge) {
return new html.ExpansionCase(
icuCase.value, expression, icuCase.sourceSpan, icuCase.valueSourceSpan,
icuCase.expSourceSpan);
}
}
visitExpansion(icu: html.Expansion, context: any): html.Expansion {
this._mayBeAddBlockChildren(icu);
const wasInIcu = this._inIcu;
if (!this._inIcu) {
// nested ICU messages should not be extracted but top-level translated as a whole
if (this._isInTranslatableSection) {
this._addMessage([icu]);
}
this._inIcu = true;
}
const cases = html.visitAll(this, icu.cases, context);
if (this._mode === _VisitorMode.Merge) {
icu = new html.Expansion(
icu.switchValue, icu.type, cases, icu.sourceSpan, icu.switchValueSourceSpan);
}
this._inIcu = wasInIcu;
return icu;
}
visitComment(comment: html.Comment, context: any): any {
const isOpening = _isOpeningComment(comment);
if (isOpening && this._isInTranslatableSection) {
this._reportError(comment, 'Could not start a block inside a translatable section');
return;
}
const isClosing = _isClosingComment(comment);
if (isClosing && !this._inI18nBlock) {
this._reportError(comment, 'Trying to close an unopened block');
return;
}
if (!this._inI18nNode && !this._inIcu) {
if (!this._inI18nBlock) {
if (isOpening) {
this._inI18nBlock = true;
this._blockStartDepth = this._depth;
this._blockChildren = [];
this._blockMeaningAndDesc = comment.value.replace(_I18N_COMMENT_PREFIX_REGEXP, '').trim();
this._openTranslatableSection(comment);
}
} else {
if (isClosing) {
if (this._depth == this._blockStartDepth) {
this._closeTranslatableSection(comment, this._blockChildren);
this._inI18nBlock = false;
const message = this._addMessage(this._blockChildren, this._blockMeaningAndDesc);
// merge attributes in sections
const nodes = this._translateMessage(comment, message);
return html.visitAll(this, nodes);
} else {
this._reportError(comment, 'I18N blocks should not cross element boundaries');
return;
}
}
}
}
}
visitText(text: html.Text, context: any): html.Text {
if (this._isInTranslatableSection) {
this._mayBeAddBlockChildren(text);
}
return text;
}
visitElement(el: html.Element, context: any): html.Element {
this._mayBeAddBlockChildren(el);
this._depth++;
const wasInI18nNode = this._inI18nNode;
const wasInImplicitNode = this._inImplicitNode;
let childNodes: html.Node[];
// Extract only top level nodes with the (implicit) "i18n" attribute if not in a block or an ICU
// message
const i18nAttr = _getI18nAttr(el);
const isImplicit = this._implicitTags.some((tag: string): boolean => el.name === tag) &&
!this._inIcu && !this._isInTranslatableSection;
const isTopLevelImplicit = !wasInImplicitNode && isImplicit;
this._inImplicitNode = this._inImplicitNode || isImplicit;
if (!this._isInTranslatableSection && !this._inIcu) {
if (i18nAttr) {
// explicit translation
this._inI18nNode = true;
const message = this._addMessage(el.children, i18nAttr.value);
childNodes = this._translateMessage(el, message);
} else if (isTopLevelImplicit) {
// implicit translation
this._inI18nNode = true;
const message = this._addMessage(el.children);
childNodes = this._translateMessage(el, message);
}
if (this._mode == _VisitorMode.Extract) {
const isTranslatable = i18nAttr || isTopLevelImplicit;
if (isTranslatable) {
this._openTranslatableSection(el);
}
html.visitAll(this, el.children);
if (isTranslatable) {
this._closeTranslatableSection(el, el.children);
}
}
if (this._mode === _VisitorMode.Merge && !i18nAttr && !isTopLevelImplicit) {
childNodes = [];
el.children.forEach(child => {
const visited = child.visit(this, context);
if (visited && !this._isInTranslatableSection) {
// Do not add the children from translatable sections (= i18n blocks here)
// They will be added when the section is close (i.e. on `<!-- /i18n -->`)
childNodes = childNodes.concat(visited);
}
});
}
} else {
if (i18nAttr || isTopLevelImplicit) {
this._reportError(
el, 'Could not mark an element as translatable inside a translatable section');
}
if (this._mode == _VisitorMode.Extract) {
// Descend into child nodes for extraction
html.visitAll(this, el.children);
}
if (this._mode == _VisitorMode.Merge) {
// Translate attributes in ICU messages
childNodes = [];
el.children.forEach(child => {
const visited = child.visit(this, context);
if (visited && !this._isInTranslatableSection) {
// Do not add the children from translatable sections (= i18n blocks here)
// They will be added when the section is close (i.e. on `<!-- /i18n -->`)
childNodes = childNodes.concat(visited);
}
});
}
}
this._visitAttributesOf(el);
this._depth--;
this._inI18nNode = wasInI18nNode;
this._inImplicitNode = wasInImplicitNode;
if (this._mode === _VisitorMode.Merge) {
// There are no childNodes in translatable sections - those nodes will be replace anyway
const translatedAttrs = this._translateAttributes(el);
return new html.Element(
el.name, translatedAttrs, childNodes, el.sourceSpan, el.startSourceSpan,
el.endSourceSpan);
}
}
visitAttribute(attribute: html.Attribute, context: any): any {
throw new Error('unreachable code');
}
private _init(mode: _VisitorMode, interpolationConfig: InterpolationConfig): void {
this._mode = mode;
this._inI18nBlock = false;
this._inI18nNode = false;
this._depth = 0;
this._inIcu = false;
this._msgCountAtSectionStart = void 0;
this._errors = [];
this._messages = [];
this._inImplicitNode = false;
this._createI18nMessage = createI18nMessageFactory(interpolationConfig);
}
// looks for translatable attributes
private _visitAttributesOf(el: html.Element): void {
const explicitAttrNameToValue: {[k: string]: string} = {};
const implicitAttrNames: string[] = this._implicitAttrs[el.name] || [];
el.attrs.filter(attr => attr.name.startsWith(_I18N_ATTR_PREFIX))
.forEach(
attr => explicitAttrNameToValue[attr.name.slice(_I18N_ATTR_PREFIX.length)] =
attr.value);
el.attrs.forEach(attr => {
if (attr.name in explicitAttrNameToValue) {
this._addMessage([attr], explicitAttrNameToValue[attr.name]);
} else if (implicitAttrNames.some(name => attr.name === name)) {
this._addMessage([attr]);
}
});
}
// add a translatable message
private _addMessage(ast: html.Node[], meaningAndDesc?: string): i18n.Message {
if (ast.length == 0 ||
ast.length == 1 && ast[0] instanceof html.Attribute && !(<html.Attribute>ast[0]).value) {
// Do not create empty messages
return;
}
const [meaning, description] = _splitMeaningAndDesc(meaningAndDesc);
const message = this._createI18nMessage(ast, meaning, description);
this._messages.push(message);
return message;
}
// Translates the given message given the `TranslationBundle`
// no-op when called in extraction mode (returns [])
private _translateMessage(el: html.Node, message: i18n.Message): html.Node[] {
if (message && this._mode === _VisitorMode.Merge) {
const id = digestMessage(message);
const nodes = this._translations.get(id);
if (nodes) {
return nodes;
}
this._reportError(el, `Translation unavailable for message id="${id}"`);
}
return [];
}
// translate the attributes of an element and remove i18n specific attributes
private _translateAttributes(el: html.Element): html.Attribute[] {
const attributes = el.attrs;
const i18nAttributeMeanings: {[name: string]: string} = {};
attributes.forEach(attr => {
if (attr.name.startsWith(_I18N_ATTR_PREFIX)) {
i18nAttributeMeanings[attr.name.slice(_I18N_ATTR_PREFIX.length)] =
_splitMeaningAndDesc(attr.value)[0];
}
});
const translatedAttributes: html.Attribute[] = [];
attributes.forEach((attr) => {
if (attr.name === _I18N_ATTR || attr.name.startsWith(_I18N_ATTR_PREFIX)) {
// strip i18n specific attributes
return;
}
if (attr.value && attr.value != '' && i18nAttributeMeanings.hasOwnProperty(attr.name)) {
const meaning = i18nAttributeMeanings[attr.name];
const message: i18n.Message = this._createI18nMessage([attr], meaning, '');
const id = digestMessage(message);
const nodes = this._translations.get(id);
if (nodes) {
if (nodes[0] instanceof html.Text) {
const value = (nodes[0] as html.Text).value;
translatedAttributes.push(new html.Attribute(attr.name, value, attr.sourceSpan));
} else {
this._reportError(
el, `Unexpected translation for attribute "${attr.name}" (id="${id}")`);
}
} else {
this._reportError(
el, `Translation unavailable for attribute "${attr.name}" (id="${id}")`);
}
} else {
translatedAttributes.push(attr);
}
});
return translatedAttributes;
}
/**
* Add the node as a child of the block when:
* - we are in a block,
* - we are not inside a ICU message (those are handled separately),
* - the node is a "direct child" of the block
*/
private _mayBeAddBlockChildren(node: html.Node): void {
if (this._inI18nBlock && !this._inIcu && this._depth == this._blockStartDepth) {
this._blockChildren.push(node);
}
}
/**
* Marks the start of a section, see `_endSection`
*/
private _openTranslatableSection(node: html.Node): void {
if (this._isInTranslatableSection) {
this._reportError(node, 'Unexpected section start');
} else {
this._msgCountAtSectionStart = this._messages.length;
}
}
/**
* A translatable section could be:
* - a translatable element,
* - nodes between `<!-- i18n -->` and `<!-- /i18n -->` comments
*/
private get _isInTranslatableSection(): boolean {
return this._msgCountAtSectionStart !== void 0;
}
/**
* Terminates a section.
*
* If a section has only one significant children (comments not significant) then we should not
* keep the message from this children:
*
* `<p i18n="meaning|description">{ICU message}</p>` would produce two messages:
* - one for the <p> content with meaning and description,
* - another one for the ICU message.
*
* In this case the last message is discarded as it contains less information (the AST is
* otherwise identical).
*
* Note that we should still keep messages extracted from attributes inside the section (ie in the
* ICU message here)
*/
private _closeTranslatableSection(node: html.Node, directChildren: html.Node[]): void {
if (!this._isInTranslatableSection) {
this._reportError(node, 'Unexpected section end');
return;
}
const startIndex = this._msgCountAtSectionStart;
const significantChildren: number = directChildren.reduce(
(count: number, node: html.Node): number => count + (node instanceof html.Comment ? 0 : 1),
0);
if (significantChildren == 1) {
for (let i = this._messages.length - 1; i >= startIndex; i--) {
const ast = this._messages[i].nodes;
if (!(ast.length == 1 && ast[0] instanceof i18n.Text)) {
this._messages.splice(i, 1);
break;
}
}
}
this._msgCountAtSectionStart = void 0;
}
private _reportError(node: html.Node, msg: string): void {
this._errors.push(new I18nError(node.sourceSpan, msg));
}
}
function _isOpeningComment(n: html.Node): boolean {
return n instanceof html.Comment && n.value && n.value.startsWith('i18n');
}
function _isClosingComment(n: html.Node): boolean {
return n instanceof html.Comment && n.value && n.value === '/i18n';
}
function _getI18nAttr(p: html.Element): html.Attribute {
return p.attrs.find(attr => attr.name === _I18N_ATTR) || null;
}
function _splitMeaningAndDesc(i18n: string): [string, string] {
if (!i18n) return ['', ''];
const pipeIndex = i18n.indexOf('|');
return pipeIndex == -1 ? ['', i18n] : [i18n.slice(0, pipeIndex), i18n.slice(pipeIndex + 1)];
}
| modules/@angular/compiler/src/i18n/extractor_merger.ts | 1 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.996840238571167,
0.09207387268543243,
0.00016469002002850175,
0.0004020714550279081,
0.265329509973526
] |
{
"id": 6,
"code_window": [
"\n",
" const translations = new TranslationBundle(i18nMsgMap);\n",
"\n",
" const translateNodes = mergeTranslations(\n",
" htmlNodes, translations, DEFAULT_INTERPOLATION_CONFIG, implicitTags, implicitAttrs);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
" const translatedNodes =\n",
" mergeTranslations(\n",
" htmlNodes, translations, DEFAULT_INTERPOLATION_CONFIG, implicitTags, implicitAttrs)\n",
" .rootNodes;\n"
],
"file_path": "modules/@angular/compiler/test/i18n/extractor_merger_spec.ts",
"type": "replace",
"edit_start_line_idx": 412
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
declare module 'B64' {
export function fromByteArray(arr: Uint8Array): string;
export function toByteArray(str: string): Uint8Array;
} | modules/playground/src/web_workers/images/b64.d.ts | 0 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.00017481199756730348,
0.00017153681255877018,
0.00016826161299832165,
0.00017153681255877018,
0.000003275192284490913
] |
{
"id": 6,
"code_window": [
"\n",
" const translations = new TranslationBundle(i18nMsgMap);\n",
"\n",
" const translateNodes = mergeTranslations(\n",
" htmlNodes, translations, DEFAULT_INTERPOLATION_CONFIG, implicitTags, implicitAttrs);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
" const translatedNodes =\n",
" mergeTranslations(\n",
" htmlNodes, translations, DEFAULT_INTERPOLATION_CONFIG, implicitTags, implicitAttrs)\n",
" .rootNodes;\n"
],
"file_path": "modules/@angular/compiler/test/i18n/extractor_merger_spec.ts",
"type": "replace",
"edit_start_line_idx": 412
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {DirectiveResolver} from '@angular/compiler';
import {DirectiveMetadata, Type} from '@angular/core';
var COMPONENT_SELECTOR = /^[\w|-]*$/;
var SKEWER_CASE = /-(\w)/g;
var directiveResolver = new DirectiveResolver();
export interface AttrProp {
prop: string;
attr: string;
bracketAttr: string;
bracketParenAttr: string;
parenAttr: string;
onAttr: string;
bindAttr: string;
bindonAttr: string;
}
export interface ComponentInfo {
type: Type<any>;
selector: string;
inputs: AttrProp[];
outputs: AttrProp[];
}
export function getComponentInfo(type: Type<any>): ComponentInfo {
var resolvedMetadata: DirectiveMetadata = directiveResolver.resolve(type);
var selector = resolvedMetadata.selector;
if (!selector.match(COMPONENT_SELECTOR)) {
throw new Error('Only selectors matching element names are supported, got: ' + selector);
}
selector = selector.replace(
SKEWER_CASE, (all: any /** TODO #9100 */, letter: string) => letter.toUpperCase());
return {
type: type,
selector: selector,
inputs: parseFields(resolvedMetadata.inputs),
outputs: parseFields(resolvedMetadata.outputs)
};
}
export function parseFields(names: string[]): AttrProp[] {
var attrProps: AttrProp[] = [];
if (names) {
for (var i = 0; i < names.length; i++) {
var parts = names[i].split(':');
var prop = parts[0].trim();
var attr = (parts[1] || parts[0]).trim();
var capitalAttr = attr.charAt(0).toUpperCase() + attr.substr(1);
attrProps.push(<AttrProp>{
prop: prop,
attr: attr,
bracketAttr: `[${attr}]`,
parenAttr: `(${attr})`,
bracketParenAttr: `[(${attr})]`,
onAttr: `on${capitalAttr}`,
bindAttr: `bind${capitalAttr}`,
bindonAttr: `bindon${capitalAttr}`
});
}
}
return attrProps;
}
| modules/@angular/upgrade/src/metadata.ts | 0 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.000355488940840587,
0.00019647620501928031,
0.0001704005990177393,
0.0001740981824696064,
0.00006016133556840941
] |
{
"id": 6,
"code_window": [
"\n",
" const translations = new TranslationBundle(i18nMsgMap);\n",
"\n",
" const translateNodes = mergeTranslations(\n",
" htmlNodes, translations, DEFAULT_INTERPOLATION_CONFIG, implicitTags, implicitAttrs);\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
" const translatedNodes =\n",
" mergeTranslations(\n",
" htmlNodes, translations, DEFAULT_INTERPOLATION_CONFIG, implicitTags, implicitAttrs)\n",
" .rootNodes;\n"
],
"file_path": "modules/@angular/compiler/test/i18n/extractor_merger_spec.ts",
"type": "replace",
"edit_start_line_idx": 412
} | /**
* Dummy typings for systemjs.
*/
declare var System: any;
| modules/system.d.ts | 0 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.0001706127804936841,
0.0001706127804936841,
0.0001706127804936841,
0.0001706127804936841,
0
] |
{
"id": 7,
"code_window": [
"\n",
" return serializeHtmlNodes(translateNodes).join('');\n",
"}\n",
"\n",
"function extract(\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return serializeHtmlNodes(translatedNodes).join('');\n"
],
"file_path": "modules/@angular/compiler/test/i18n/extractor_merger_spec.ts",
"type": "replace",
"edit_start_line_idx": 415
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal';
import {digestMessage, serializeNodes as serializeI18nNodes} from '../../src/i18n/digest';
import {extractMessages, mergeTranslations} from '../../src/i18n/extractor_merger';
import * as i18n from '../../src/i18n/i18n_ast';
import {TranslationBundle} from '../../src/i18n/translation_bundle';
import * as html from '../../src/ml_parser/ast';
import {HtmlParser} from '../../src/ml_parser/html_parser';
import {DEFAULT_INTERPOLATION_CONFIG} from '../../src/ml_parser/interpolation_config';
import {serializeNodes as serializeHtmlNodes} from '../ml_parser/ast_serializer_spec';
export function main() {
describe('Extractor', () => {
describe('elements', () => {
it('should extract from elements', () => {
expect(extract('<div i18n="m|d|e">text<span>nested</span></div>')).toEqual([
[['text', '<ph tag name="START_TAG_SPAN">nested</ph name="CLOSE_TAG_SPAN">'], 'm', 'd|e'],
]);
});
it('should extract from attributes', () => {
expect(
extract(
'<div i18n="m1|d1"><span i18n-title="m2|d2" title="single child">nested</span></div>'))
.toEqual([
[['<ph tag name="START_TAG_SPAN">nested</ph name="CLOSE_TAG_SPAN">'], 'm1', 'd1'],
[['single child'], 'm2', 'd2'],
]);
});
it('should extract from ICU messages', () => {
expect(
extract(
'<div i18n="m|d">{count, plural, =0 { <p i18n-title i18n-desc title="title" desc="desc"></p>}}</div>'))
.toEqual([
[
[
'{count, plural, =0 {[<ph tag name="START_PARAGRAPH"></ph name="CLOSE_PARAGRAPH">]}}'
],
'm', 'd'
],
[['title'], '', ''],
[['desc'], '', ''],
]);
});
it('should not create a message for empty elements',
() => { expect(extract('<div i18n="m|d"></div>')).toEqual([]); });
it('should ignore implicit elements in translatable elements', () => {
expect(extract('<div i18n="m|d"><p></p></div>', ['p'])).toEqual([
[['<ph tag name="START_PARAGRAPH"></ph name="CLOSE_PARAGRAPH">'], 'm', 'd']
]);
});
});
describe('blocks', () => {
it('should extract from blocks', () => {
expect(extract(`<!-- i18n: meaning1|desc1 -->message1<!-- /i18n -->
<!-- i18n: desc2 -->message2<!-- /i18n -->
<!-- i18n -->message3<!-- /i18n -->`))
.toEqual([
[['message1'], 'meaning1', 'desc1'],
[['message2'], '', 'desc2'],
[['message3'], '', ''],
]);
});
it('should ignore implicit elements in blocks', () => {
expect(extract('<!-- i18n:m|d --><p></p><!-- /i18n -->', ['p'])).toEqual([
[['<ph tag name="START_PARAGRAPH"></ph name="CLOSE_PARAGRAPH">'], 'm', 'd']
]);
});
it('should extract siblings', () => {
expect(
extract(
`<!-- i18n -->text<p>html<b>nested</b></p>{count, plural, =0 {<span>html</span>}}{{interp}}<!-- /i18n -->`))
.toEqual([
[
[
'{count, plural, =0 {[<ph tag name="START_TAG_SPAN">html</ph name="CLOSE_TAG_SPAN">]}}'
],
'', ''
],
[
[
'text',
'<ph tag name="START_PARAGRAPH">html, <ph tag name="START_BOLD_TEXT">nested</ph name="CLOSE_BOLD_TEXT"></ph name="CLOSE_PARAGRAPH">',
'<ph icu name="ICU">{count, plural, =0 {[<ph tag name="START_TAG_SPAN">html</ph name="CLOSE_TAG_SPAN">]}}</ph>',
'[<ph name="INTERPOLATION">interp</ph>]'
],
'', ''
],
]);
});
it('should ignore other comments', () => {
expect(extract(`<!-- i18n: meaning1|desc1 --><!-- other -->message1<!-- /i18n -->`))
.toEqual([
[['message1'], 'meaning1', 'desc1'],
]);
});
it('should not create a message for empty blocks',
() => { expect(extract(`<!-- i18n: meaning1|desc1 --><!-- /i18n -->`)).toEqual([]); });
});
describe('ICU messages', () => {
it('should extract ICU messages from translatable elements', () => {
// single message when ICU is the only children
expect(extract('<div i18n="m|d">{count, plural, =0 {text}}</div>')).toEqual([
[['{count, plural, =0 {[text]}}'], 'm', 'd'],
]);
// single message when ICU is the only (implicit) children
expect(extract('<div>{count, plural, =0 {text}}</div>', ['div'])).toEqual([
[['{count, plural, =0 {[text]}}'], '', ''],
]);
// one message for the element content and one message for the ICU
expect(extract('<div i18n="m|d">before{count, plural, =0 {text}}after</div>')).toEqual([
[['before', '<ph icu name="ICU">{count, plural, =0 {[text]}}</ph>', 'after'], 'm', 'd'],
[['{count, plural, =0 {[text]}}'], '', ''],
]);
});
it('should extract ICU messages from translatable block', () => {
// single message when ICU is the only children
expect(extract('<!-- i18n:m|d -->{count, plural, =0 {text}}<!-- /i18n -->')).toEqual([
[['{count, plural, =0 {[text]}}'], 'm', 'd'],
]);
// one message for the block content and one message for the ICU
expect(extract('<!-- i18n:m|d -->before{count, plural, =0 {text}}after<!-- /i18n -->'))
.toEqual([
[['{count, plural, =0 {[text]}}'], '', ''],
[
['before', '<ph icu name="ICU">{count, plural, =0 {[text]}}</ph>', 'after'], 'm',
'd'
],
]);
});
it('should not extract ICU messages outside of i18n sections',
() => { expect(extract('{count, plural, =0 {text}}')).toEqual([]); });
it('should ignore nested ICU messages', () => {
expect(extract('<div i18n="m|d">{count, plural, =0 { {sex, gender, =m {m}} }}</div>'))
.toEqual([
[['{count, plural, =0 {[{sex, gender, =m {[m]}}, ]}}'], 'm', 'd'],
]);
});
it('should ignore implicit elements in non translatable ICU messages', () => {
expect(
extract(
'<div i18n="m|d">{count, plural, =0 { {sex, gender, =m {<p>ignore</p>}} }}</div>',
['p']))
.toEqual([[
[
'{count, plural, =0 {[{sex, gender, =m {[<ph tag name="START_PARAGRAPH">ignore</ph name="CLOSE_PARAGRAPH">]}}, ]}}'
],
'm', 'd'
]]);
});
it('should ignore implicit elements in non translatable ICU messages', () => {
expect(extract('{count, plural, =0 { {sex, gender, =m {<p>ignore</p>}} }}', ['p']))
.toEqual([]);
});
});
describe('attributes', () => {
it('should extract from attributes outside of translatable sections', () => {
expect(extract('<div i18n-title="m|d" title="msg"></div>')).toEqual([
[['msg'], 'm', 'd'],
]);
});
it('should extract from attributes in translatable elements', () => {
expect(extract('<div i18n><p><b i18n-title="m|d" title="msg"></b></p></div>')).toEqual([
[
[
'<ph tag name="START_PARAGRAPH"><ph tag name="START_BOLD_TEXT"></ph name="CLOSE_BOLD_TEXT"></ph name="CLOSE_PARAGRAPH">'
],
'', ''
],
[['msg'], 'm', 'd'],
]);
});
it('should extract from attributes in translatable blocks', () => {
expect(extract('<!-- i18n --><p><b i18n-title="m|d" title="msg"></b></p><!-- /i18n -->'))
.toEqual([
[['msg'], 'm', 'd'],
[
[
'<ph tag name="START_PARAGRAPH"><ph tag name="START_BOLD_TEXT"></ph name="CLOSE_BOLD_TEXT"></ph name="CLOSE_PARAGRAPH">'
],
'', ''
],
]);
});
it('should extract from attributes in translatable ICUs', () => {
expect(
extract(
'<!-- i18n -->{count, plural, =0 {<p><b i18n-title="m|d" title="msg"></b></p>}}<!-- /i18n -->'))
.toEqual([
[['msg'], 'm', 'd'],
[
[
'{count, plural, =0 {[<ph tag name="START_PARAGRAPH"><ph tag name="START_BOLD_TEXT"></ph name="CLOSE_BOLD_TEXT"></ph name="CLOSE_PARAGRAPH">]}}'
],
'', ''
],
]);
});
it('should extract from attributes in non translatable ICUs', () => {
expect(extract('{count, plural, =0 {<p><b i18n-title="m|d" title="msg"></b></p>}}'))
.toEqual([
[['msg'], 'm', 'd'],
]);
});
it('should not create a message for empty attributes',
() => { expect(extract('<div i18n-title="m|d" title></div>')).toEqual([]); });
});
describe('implicit elements', () => {
it('should extract from implicit elements', () => {
expect(extract('<b>bold</b><i>italic</i>', ['b'])).toEqual([
[['bold'], '', ''],
]);
});
it('should allow nested implicit elements', () => {
let result: any[];
expect(() => {
result = extract('<div>outer<div>inner</div></div>', ['div']);
}).not.toThrow();
expect(result).toEqual([
[['outer', '<ph tag name="START_TAG_DIV">inner</ph name="CLOSE_TAG_DIV">'], '', ''],
]);
});
});
describe('implicit attributes', () => {
it('should extract implicit attributes', () => {
expect(extract('<b title="bb">bold</b><i title="ii">italic</i>', [], {'b': ['title']}))
.toEqual([
[['bb'], '', ''],
]);
});
});
describe('errors', () => {
describe('elements', () => {
it('should report nested translatable elements', () => {
expect(extractErrors(`<p i18n><b i18n></b></p>`)).toEqual([
['Could not mark an element as translatable inside a translatable section', '<b i18n>'],
]);
});
it('should report translatable elements in implicit elements', () => {
expect(extractErrors(`<p><b i18n></b></p>`, ['p'])).toEqual([
['Could not mark an element as translatable inside a translatable section', '<b i18n>'],
]);
});
it('should report translatable elements in translatable blocks', () => {
expect(extractErrors(`<!-- i18n --><b i18n></b><!-- /i18n -->`)).toEqual([
['Could not mark an element as translatable inside a translatable section', '<b i18n>'],
]);
});
});
describe('blocks', () => {
it('should report nested blocks', () => {
expect(extractErrors(`<!-- i18n --><!-- i18n --><!-- /i18n --><!-- /i18n -->`)).toEqual([
['Could not start a block inside a translatable section', '<!--'],
['Trying to close an unopened block', '<!--'],
]);
});
it('should report unclosed blocks', () => {
expect(extractErrors(`<!-- i18n -->`)).toEqual([
['Unclosed block', '<!--'],
]);
});
it('should report translatable blocks in translatable elements', () => {
expect(extractErrors(`<p i18n><!-- i18n --><!-- /i18n --></p>`)).toEqual([
['Could not start a block inside a translatable section', '<!--'],
['Trying to close an unopened block', '<!--'],
]);
});
it('should report translatable blocks in implicit elements', () => {
expect(extractErrors(`<p><!-- i18n --><!-- /i18n --></p>`, ['p'])).toEqual([
['Could not start a block inside a translatable section', '<!--'],
['Trying to close an unopened block', '<!--'],
]);
});
it('should report when start and end of a block are not at the same level', () => {
expect(extractErrors(`<!-- i18n --><p><!-- /i18n --></p>`)).toEqual([
['I18N blocks should not cross element boundaries', '<!--'],
['Unclosed block', '<p>'],
]);
expect(extractErrors(`<p><!-- i18n --></p><!-- /i18n -->`)).toEqual([
['I18N blocks should not cross element boundaries', '<!--'],
['Unclosed block', '<!--'],
]);
});
});
});
});
describe('Merger', () => {
describe('elements', () => {
it('should merge elements', () => {
const HTML = `<p i18n="m|d">foo</p>`;
expect(fakeTranslate(HTML)).toEqual('<p>**foo**</p>');
});
it('should merge nested elements', () => {
const HTML = `<div>before<p i18n="m|d">foo</p><!-- comment --></div>`;
expect(fakeTranslate(HTML)).toEqual('<div>before<p>**foo**</p></div>');
});
});
describe('blocks', () => {
it('should merge blocks', () => {
const HTML = `before<!-- i18n --><p>foo</p><span><i>bar</i></span><!-- /i18n -->after`;
expect(fakeTranslate(HTML))
.toEqual(
'before**<ph tag name="START_PARAGRAPH">foo</ph name="CLOSE_PARAGRAPH"><ph tag name="START_TAG_SPAN"><ph tag name="START_ITALIC_TEXT">bar</ph name="CLOSE_ITALIC_TEXT"></ph name="CLOSE_TAG_SPAN">**after');
});
it('should merge nested blocks', () => {
const HTML =
`<div>before<!-- i18n --><p>foo</p><span><i>bar</i></span><!-- /i18n -->after</div>`;
expect(fakeTranslate(HTML))
.toEqual(
'<div>before**<ph tag name="START_PARAGRAPH">foo</ph name="CLOSE_PARAGRAPH"><ph tag name="START_TAG_SPAN"><ph tag name="START_ITALIC_TEXT">bar</ph name="CLOSE_ITALIC_TEXT"></ph name="CLOSE_TAG_SPAN">**after</div>');
});
});
describe('attributes', () => {
it('should merge attributes', () => {
const HTML = `<p i18n-title="m|d" title="foo"></p>`;
expect(fakeTranslate(HTML)).toEqual('<p title="**foo**"></p>');
});
it('should merge nested attributes', () => {
const HTML = `<div>{count, plural, =0 {<p i18n-title title="foo"></p>}}</div>`;
expect(fakeTranslate(HTML))
.toEqual('<div>{count, plural, =0 {<p title="**foo**"></p>}}</div>');
});
it('should merge attributes without values', () => {
const HTML = `<p i18n-title="m|d" title=""></p>`;
expect(fakeTranslate(HTML)).toEqual('<p title=""></p>');
});
});
});
}
function parseHtml(html: string): html.Node[] {
const htmlParser = new HtmlParser();
const parseResult = htmlParser.parse(html, 'extractor spec', true);
if (parseResult.errors.length > 1) {
throw new Error(`unexpected parse errors: ${parseResult.errors.join('\n')}`);
}
return parseResult.rootNodes;
}
function fakeTranslate(
content: string, implicitTags: string[] = [],
implicitAttrs: {[k: string]: string[]} = {}): string {
const htmlNodes: html.Node[] = parseHtml(content);
const messages: i18n.Message[] =
extractMessages(htmlNodes, DEFAULT_INTERPOLATION_CONFIG, implicitTags, implicitAttrs)
.messages;
const i18nMsgMap: {[id: string]: html.Node[]} = {};
messages.forEach(message => {
const id = digestMessage(message);
const text = serializeI18nNodes(message.nodes).join('');
i18nMsgMap[id] = [new html.Text(`**${text}**`, null)];
});
const translations = new TranslationBundle(i18nMsgMap);
const translateNodes = mergeTranslations(
htmlNodes, translations, DEFAULT_INTERPOLATION_CONFIG, implicitTags, implicitAttrs);
return serializeHtmlNodes(translateNodes).join('');
}
function extract(
html: string, implicitTags: string[] = [],
implicitAttrs: {[k: string]: string[]} = {}): [string[], string, string][] {
const result =
extractMessages(parseHtml(html), DEFAULT_INTERPOLATION_CONFIG, implicitTags, implicitAttrs);
if (result.errors.length > 0) {
throw new Error(`unexpected errors: ${result.errors.join('\n')}`);
}
// clang-format off
// https://github.com/angular/clang-format/issues/35
return result.messages.map(
message => [serializeI18nNodes(message.nodes), message.meaning, message.description, ]) as [string[], string, string][];
// clang-format on
}
function extractErrors(
html: string, implicitTags: string[] = [], implicitAttrs: {[k: string]: string[]} = {}): any[] {
const errors =
extractMessages(parseHtml(html), DEFAULT_INTERPOLATION_CONFIG, implicitTags, implicitAttrs)
.errors;
return errors.map((e): [string, string] => [e.msg, e.span.toString()]);
}
| modules/@angular/compiler/test/i18n/extractor_merger_spec.ts | 1 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.9987689852714539,
0.45944294333457947,
0.0001661032292759046,
0.018872465938329697,
0.4891291856765747
] |
{
"id": 7,
"code_window": [
"\n",
" return serializeHtmlNodes(translateNodes).join('');\n",
"}\n",
"\n",
"function extract(\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return serializeHtmlNodes(translatedNodes).join('');\n"
],
"file_path": "modules/@angular/compiler/test/i18n/extractor_merger_spec.ts",
"type": "replace",
"edit_start_line_idx": 415
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export enum NumberFormatStyle {
Decimal,
Percent,
Currency
}
export class NumberFormatter {
static format(
num: number, locale: string, style: NumberFormatStyle,
{minimumIntegerDigits, minimumFractionDigits, maximumFractionDigits, currency,
currencyAsSymbol = false}: {
minimumIntegerDigits?: number,
minimumFractionDigits?: number,
maximumFractionDigits?: number,
currency?: string,
currencyAsSymbol?: boolean
} = {}): string {
let options: Intl.NumberFormatOptions = {
minimumIntegerDigits,
minimumFractionDigits,
maximumFractionDigits,
style: NumberFormatStyle[style].toLowerCase()
};
if (style == NumberFormatStyle.Currency) {
options.currency = currency;
options.currencyDisplay = currencyAsSymbol ? 'symbol' : 'code';
}
return new Intl.NumberFormat(locale, options).format(num);
}
}
var DATE_FORMATS_SPLIT =
/((?:[^yMLdHhmsazZEwGjJ']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|J+|j+|m+|s+|a|z|Z|G+|w+))(.*)/;
var PATTERN_ALIASES = {
yMMMdjms: datePartGetterFactory(combine([
digitCondition('year', 1),
nameCondition('month', 3),
digitCondition('day', 1),
digitCondition('hour', 1),
digitCondition('minute', 1),
digitCondition('second', 1),
])),
yMdjm: datePartGetterFactory(combine([
digitCondition('year', 1), digitCondition('month', 1), digitCondition('day', 1),
digitCondition('hour', 1), digitCondition('minute', 1)
])),
yMMMMEEEEd: datePartGetterFactory(combine([
digitCondition('year', 1), nameCondition('month', 4), nameCondition('weekday', 4),
digitCondition('day', 1)
])),
yMMMMd: datePartGetterFactory(
combine([digitCondition('year', 1), nameCondition('month', 4), digitCondition('day', 1)])),
yMMMd: datePartGetterFactory(
combine([digitCondition('year', 1), nameCondition('month', 3), digitCondition('day', 1)])),
yMd: datePartGetterFactory(
combine([digitCondition('year', 1), digitCondition('month', 1), digitCondition('day', 1)])),
jms: datePartGetterFactory(combine(
[digitCondition('hour', 1), digitCondition('second', 1), digitCondition('minute', 1)])),
jm: datePartGetterFactory(combine([digitCondition('hour', 1), digitCondition('minute', 1)]))
};
var DATE_FORMATS = {
yyyy: datePartGetterFactory(digitCondition('year', 4)),
yy: datePartGetterFactory(digitCondition('year', 2)),
y: datePartGetterFactory(digitCondition('year', 1)),
MMMM: datePartGetterFactory(nameCondition('month', 4)),
MMM: datePartGetterFactory(nameCondition('month', 3)),
MM: datePartGetterFactory(digitCondition('month', 2)),
M: datePartGetterFactory(digitCondition('month', 1)),
LLLL: datePartGetterFactory(nameCondition('month', 4)),
dd: datePartGetterFactory(digitCondition('day', 2)),
d: datePartGetterFactory(digitCondition('day', 1)),
HH: digitModifier(
hourExtracter(datePartGetterFactory(hour12Modify(digitCondition('hour', 2), false)))),
H: hourExtracter(datePartGetterFactory(hour12Modify(digitCondition('hour', 1), false))),
hh: digitModifier(
hourExtracter(datePartGetterFactory(hour12Modify(digitCondition('hour', 2), true)))),
h: hourExtracter(datePartGetterFactory(hour12Modify(digitCondition('hour', 1), true))),
jj: datePartGetterFactory(digitCondition('hour', 2)),
j: datePartGetterFactory(digitCondition('hour', 1)),
mm: digitModifier(datePartGetterFactory(digitCondition('minute', 2))),
m: datePartGetterFactory(digitCondition('minute', 1)),
ss: digitModifier(datePartGetterFactory(digitCondition('second', 2))),
s: datePartGetterFactory(digitCondition('second', 1)),
// while ISO 8601 requires fractions to be prefixed with `.` or `,`
// we can be just safely rely on using `sss` since we currently don't support single or two digit
// fractions
sss: datePartGetterFactory(digitCondition('second', 3)),
EEEE: datePartGetterFactory(nameCondition('weekday', 4)),
EEE: datePartGetterFactory(nameCondition('weekday', 3)),
EE: datePartGetterFactory(nameCondition('weekday', 2)),
E: datePartGetterFactory(nameCondition('weekday', 1)),
a: hourClockExtracter(datePartGetterFactory(hour12Modify(digitCondition('hour', 1), true))),
Z: timeZoneGetter('short'),
z: timeZoneGetter('long'),
ww: datePartGetterFactory({}), // Week of year, padded (00-53). Week 01 is the week with the
// first Thursday of the year. not support ?
w: datePartGetterFactory({}), // Week of year (0-53). Week 1 is the week with the first Thursday
// of the year not support ?
G: datePartGetterFactory(nameCondition('era', 1)),
GG: datePartGetterFactory(nameCondition('era', 2)),
GGG: datePartGetterFactory(nameCondition('era', 3)),
GGGG: datePartGetterFactory(nameCondition('era', 4))
};
function digitModifier(inner: (date: Date, locale: string) => string): (
date: Date, locale: string) => string {
return function(date: Date, locale: string): string {
var result = inner(date, locale);
return result.length == 1 ? '0' + result : result;
};
}
function hourClockExtracter(inner: (date: Date, locale: string) => string): (
date: Date, locale: string) => string {
return function(date: Date, locale: string): string {
var result = inner(date, locale);
return result.split(' ')[1];
};
}
function hourExtracter(inner: (date: Date, locale: string) => string): (
date: Date, locale: string) => string {
return function(date: Date, locale: string): string {
var result = inner(date, locale);
return result.split(' ')[0];
};
}
function timeZoneGetter(timezone: string): (date: Date, locale: string) => string {
// To workaround `Intl` API restriction for single timezone let format with 24 hours
const format = {hour: '2-digit', hour12: false, timeZoneName: timezone};
return function(date: Date, locale: string): string {
const result = new Intl.DateTimeFormat(locale, format).format(date);
// Then extract first 3 letters that related to hours
return result ? result.substring(3) : '';
};
}
function hour12Modify(
options: Intl.DateTimeFormatOptions, value: boolean): Intl.DateTimeFormatOptions {
options.hour12 = value;
return options;
}
function digitCondition(prop: string, len: number): Intl.DateTimeFormatOptions {
var result: {[k: string]: string} = {};
result[prop] = len == 2 ? '2-digit' : 'numeric';
return result;
}
function nameCondition(prop: string, len: number): Intl.DateTimeFormatOptions {
var result: {[k: string]: string} = {};
result[prop] = len < 4 ? 'short' : 'long';
return result;
}
function combine(options: Intl.DateTimeFormatOptions[]): Intl.DateTimeFormatOptions {
var result = {};
options.forEach(option => { (<any>Object).assign(result, option); });
return result;
}
function datePartGetterFactory(ret: Intl.DateTimeFormatOptions): (date: Date, locale: string) =>
string {
return function(date: Date, locale: string): string {
return new Intl.DateTimeFormat(locale, ret).format(date);
};
}
var datePartsFormatterCache: Map<string, string[]> = new Map<string, string[]>();
function dateFormatter(format: string, date: Date, locale: string): string {
var text = '';
var match: any /** TODO #9100 */;
var fn: any /** TODO #9100 */;
var parts: string[] = [];
if ((PATTERN_ALIASES as any /** TODO #9100 */)[format]) {
return (PATTERN_ALIASES as any /** TODO #9100 */)[format](date, locale);
}
if (datePartsFormatterCache.has(format)) {
parts = datePartsFormatterCache.get(format);
} else {
const matches = DATE_FORMATS_SPLIT.exec(format);
while (format) {
match = DATE_FORMATS_SPLIT.exec(format);
if (match) {
parts = concat(parts, match, 1);
format = parts.pop();
} else {
parts.push(format);
format = null;
}
}
datePartsFormatterCache.set(format, parts);
}
parts.forEach(part => {
fn = (DATE_FORMATS as any /** TODO #9100 */)[part];
text += fn ? fn(date, locale) :
part === '\'\'' ? '\'' : part.replace(/(^'|'$)/g, '').replace(/''/g, '\'');
});
return text;
}
var slice = [].slice;
function concat(
array1: any /** TODO #9100 */, array2: any /** TODO #9100 */,
index: any /** TODO #9100 */): string[] {
return array1.concat(slice.call(array2, index));
}
export class DateFormatter {
static format(date: Date, locale: string, pattern: string): string {
return dateFormatter(pattern, date, locale);
}
}
| modules/@angular/facade/src/intl.ts | 0 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.000305526569718495,
0.00018113735131919384,
0.0001639858091948554,
0.0001698230771580711,
0.000030796571081737056
] |
{
"id": 7,
"code_window": [
"\n",
" return serializeHtmlNodes(translateNodes).join('');\n",
"}\n",
"\n",
"function extract(\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return serializeHtmlNodes(translatedNodes).join('');\n"
],
"file_path": "modules/@angular/compiler/test/i18n/extractor_merger_spec.ts",
"type": "replace",
"edit_start_line_idx": 415
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ViewType} from '../../core_private';
import {CompiledAnimation} from '../animation/animation_compiler';
import {CompileDirectiveMetadata, CompileIdentifierMap, CompileIdentifierMetadata, CompilePipeMetadata, CompileTokenMetadata} from '../compile_metadata';
import {CompilerConfig} from '../config';
import {ListWrapper} from '../facade/collection';
import {isBlank, isPresent} from '../facade/lang';
import {Identifiers} from '../identifiers';
import * as o from '../output/output_ast';
import {createDiTokenExpression} from '../util';
import {CompileBinding} from './compile_binding';
import {CompileElement, CompileNode} from './compile_element';
import {CompileMethod} from './compile_method';
import {CompilePipe} from './compile_pipe';
import {CompileQuery, addQueryToTokenMap, createQueryList} from './compile_query';
import {EventHandlerVars} from './constants';
import {NameResolver} from './expression_converter';
import {createPureProxy, getPropertyInView, getViewFactoryName, injectFromViewParentInjector} from './util';
export class CompileView implements NameResolver {
public viewType: ViewType;
public viewQueries: CompileIdentifierMap<CompileTokenMetadata, CompileQuery[]>;
public nodes: CompileNode[] = [];
// root nodes or AppElements for ViewContainers
public rootNodesOrAppElements: o.Expression[] = [];
public bindings: CompileBinding[] = [];
public classStatements: o.Statement[] = [];
public createMethod: CompileMethod;
public injectorGetMethod: CompileMethod;
public updateContentQueriesMethod: CompileMethod;
public dirtyParentQueriesMethod: CompileMethod;
public updateViewQueriesMethod: CompileMethod;
public detectChangesInInputsMethod: CompileMethod;
public detectChangesRenderPropertiesMethod: CompileMethod;
public afterContentLifecycleCallbacksMethod: CompileMethod;
public afterViewLifecycleCallbacksMethod: CompileMethod;
public destroyMethod: CompileMethod;
public detachMethod: CompileMethod;
public eventHandlerMethods: o.ClassMethod[] = [];
public fields: o.ClassField[] = [];
public getters: o.ClassGetter[] = [];
public disposables: o.Expression[] = [];
public subscriptions: o.Expression[] = [];
public componentView: CompileView;
public purePipes = new Map<string, CompilePipe>();
public pipes: CompilePipe[] = [];
public locals = new Map<string, o.Expression>();
public className: string;
public classType: o.Type;
public viewFactory: o.ReadVarExpr;
public literalArrayCount = 0;
public literalMapCount = 0;
public pipeCount = 0;
public componentContext: o.Expression;
constructor(
public component: CompileDirectiveMetadata, public genConfig: CompilerConfig,
public pipeMetas: CompilePipeMetadata[], public styles: o.Expression,
public animations: CompiledAnimation[], public viewIndex: number,
public declarationElement: CompileElement, public templateVariableBindings: string[][]) {
this.createMethod = new CompileMethod(this);
this.injectorGetMethod = new CompileMethod(this);
this.updateContentQueriesMethod = new CompileMethod(this);
this.dirtyParentQueriesMethod = new CompileMethod(this);
this.updateViewQueriesMethod = new CompileMethod(this);
this.detectChangesInInputsMethod = new CompileMethod(this);
this.detectChangesRenderPropertiesMethod = new CompileMethod(this);
this.afterContentLifecycleCallbacksMethod = new CompileMethod(this);
this.afterViewLifecycleCallbacksMethod = new CompileMethod(this);
this.destroyMethod = new CompileMethod(this);
this.detachMethod = new CompileMethod(this);
this.viewType = getViewType(component, viewIndex);
this.className = `_View_${component.type.name}${viewIndex}`;
this.classType = o.importType(new CompileIdentifierMetadata({name: this.className}));
this.viewFactory = o.variable(getViewFactoryName(component, viewIndex));
if (this.viewType === ViewType.COMPONENT || this.viewType === ViewType.HOST) {
this.componentView = this;
} else {
this.componentView = this.declarationElement.view.componentView;
}
this.componentContext =
getPropertyInView(o.THIS_EXPR.prop('context'), this, this.componentView);
var viewQueries = new CompileIdentifierMap<CompileTokenMetadata, CompileQuery[]>();
if (this.viewType === ViewType.COMPONENT) {
var directiveInstance = o.THIS_EXPR.prop('context');
ListWrapper.forEachWithIndex(this.component.viewQueries, (queryMeta, queryIndex) => {
var propName = `_viewQuery_${queryMeta.selectors[0].name}_${queryIndex}`;
var queryList = createQueryList(queryMeta, directiveInstance, propName, this);
var query = new CompileQuery(queryMeta, queryList, directiveInstance, this);
addQueryToTokenMap(viewQueries, query);
});
var constructorViewQueryCount = 0;
this.component.type.diDeps.forEach((dep) => {
if (isPresent(dep.viewQuery)) {
var queryList = o.THIS_EXPR.prop('declarationAppElement')
.prop('componentConstructorViewQueries')
.key(o.literal(constructorViewQueryCount++));
var query = new CompileQuery(dep.viewQuery, queryList, null, this);
addQueryToTokenMap(viewQueries, query);
}
});
}
this.viewQueries = viewQueries;
templateVariableBindings.forEach(
(entry) => { this.locals.set(entry[1], o.THIS_EXPR.prop('context').prop(entry[0])); });
if (!this.declarationElement.isNull()) {
this.declarationElement.setEmbeddedView(this);
}
}
callPipe(name: string, input: o.Expression, args: o.Expression[]): o.Expression {
return CompilePipe.call(this, name, [input].concat(args));
}
getLocal(name: string): o.Expression {
if (name == EventHandlerVars.event.name) {
return EventHandlerVars.event;
}
var currView: CompileView = this;
var result = currView.locals.get(name);
while (isBlank(result) && isPresent(currView.declarationElement.view)) {
currView = currView.declarationElement.view;
result = currView.locals.get(name);
}
if (isPresent(result)) {
return getPropertyInView(result, this, currView);
} else {
return null;
}
}
createLiteralArray(values: o.Expression[]): o.Expression {
if (values.length === 0) {
return o.importExpr(Identifiers.EMPTY_ARRAY);
}
var proxyExpr = o.THIS_EXPR.prop(`_arr_${this.literalArrayCount++}`);
var proxyParams: o.FnParam[] = [];
var proxyReturnEntries: o.Expression[] = [];
for (var i = 0; i < values.length; i++) {
var paramName = `p${i}`;
proxyParams.push(new o.FnParam(paramName));
proxyReturnEntries.push(o.variable(paramName));
}
createPureProxy(
o.fn(
proxyParams, [new o.ReturnStatement(o.literalArr(proxyReturnEntries))],
new o.ArrayType(o.DYNAMIC_TYPE)),
values.length, proxyExpr, this);
return proxyExpr.callFn(values);
}
createLiteralMap(entries: Array<Array<string|o.Expression>>): o.Expression {
if (entries.length === 0) {
return o.importExpr(Identifiers.EMPTY_MAP);
}
var proxyExpr = o.THIS_EXPR.prop(`_map_${this.literalMapCount++}`);
var proxyParams: o.FnParam[] = [];
var proxyReturnEntries: Array<Array<string|o.Expression>> = [];
var values: o.Expression[] = [];
for (var i = 0; i < entries.length; i++) {
var paramName = `p${i}`;
proxyParams.push(new o.FnParam(paramName));
proxyReturnEntries.push([entries[i][0], o.variable(paramName)]);
values.push(<o.Expression>entries[i][1]);
}
createPureProxy(
o.fn(
proxyParams, [new o.ReturnStatement(o.literalMap(proxyReturnEntries))],
new o.MapType(o.DYNAMIC_TYPE)),
entries.length, proxyExpr, this);
return proxyExpr.callFn(values);
}
afterNodes() {
this.viewQueries.values().forEach(
(queries) => queries.forEach(
(query) => query.afterChildren(this.createMethod, this.updateViewQueriesMethod)));
}
}
function getViewType(component: CompileDirectiveMetadata, embeddedTemplateIndex: number): ViewType {
if (embeddedTemplateIndex > 0) {
return ViewType.EMBEDDED;
} else if (component.type.isHost) {
return ViewType.HOST;
} else {
return ViewType.COMPONENT;
}
}
| modules/@angular/compiler/src/view_compiler/compile_view.ts | 0 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.00019279505067970604,
0.00017156804096885026,
0.00016660892288200557,
0.0001701296423561871,
0.000005405952833825722
] |
{
"id": 7,
"code_window": [
"\n",
" return serializeHtmlNodes(translateNodes).join('');\n",
"}\n",
"\n",
"function extract(\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" return serializeHtmlNodes(translatedNodes).join('');\n"
],
"file_path": "modules/@angular/compiler/test/i18n/extractor_merger_spec.ts",
"type": "replace",
"edit_start_line_idx": 415
} | // Tun on full stack traces in errors to help debugging
Error.stackTraceLimit=Infinity;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 100;
// Cancel Karma's synchronous start,
// we will call `__karma__.start()` later, once all the specs are loaded.
__karma__.loaded = function() {};
System.config({
baseURL: '/base',
defaultJSExtensions: true,
map: {
'benchpress/*': 'dist/js/dev/es5/benchpress/*.js',
'@angular': 'dist/all/@angular',
'rxjs': 'node_modules/rxjs',
'parse5/index': 'dist/all/empty.js',
'@angular/platform-server/src/parse5_adapter': 'dist/all/empty.js',
'angular2/*': 'dist/all/angular2/*.js',
'angular2/src/alt_router/router_testing_providers': 'dist/all/angular2/src/alt_router/router_testing_providers.js'
},
packages: {
'@angular/core': {
main: 'index.js',
defaultExtension: 'js'
},
'@angular/compiler': {
main: 'index.js',
defaultExtension: 'js'
},
'@angular/common': {
main: 'index.js',
defaultExtension: 'js'
},
'@angular/forms': {
main: 'index.js',
defaultExtension: 'js'
},
// remove after all tests imports are fixed
'@angular/facade': {
main: 'index.js',
defaultExtension: 'js'
},
'@angular/router': {
main: 'index.js',
defaultExtension: 'js'
},
'@angular/http': {
main: 'index.js',
defaultExtension: 'js'
},
'@angular/upgrade': {
main: 'index.js',
defaultExtension: 'js'
},
'@angular/platform-browser': {
main: 'index.js',
defaultExtension: 'js'
},
'@angular/platform-browser-dynamic': {
main: 'index.js',
defaultExtension: 'js'
},
'@angular/platform-server': {
main: 'index.js',
defaultExtension: 'js'
}
}
});
// Set up the test injector, then import all the specs, execute their `main()`
// method and kick off Karma (Jasmine).
System.import('@angular/core/testing')
.then(function(coreTesting){
return System.import('@angular/platform-browser-dynamic/testing')
.then(function(browserTesting) {
coreTesting.TestBed.initTestEnvironment(
browserTesting.BrowserDynamicTestingModule,
browserTesting.platformBrowserDynamicTesting());
});
})
.then(function() {
return Promise.all(
Object.keys(window.__karma__.files) // All files served by Karma.
.filter(onlySpecFiles)
.map(window.file2moduleName) // Normalize paths to module names.
.map(function(path) {
return System.import(path).then(function(module) {
if (module.hasOwnProperty('main')) {
module.main();
} else {
throw new Error('Module ' + path + ' does not implement main() method.');
}
});
}));
})
.then(function() {
__karma__.start();
}, function(error) {
__karma__.error(error.stack || error);
});
function onlySpecFiles(path) {
return /_spec\.js$/.test(path);
}
| test-main.js | 0 | https://github.com/angular/angular/commit/39c0f9ebb3d18e377f9b62c999508c532ff14986 | [
0.00017281921464018524,
0.00016799518198240548,
0.0001620179828023538,
0.00016806102939881384,
0.0000025233141514036106
] |
{
"id": 0,
"code_window": [
"export interface IGalleryExtensionProperties {\n",
"\tdependencies?: string[];\n",
"\textensionPack?: string[];\n",
"\tengine?: string;\n",
"}\n",
"\n",
"export interface IGalleryExtensionAsset {\n",
"\turi: string;\n",
"\tfallbackUri: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tlocalizedLanguages?: string[];\n"
],
"file_path": "src/vs/platform/extensionManagement/common/extensionManagement.ts",
"type": "add",
"edit_start_line_idx": 142
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { tmpdir } from 'os';
import * as path from 'path';
import { TPromise } from 'vs/base/common/winjs.base';
import { distinct } from 'vs/base/common/arrays';
import { getErrorMessage, isPromiseCanceledError, canceled } from 'vs/base/common/errors';
import { StatisticType, IGalleryExtension, IExtensionGalleryService, IGalleryExtensionAsset, IQueryOptions, SortBy, SortOrder, IExtensionManifest, IExtensionIdentifier, IReportedExtension, InstallOperation, ITranslation } from 'vs/platform/extensionManagement/common/extensionManagement';
import { getGalleryExtensionId, getGalleryExtensionTelemetryData, adoptToGalleryExtensionId } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
import { assign, getOrDefault } from 'vs/base/common/objects';
import { IRequestService } from 'vs/platform/request/node/request';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IPager } from 'vs/base/common/paging';
import { IRequestOptions, IRequestContext, download, asJson, asText } from 'vs/base/node/request';
import pkg from 'vs/platform/node/package';
import product from 'vs/platform/node/product';
import { isEngineValid } from 'vs/platform/extensions/node/extensionValidator';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { readFile } from 'vs/base/node/pfs';
import { writeFileAndFlushSync } from 'vs/base/node/extfs';
import { generateUuid, isUUID } from 'vs/base/common/uuid';
import { values } from 'vs/base/common/map';
import { CancellationToken } from 'vs/base/common/cancellation';
interface IRawGalleryExtensionFile {
assetType: string;
source: string;
}
interface IRawGalleryExtensionProperty {
key: string;
value: string;
}
interface IRawGalleryExtensionVersion {
version: string;
lastUpdated: string;
assetUri: string;
fallbackAssetUri: string;
files: IRawGalleryExtensionFile[];
properties?: IRawGalleryExtensionProperty[];
}
interface IRawGalleryExtensionStatistics {
statisticName: string;
value: number;
}
interface IRawGalleryExtension {
extensionId: string;
extensionName: string;
displayName: string;
shortDescription: string;
publisher: { displayName: string, publisherId: string, publisherName: string; };
versions: IRawGalleryExtensionVersion[];
statistics: IRawGalleryExtensionStatistics[];
flags: string;
}
interface IRawGalleryQueryResult {
results: {
extensions: IRawGalleryExtension[];
resultMetadata: {
metadataType: string;
metadataItems: {
name: string;
count: number;
}[];
}[]
}[];
}
enum Flags {
None = 0x0,
IncludeVersions = 0x1,
IncludeFiles = 0x2,
IncludeCategoryAndTags = 0x4,
IncludeSharedAccounts = 0x8,
IncludeVersionProperties = 0x10,
ExcludeNonValidated = 0x20,
IncludeInstallationTargets = 0x40,
IncludeAssetUri = 0x80,
IncludeStatistics = 0x100,
IncludeLatestVersionOnly = 0x200,
Unpublished = 0x1000
}
function flagsToString(...flags: Flags[]): string {
return String(flags.reduce((r, f) => r | f, 0));
}
enum FilterType {
Tag = 1,
ExtensionId = 4,
Category = 5,
ExtensionName = 7,
Target = 8,
Featured = 9,
SearchText = 10,
ExcludeWithFlags = 12
}
const AssetType = {
Icon: 'Microsoft.VisualStudio.Services.Icons.Default',
Details: 'Microsoft.VisualStudio.Services.Content.Details',
Changelog: 'Microsoft.VisualStudio.Services.Content.Changelog',
Manifest: 'Microsoft.VisualStudio.Code.Manifest',
VSIX: 'Microsoft.VisualStudio.Services.VSIXPackage',
License: 'Microsoft.VisualStudio.Services.Content.License',
Repository: 'Microsoft.VisualStudio.Services.Links.Source'
};
const PropertyType = {
Dependency: 'Microsoft.VisualStudio.Code.ExtensionDependencies',
ExtensionPack: 'Microsoft.VisualStudio.Code.ExtensionPack',
Engine: 'Microsoft.VisualStudio.Code.Engine'
};
interface ICriterium {
filterType: FilterType;
value?: string;
}
const DefaultPageSize = 10;
interface IQueryState {
pageNumber: number;
pageSize: number;
sortBy: SortBy;
sortOrder: SortOrder;
flags: Flags;
criteria: ICriterium[];
assetTypes: string[];
}
const DefaultQueryState: IQueryState = {
pageNumber: 1,
pageSize: DefaultPageSize,
sortBy: SortBy.NoneOrRelevance,
sortOrder: SortOrder.Default,
flags: Flags.None,
criteria: [],
assetTypes: []
};
class Query {
constructor(private state = DefaultQueryState) { }
get pageNumber(): number { return this.state.pageNumber; }
get pageSize(): number { return this.state.pageSize; }
get sortBy(): number { return this.state.sortBy; }
get sortOrder(): number { return this.state.sortOrder; }
get flags(): number { return this.state.flags; }
withPage(pageNumber: number, pageSize: number = this.state.pageSize): Query {
return new Query(assign({}, this.state, { pageNumber, pageSize }));
}
withFilter(filterType: FilterType, ...values: string[]): Query {
const criteria = [
...this.state.criteria,
...values.map(value => ({ filterType, value }))
];
return new Query(assign({}, this.state, { criteria }));
}
withSortBy(sortBy: SortBy): Query {
return new Query(assign({}, this.state, { sortBy }));
}
withSortOrder(sortOrder: SortOrder): Query {
return new Query(assign({}, this.state, { sortOrder }));
}
withFlags(...flags: Flags[]): Query {
return new Query(assign({}, this.state, { flags: flags.reduce((r, f) => r | f, 0) }));
}
withAssetTypes(...assetTypes: string[]): Query {
return new Query(assign({}, this.state, { assetTypes }));
}
get raw(): any {
const { criteria, pageNumber, pageSize, sortBy, sortOrder, flags, assetTypes } = this.state;
const filters = [{ criteria, pageNumber, pageSize, sortBy, sortOrder }];
return { filters, assetTypes, flags };
}
get searchText(): string {
const criterium = this.state.criteria.filter(criterium => criterium.filterType === FilterType.SearchText)[0];
return criterium ? criterium.value : '';
}
}
function getStatistic(statistics: IRawGalleryExtensionStatistics[], name: string): number {
const result = (statistics || []).filter(s => s.statisticName === name)[0];
return result ? result.value : 0;
}
function getCoreTranslationAssets(version: IRawGalleryExtensionVersion): { [languageId: string]: IGalleryExtensionAsset } {
const coreTranslationAssetPrefix = 'Microsoft.VisualStudio.Code.Translation.';
const result = version.files.filter(f => f.assetType.indexOf(coreTranslationAssetPrefix) === 0);
return result.reduce((result, file) => {
result[file.assetType.substring(coreTranslationAssetPrefix.length)] = getVersionAsset(version, file.assetType);
return result;
}, {});
}
function getVersionAsset(version: IRawGalleryExtensionVersion, type: string): IGalleryExtensionAsset {
const result = version.files.filter(f => f.assetType === type)[0];
if (type === AssetType.Repository) {
if (version.properties) {
const results = version.properties.filter(p => p.key === type);
const gitRegExp = new RegExp('((git|ssh|http(s)?)|(git@[\w\.]+))(:(//)?)([\w\.@\:/\-~]+)(\.git)(/)?');
const uri = results.filter(r => gitRegExp.test(r.value))[0];
if (!uri) {
return {
uri: null,
fallbackUri: null
};
}
return {
uri: uri.value,
fallbackUri: uri.value,
};
}
}
if (!result) {
if (type === AssetType.Icon) {
const uri = require.toUrl('./media/defaultIcon.png');
return { uri, fallbackUri: uri };
}
if (type === AssetType.Repository) {
return {
uri: null,
fallbackUri: null
};
}
return null;
}
if (type === AssetType.VSIX) {
return {
uri: `${version.fallbackAssetUri}/${type}?redirect=true`,
fallbackUri: `${version.fallbackAssetUri}/${type}`
};
}
return {
uri: `${version.assetUri}/${type}`,
fallbackUri: `${version.fallbackAssetUri}/${type}`
};
}
function getExtensions(version: IRawGalleryExtensionVersion, property: string): string[] {
const values = version.properties ? version.properties.filter(p => p.key === property) : [];
const value = values.length > 0 && values[0].value;
return value ? value.split(',').map(v => adoptToGalleryExtensionId(v)) : [];
}
function getEngine(version: IRawGalleryExtensionVersion): string {
const values = version.properties ? version.properties.filter(p => p.key === PropertyType.Engine) : [];
return (values.length > 0 && values[0].value) || '';
}
function getIsPreview(flags: string): boolean {
return flags.indexOf('preview') !== -1;
}
function toExtension(galleryExtension: IRawGalleryExtension, version: IRawGalleryExtensionVersion, index: number, query: Query, querySource?: string): IGalleryExtension {
const assets = {
manifest: getVersionAsset(version, AssetType.Manifest),
readme: getVersionAsset(version, AssetType.Details),
changelog: getVersionAsset(version, AssetType.Changelog),
download: getVersionAsset(version, AssetType.VSIX),
icon: getVersionAsset(version, AssetType.Icon),
license: getVersionAsset(version, AssetType.License),
repository: getVersionAsset(version, AssetType.Repository),
coreTranslations: getCoreTranslationAssets(version)
};
return {
identifier: {
id: getGalleryExtensionId(galleryExtension.publisher.publisherName, galleryExtension.extensionName),
uuid: galleryExtension.extensionId
},
name: galleryExtension.extensionName,
version: version.version,
date: version.lastUpdated,
displayName: galleryExtension.displayName,
publisherId: galleryExtension.publisher.publisherId,
publisher: galleryExtension.publisher.publisherName,
publisherDisplayName: galleryExtension.publisher.displayName,
description: galleryExtension.shortDescription || '',
installCount: getStatistic(galleryExtension.statistics, 'install') + getStatistic(galleryExtension.statistics, 'updateCount'),
rating: getStatistic(galleryExtension.statistics, 'averagerating'),
ratingCount: getStatistic(galleryExtension.statistics, 'ratingcount'),
assets,
properties: {
dependencies: getExtensions(version, PropertyType.Dependency),
extensionPack: getExtensions(version, PropertyType.ExtensionPack),
engine: getEngine(version)
},
/* __GDPR__FRAGMENT__
"GalleryExtensionTelemetryData2" : {
"index" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"searchText": { "classification": "CustomerContent", "purpose": "FeatureInsight" },
"querySource": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
telemetryData: {
index: ((query.pageNumber - 1) * query.pageSize) + index,
searchText: query.searchText,
querySource
},
preview: getIsPreview(galleryExtension.flags)
};
}
interface IRawExtensionsReport {
malicious: string[];
slow: string[];
}
export class ExtensionGalleryService implements IExtensionGalleryService {
_serviceBrand: any;
private extensionsGalleryUrl: string;
private extensionsControlUrl: string;
private readonly commonHeadersPromise: TPromise<{ [key: string]: string; }>;
constructor(
@IRequestService private requestService: IRequestService,
@IEnvironmentService private environmentService: IEnvironmentService,
@ITelemetryService private telemetryService: ITelemetryService
) {
const config = product.extensionsGallery;
this.extensionsGalleryUrl = config && config.serviceUrl;
this.extensionsControlUrl = config && config.controlUrl;
this.commonHeadersPromise = resolveMarketplaceHeaders(this.environmentService);
}
private api(path = ''): string {
return `${this.extensionsGalleryUrl}${path}`;
}
isEnabled(): boolean {
return !!this.extensionsGalleryUrl;
}
getExtension({ id, uuid }: IExtensionIdentifier, version?: string): TPromise<IGalleryExtension> {
let query = new Query()
.withFlags(Flags.IncludeAssetUri, Flags.IncludeStatistics, Flags.IncludeFiles, Flags.IncludeVersionProperties)
.withPage(1, 1)
.withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code')
.withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished));
if (uuid) {
query = query.withFilter(FilterType.ExtensionId, uuid);
} else {
query = query.withFilter(FilterType.ExtensionName, id);
}
return this.queryGallery(query, CancellationToken.None).then(({ galleryExtensions }) => {
if (galleryExtensions.length) {
const galleryExtension = galleryExtensions[0];
const versionAsset = version ? galleryExtension.versions.filter(v => v.version === version)[0] : galleryExtension.versions[0];
if (versionAsset) {
return toExtension(galleryExtension, versionAsset, 0, query);
}
}
return null;
});
}
query(options: IQueryOptions = {}): TPromise<IPager<IGalleryExtension>> {
if (!this.isEnabled()) {
return TPromise.wrapError<IPager<IGalleryExtension>>(new Error('No extension gallery service configured.'));
}
const type = options.names ? 'ids' : (options.text ? 'text' : 'all');
let text = options.text || '';
const pageSize = getOrDefault(options, o => o.pageSize, 50);
/* __GDPR__
"galleryService:query" : {
"type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"text": { "classification": "CustomerContent", "purpose": "FeatureInsight" }
}
*/
this.telemetryService.publicLog('galleryService:query', { type, text });
let query = new Query()
.withFlags(Flags.IncludeLatestVersionOnly, Flags.IncludeAssetUri, Flags.IncludeStatistics, Flags.IncludeFiles, Flags.IncludeVersionProperties)
.withPage(1, pageSize)
.withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code')
.withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished));
if (text) {
// Use category filter instead of "category:themes"
text = text.replace(/\bcategory:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g, (_, quotedCategory, category) => {
query = query.withFilter(FilterType.Category, category || quotedCategory);
return '';
});
// Use tag filter instead of "tag:debuggers"
text = text.replace(/\btag:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g, (_, quotedTag, tag) => {
query = query.withFilter(FilterType.Tag, tag || quotedTag);
return '';
});
text = text.trim();
if (text) {
text = text.length < 200 ? text : text.substring(0, 200);
query = query.withFilter(FilterType.SearchText, text);
}
query = query.withSortBy(SortBy.NoneOrRelevance);
} else if (options.ids) {
query = query.withFilter(FilterType.ExtensionId, ...options.ids);
} else if (options.names) {
query = query.withFilter(FilterType.ExtensionName, ...options.names);
} else {
query = query.withSortBy(SortBy.InstallCount);
}
if (typeof options.sortBy === 'number') {
query = query.withSortBy(options.sortBy);
}
if (typeof options.sortOrder === 'number') {
query = query.withSortOrder(options.sortOrder);
}
return this.queryGallery(query, CancellationToken.None).then(({ galleryExtensions, total }) => {
const extensions = galleryExtensions.map((e, index) => toExtension(e, e.versions[0], index, query, options.source));
const pageSize = query.pageSize;
const getPage = (pageIndex: number, ct: CancellationToken) => {
if (ct.isCancellationRequested) {
return TPromise.wrapError(canceled());
}
const nextPageQuery = query.withPage(pageIndex + 1);
return this.queryGallery(nextPageQuery, ct)
.then(({ galleryExtensions }) => galleryExtensions.map((e, index) => toExtension(e, e.versions[0], index, nextPageQuery, options.source)));
};
return { firstPage: extensions, total, pageSize, getPage } as IPager<IGalleryExtension>;
});
}
private queryGallery(query: Query, token: CancellationToken): TPromise<{ galleryExtensions: IRawGalleryExtension[], total: number; }> {
return this.commonHeadersPromise.then(commonHeaders => {
const data = JSON.stringify(query.raw);
const headers = assign({}, commonHeaders, {
'Content-Type': 'application/json',
'Accept': 'application/json;api-version=3.0-preview.1',
'Accept-Encoding': 'gzip',
'Content-Length': data.length
});
return this.requestService.request({
type: 'POST',
url: this.api('/extensionquery'),
data,
headers
}, token).then(context => {
if (context.res.statusCode >= 400 && context.res.statusCode < 500) {
return { galleryExtensions: [], total: 0 };
}
return asJson<IRawGalleryQueryResult>(context).then(result => {
const r = result.results[0];
const galleryExtensions = r.extensions;
const resultCount = r.resultMetadata && r.resultMetadata.filter(m => m.metadataType === 'ResultCount')[0];
const total = resultCount && resultCount.metadataItems.filter(i => i.name === 'TotalCount')[0].count || 0;
return { galleryExtensions, total };
});
});
});
}
reportStatistic(publisher: string, name: string, version: string, type: StatisticType): TPromise<void> {
if (!this.isEnabled()) {
return TPromise.as(null);
}
return this.commonHeadersPromise.then(commonHeaders => {
const headers = { ...commonHeaders, Accept: '*/*;api-version=4.0-preview.1' };
return this.requestService.request({
type: 'POST',
url: this.api(`/publishers/${publisher}/extensions/${name}/${version}/stats?statType=${type}`),
headers
}, CancellationToken.None).then(null, () => null);
});
}
download(extension: IGalleryExtension, operation: InstallOperation): TPromise<string> {
const zipPath = path.join(tmpdir(), generateUuid());
const data = getGalleryExtensionTelemetryData(extension);
const startTime = new Date().getTime();
/* __GDPR__
"galleryService:downloadVSIX" : {
"duration": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true },
"${include}": [
"${GalleryExtensionTelemetryData}"
]
}
*/
const log = (duration: number) => this.telemetryService.publicLog('galleryService:downloadVSIX', assign(data, { duration }));
const operationParam = operation === InstallOperation.Install ? 'install' : operation === InstallOperation.Update ? 'update' : '';
const downloadAsset = operationParam ? {
uri: `${extension.assets.download.uri}&${operationParam}=true`,
fallbackUri: `${extension.assets.download.fallbackUri}?${operationParam}=true`
} : extension.assets.download;
return this.getAsset(downloadAsset)
.then(context => download(zipPath, context))
.then(() => log(new Date().getTime() - startTime))
.then(() => zipPath);
}
getReadme(extension: IGalleryExtension, token: CancellationToken): TPromise<string> {
return this.getAsset(extension.assets.readme, {}, token)
.then(asText);
}
getManifest(extension: IGalleryExtension, token: CancellationToken): TPromise<IExtensionManifest> {
return this.getAsset(extension.assets.manifest, {}, token)
.then(asText)
.then(JSON.parse);
}
getCoreTranslation(extension: IGalleryExtension, languageId: string): TPromise<ITranslation> {
const asset = extension.assets.coreTranslations[languageId.toUpperCase()];
if (asset) {
return this.getAsset(asset)
.then(asText)
.then(JSON.parse);
}
return TPromise.as(null);
}
getChangelog(extension: IGalleryExtension, token: CancellationToken): TPromise<string> {
return this.getAsset(extension.assets.changelog, {}, token)
.then(asText);
}
loadAllDependencies(extensions: IExtensionIdentifier[], token: CancellationToken): TPromise<IGalleryExtension[]> {
return this.getDependenciesReccursively(extensions.map(e => e.id), [], token);
}
loadCompatibleVersion(extension: IGalleryExtension): TPromise<IGalleryExtension> {
if (extension.properties.engine && isEngineValid(extension.properties.engine)) {
return TPromise.wrap(extension);
}
const query = new Query()
.withFlags(Flags.IncludeVersions, Flags.IncludeFiles, Flags.IncludeVersionProperties)
.withPage(1, 1)
.withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code')
.withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished))
.withAssetTypes(AssetType.Manifest, AssetType.VSIX)
.withFilter(FilterType.ExtensionId, extension.identifier.uuid);
return this.queryGallery(query, CancellationToken.None)
.then(({ galleryExtensions }) => {
const [rawExtension] = galleryExtensions;
if (!rawExtension) {
return null;
}
return this.getLastValidExtensionVersion(rawExtension, rawExtension.versions)
.then(rawVersion => {
if (rawVersion) {
extension.properties.dependencies = getExtensions(rawVersion, PropertyType.Dependency);
extension.properties.engine = getEngine(rawVersion);
extension.assets.download = getVersionAsset(rawVersion, AssetType.VSIX);
extension.version = rawVersion.version;
return extension;
}
return null;
});
});
}
private loadDependencies(extensionNames: string[], token: CancellationToken): TPromise<IGalleryExtension[]> {
if (!extensionNames || extensionNames.length === 0) {
return TPromise.as([]);
}
let query = new Query()
.withFlags(Flags.IncludeLatestVersionOnly, Flags.IncludeAssetUri, Flags.IncludeStatistics, Flags.IncludeFiles, Flags.IncludeVersionProperties)
.withPage(1, extensionNames.length)
.withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code')
.withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished))
.withAssetTypes(AssetType.Icon, AssetType.License, AssetType.Details, AssetType.Manifest, AssetType.VSIX)
.withFilter(FilterType.ExtensionName, ...extensionNames);
return this.queryGallery(query, token).then(result => {
const dependencies = [];
const ids = [];
for (let index = 0; index < result.galleryExtensions.length; index++) {
const rawExtension = result.galleryExtensions[index];
if (ids.indexOf(rawExtension.extensionId) === -1) {
dependencies.push(toExtension(rawExtension, rawExtension.versions[0], index, query, 'dependencies'));
ids.push(rawExtension.extensionId);
}
}
return dependencies;
});
}
private getDependenciesReccursively(toGet: string[], result: IGalleryExtension[], token: CancellationToken): TPromise<IGalleryExtension[]> {
if (!toGet || !toGet.length) {
return TPromise.wrap(result);
}
toGet = result.length ? toGet.filter(e => !ExtensionGalleryService.hasExtensionByName(result, e)) : toGet;
if (!toGet.length) {
return TPromise.wrap(result);
}
return this.loadDependencies(toGet, token)
.then(loadedDependencies => {
const dependenciesSet = new Set<string>();
for (const dep of loadedDependencies) {
if (dep.properties.dependencies) {
dep.properties.dependencies.forEach(d => dependenciesSet.add(d));
}
}
result = distinct(result.concat(loadedDependencies), d => d.identifier.uuid);
const dependencies: string[] = [];
dependenciesSet.forEach(d => !ExtensionGalleryService.hasExtensionByName(result, d) && dependencies.push(d));
return this.getDependenciesReccursively(dependencies, result, token);
});
}
private getAsset(asset: IGalleryExtensionAsset, options: IRequestOptions = {}, token: CancellationToken = CancellationToken.None): TPromise<IRequestContext> {
return this.commonHeadersPromise.then(commonHeaders => {
const baseOptions = { type: 'GET' };
const headers = assign({}, commonHeaders, options.headers || {});
options = assign({}, options, baseOptions, { headers });
const url = asset.uri;
const fallbackUrl = asset.fallbackUri;
const firstOptions = assign({}, options, { url });
return this.requestService.request(firstOptions, token)
.then(context => {
if (context.res.statusCode === 200) {
return TPromise.as(context);
}
return asText(context)
.then(message => TPromise.wrapError<IRequestContext>(new Error(`Expected 200, got back ${context.res.statusCode} instead.\n\n${message}`)));
})
.then(null, err => {
if (isPromiseCanceledError(err)) {
return TPromise.wrapError<IRequestContext>(err);
}
const message = getErrorMessage(err);
/* __GDPR__
"galleryService:requestError" : {
"url" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"cdn": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"message": { "classification": "CallstackOrException", "purpose": "FeatureInsight" }
}
*/
this.telemetryService.publicLog('galleryService:requestError', { url, cdn: true, message });
/* __GDPR__
"galleryService:cdnFallback" : {
"url" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"message": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
this.telemetryService.publicLog('galleryService:cdnFallback', { url, message });
const fallbackOptions = assign({}, options, { url: fallbackUrl });
return this.requestService.request(fallbackOptions, token).then(null, err => {
if (isPromiseCanceledError(err)) {
return TPromise.wrapError<IRequestContext>(err);
}
const message = getErrorMessage(err);
/* __GDPR__
"galleryService:requestError" : {
"url" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"cdn": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"message": { "classification": "CallstackOrException", "purpose": "FeatureInsight" }
}
*/
this.telemetryService.publicLog('galleryService:requestError', { url: fallbackUrl, cdn: false, message });
return TPromise.wrapError<IRequestContext>(err);
});
});
});
}
private getLastValidExtensionVersion(extension: IRawGalleryExtension, versions: IRawGalleryExtensionVersion[]): TPromise<IRawGalleryExtensionVersion> {
const version = this.getLastValidExtensionVersionFromProperties(extension, versions);
if (version) {
return version;
}
return this.getLastValidExtensionVersionReccursively(extension, versions);
}
private getLastValidExtensionVersionFromProperties(extension: IRawGalleryExtension, versions: IRawGalleryExtensionVersion[]): TPromise<IRawGalleryExtensionVersion> {
for (const version of versions) {
const engine = getEngine(version);
if (!engine) {
return null;
}
if (isEngineValid(engine)) {
return TPromise.wrap(version);
}
}
return null;
}
private getLastValidExtensionVersionReccursively(extension: IRawGalleryExtension, versions: IRawGalleryExtensionVersion[]): TPromise<IRawGalleryExtensionVersion> {
if (!versions.length) {
return null;
}
const version = versions[0];
const asset = getVersionAsset(version, AssetType.Manifest);
const headers = { 'Accept-Encoding': 'gzip' };
return this.getAsset(asset, { headers })
.then(context => asJson<IExtensionManifest>(context))
.then(manifest => {
const engine = manifest.engines.vscode;
if (!isEngineValid(engine)) {
return this.getLastValidExtensionVersionReccursively(extension, versions.slice(1));
}
version.properties = version.properties || [];
version.properties.push({ key: PropertyType.Engine, value: manifest.engines.vscode });
return version;
});
}
private static hasExtensionByName(extensions: IGalleryExtension[], name: string): boolean {
for (const extension of extensions) {
if (`${extension.publisher}.${extension.name}` === name) {
return true;
}
}
return false;
}
getExtensionsReport(): TPromise<IReportedExtension[]> {
if (!this.isEnabled()) {
return TPromise.wrapError(new Error('No extension gallery service configured.'));
}
if (!this.extensionsControlUrl) {
return TPromise.as([]);
}
return this.requestService.request({ type: 'GET', url: this.extensionsControlUrl }, CancellationToken.None).then(context => {
if (context.res.statusCode !== 200) {
return TPromise.wrapError(new Error('Could not get extensions report.'));
}
return asJson<IRawExtensionsReport>(context).then(result => {
const map = new Map<string, IReportedExtension>();
for (const id of result.malicious) {
const ext = map.get(id) || { id: { id }, malicious: true, slow: false };
ext.malicious = true;
map.set(id, ext);
}
return TPromise.as(values(map));
});
});
}
}
export function resolveMarketplaceHeaders(environmentService: IEnvironmentService): TPromise<{ [key: string]: string; }> {
const marketplaceMachineIdFile = path.join(environmentService.userDataPath, 'machineid');
return readFile(marketplaceMachineIdFile, 'utf8').then(contents => {
if (isUUID(contents)) {
return contents;
}
return TPromise.wrap(null); // invalid marketplace UUID
}, error => {
return TPromise.wrap(null); // error reading ID file
}).then(uuid => {
if (!uuid) {
uuid = generateUuid();
try {
writeFileAndFlushSync(marketplaceMachineIdFile, uuid);
} catch (error) {
//noop
}
}
return {
'X-Market-Client-Id': `VSCode ${pkg.version}`,
'User-Agent': `VSCode ${pkg.version}`,
'X-Market-User-Id': uuid
};
});
}
| src/vs/platform/extensionManagement/node/extensionGalleryService.ts | 1 | https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39 | [
0.9991812109947205,
0.12900128960609436,
0.00016395296552218497,
0.0002021775144385174,
0.3260971009731293
] |
{
"id": 0,
"code_window": [
"export interface IGalleryExtensionProperties {\n",
"\tdependencies?: string[];\n",
"\textensionPack?: string[];\n",
"\tengine?: string;\n",
"}\n",
"\n",
"export interface IGalleryExtensionAsset {\n",
"\turi: string;\n",
"\tfallbackUri: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tlocalizedLanguages?: string[];\n"
],
"file_path": "src/vs/platform/extensionManagement/common/extensionManagement.ts",
"type": "add",
"edit_start_line_idx": 142
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><style>.icon-canvas-transparent{opacity:0;fill:#2d2d30}.icon-vs-out{fill:#2d2d30}.icon-vs-fg{fill:#2b282e}.icon-vs-action-blue{fill:#75beff}</style><path class="icon-canvas-transparent" d="M16 16H0V0h16v16z" id="canvas"/><path class="icon-vs-out" d="M0 10.736V4.5L9 0l7 3.5v6.236l-9 4.5-7-3.5z" id="outline"/><path class="icon-vs-action-blue" d="M9 1L1 5v5l6 3 8-4V4L9 1zM7 6.882L3.236 5 9 2.118 12.764 4 7 6.882z" id="iconBg"/><path class="icon-vs-fg" d="M9 2.118L12.764 4 7 6.882 3.236 5 9 2.118z" id="iconFg"/></svg> | src/vs/editor/contrib/suggest/media/Field_inverse_16x.svg | 0 | https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39 | [
0.00017076315998565406,
0.00017076315998565406,
0.00017076315998565406,
0.00017076315998565406,
0
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.