hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
sequencelengths 5
5
|
---|---|---|---|---|---|
{
"id": 2,
"code_window": [
" })\n",
" .add('withNotes rendering inline, github-flavored markdown', baseStory, {\n",
" notes: { markdown: markdownString },\n",
" })\n",
" .add('using decorator arguments, withNotes', withNotes('Notes into withNotes')(baseStory))\n",
" .add(\n",
" 'using decorator arguments, withMarkdownNotes',\n",
" withMarkdownNotes(markdownString)(baseStory)\n",
" );\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [
" .add('using decorator arguments, withMarkdownNotes', withMarkdownNotes(markdownString)(baseStory))\n",
" .add('with a markdown table', baseStory, {\n",
" notes: { markdown: markdownTable },\n",
" });"
],
"file_path": "examples/official-storybook/stories/addon-notes.stories.js",
"type": "replace",
"edit_start_line_idx": 41
} | import webpack from 'webpack';
import Dotenv from 'dotenv-webpack';
import InterpolateHtmlPlugin from '@storybook/react-dev-utils/InterpolateHtmlPlugin';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import { version } from '../../../package.json';
import { getPreviewHeadHtml, getManagerHeadHtml } from '../utils';
import { includePaths, excludePaths, loadEnv, nodePaths, getEntries } from './utils';
export default ({ configDir, babelOptions }) => ({
mode: 'production',
bail: true,
devtool: '#cheap-module-source-map',
entry: getEntries(configDir),
output: {
filename: 'static/[name].[chunkhash].bundle.js',
// Here we set the publicPath to ''.
// This allows us to deploy storybook into subpaths like GitHub pages.
// This works with css and image loaders too.
// This is working for storybook since, we don't use pushState urls and
// relative URLs works always.
publicPath: '',
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
chunks: ['manager', 'runtime~manager'],
chunksSortMode: 'none',
data: {
managerHead: getManagerHeadHtml(configDir),
version,
},
template: require.resolve('../index.html.ejs'),
}),
new HtmlWebpackPlugin({
filename: 'iframe.html',
excludeChunks: ['manager', 'runtime~manager'],
chunksSortMode: 'none',
data: {
previewHead: getPreviewHeadHtml(configDir),
},
template: require.resolve('../iframe.html.ejs'),
}),
new InterpolateHtmlPlugin(process.env),
new webpack.DefinePlugin(loadEnv({ production: true })),
new Dotenv({ silent: true }),
],
module: {
rules: [
{
test: /\.js$/,
use: [
{
loader: require.resolve('babel-loader'),
options: babelOptions,
},
],
include: includePaths,
exclude: excludePaths,
},
{
test: /\.md$/,
use: [
{
loader: require.resolve('raw-loader'),
},
],
},
],
},
resolve: {
// Since we ship with json-loader always, it's better to move extensions to here
// from the default config.
extensions: ['.js', '.json'],
// Add support to NODE_PATH. With this we could avoid relative path imports.
// Based on this CRA feature: https://github.com/facebookincubator/create-react-app/issues/253
modules: ['node_modules'].concat(nodePaths),
},
optimization: {
// Automatically split vendor and commons for preview bundle
// https://twitter.com/wSokra/status/969633336732905474
splitChunks: {
chunks: chunk => chunk.name !== 'manager',
},
// Keep the runtime chunk seperated to enable long term caching
// https://twitter.com/wSokra/status/969679223278505985
runtimeChunk: true,
},
});
| lib/core/src/server/config/webpack.config.prod.js | 0 | https://github.com/storybookjs/storybook/commit/ddc4e71fc285b8aa6bc9fef93683eb732d4f511d | [
0.00017653241229709238,
0.00017255774582736194,
0.00016631257312837988,
0.00017253734404221177,
0.0000027557382509257877
] |
{
"id": 2,
"code_window": [
" })\n",
" .add('withNotes rendering inline, github-flavored markdown', baseStory, {\n",
" notes: { markdown: markdownString },\n",
" })\n",
" .add('using decorator arguments, withNotes', withNotes('Notes into withNotes')(baseStory))\n",
" .add(\n",
" 'using decorator arguments, withMarkdownNotes',\n",
" withMarkdownNotes(markdownString)(baseStory)\n",
" );\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [
" .add('using decorator arguments, withMarkdownNotes', withMarkdownNotes(markdownString)(baseStory))\n",
" .add('with a markdown table', baseStory, {\n",
" notes: { markdown: markdownTable },\n",
" });"
],
"file_path": "examples/official-storybook/stories/addon-notes.stories.js",
"type": "replace",
"edit_start_line_idx": 41
} | // !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objects = {
/* Begin PBXBuildFile section */
00C302E51ABCBA2D00DB3ED1 /* libRCTActionSheet.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302AC1ABCB8CE00DB3ED1 /* libRCTActionSheet.a */; };
00C302E71ABCBA2D00DB3ED1 /* libRCTGeolocation.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302BA1ABCB90400DB3ED1 /* libRCTGeolocation.a */; };
00C302E81ABCBA2D00DB3ED1 /* libRCTImage.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302C01ABCB91800DB3ED1 /* libRCTImage.a */; };
00C302E91ABCBA2D00DB3ED1 /* libRCTNetwork.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302DC1ABCB9D200DB3ED1 /* libRCTNetwork.a */; };
00C302EA1ABCBA2D00DB3ED1 /* libRCTVibration.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302E41ABCB9EE00DB3ED1 /* libRCTVibration.a */; };
00E356F31AD99517003FC87E /* react_nativeTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 00E356F21AD99517003FC87E /* react_nativeTests.m */; };
133E29F31AD74F7200F7D852 /* libRCTLinking.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 78C398B91ACF4ADC00677621 /* libRCTLinking.a */; };
139105C61AF99C1200B5F7CC /* libRCTSettings.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 139105C11AF99BAD00B5F7CC /* libRCTSettings.a */; };
139FDEF61B0652A700C62182 /* libRCTWebSocket.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 139FDEF41B06529B00C62182 /* libRCTWebSocket.a */; };
13B07FBC1A68108700A75B9A /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB01A68108700A75B9A /* AppDelegate.m */; };
13B07FBD1A68108700A75B9A /* LaunchScreen.xib in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB11A68108700A75B9A /* LaunchScreen.xib */; };
13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Images.xcassets */; };
13B07FC11A68108700A75B9A /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB71A68108700A75B9A /* main.m */; };
140ED2AC1D01E1AD002B40FF /* libReact.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 146834041AC3E56700842450 /* libReact.a */; };
146834051AC3E58100842450 /* libReact.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 146834041AC3E56700842450 /* libReact.a */; };
2D02E4BC1E0B4A80006451C7 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB01A68108700A75B9A /* AppDelegate.m */; };
2D02E4BD1E0B4A84006451C7 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Images.xcassets */; };
2D02E4BF1E0B4AB3006451C7 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB71A68108700A75B9A /* main.m */; };
2D02E4C21E0B4AEC006451C7 /* libRCTAnimation-tvOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 5E9157351DD0AC6500FF2AA8 /* libRCTAnimation-tvOS.a */; };
2D02E4C31E0B4AEC006451C7 /* libRCTImage-tvOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 3DAD3E841DF850E9000B6D8A /* libRCTImage-tvOS.a */; };
2D02E4C41E0B4AEC006451C7 /* libRCTLinking-tvOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 3DAD3E881DF850E9000B6D8A /* libRCTLinking-tvOS.a */; };
2D02E4C51E0B4AEC006451C7 /* libRCTNetwork-tvOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 3DAD3E8C1DF850E9000B6D8A /* libRCTNetwork-tvOS.a */; };
2D02E4C61E0B4AEC006451C7 /* libRCTSettings-tvOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 3DAD3E901DF850E9000B6D8A /* libRCTSettings-tvOS.a */; };
2D02E4C71E0B4AEC006451C7 /* libRCTText-tvOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 3DAD3E941DF850E9000B6D8A /* libRCTText-tvOS.a */; };
2D02E4C81E0B4AEC006451C7 /* libRCTWebSocket-tvOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 3DAD3E991DF850E9000B6D8A /* libRCTWebSocket-tvOS.a */; };
2D02E4C91E0B4AEC006451C7 /* libReact.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 3DAD3EA31DF850E9000B6D8A /* libReact.a */; };
2DCD954D1E0B4F2C00145EB5 /* react_nativeTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 00E356F21AD99517003FC87E /* react_nativeTests.m */; };
5E9157361DD0AC6A00FF2AA8 /* libRCTAnimation.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 5E9157331DD0AC6500FF2AA8 /* libRCTAnimation.a */; };
832341BD1AAA6AB300B99B32 /* libRCTText.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 832341B51AAA6A8300B99B32 /* libRCTText.a */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
00C302AB1ABCB8CE00DB3ED1 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 00C302A71ABCB8CE00DB3ED1 /* RCTActionSheet.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 134814201AA4EA6300B7C361;
remoteInfo = RCTActionSheet;
};
00C302B91ABCB90400DB3ED1 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 00C302B51ABCB90400DB3ED1 /* RCTGeolocation.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 134814201AA4EA6300B7C361;
remoteInfo = RCTGeolocation;
};
00C302BF1ABCB91800DB3ED1 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 00C302BB1ABCB91800DB3ED1 /* RCTImage.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 58B5115D1A9E6B3D00147676;
remoteInfo = RCTImage;
};
00C302DB1ABCB9D200DB3ED1 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 00C302D31ABCB9D200DB3ED1 /* RCTNetwork.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 58B511DB1A9E6C8500147676;
remoteInfo = RCTNetwork;
};
00C302E31ABCB9EE00DB3ED1 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 00C302DF1ABCB9EE00DB3ED1 /* RCTVibration.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 832C81801AAF6DEF007FA2F7;
remoteInfo = RCTVibration;
};
00E356F41AD99517003FC87E /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 83CBB9F71A601CBA00E9B192 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 13B07F861A680F5B00A75B9A;
remoteInfo = react_native;
};
139105C01AF99BAD00B5F7CC /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 139105B61AF99BAD00B5F7CC /* RCTSettings.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 134814201AA4EA6300B7C361;
remoteInfo = RCTSettings;
};
139FDEF31B06529B00C62182 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 139FDEE61B06529A00C62182 /* RCTWebSocket.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 3C86DF461ADF2C930047B81A;
remoteInfo = RCTWebSocket;
};
146834031AC3E56700842450 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 83CBBA2E1A601D0E00E9B192;
remoteInfo = React;
};
2D02E4911E0B4A5D006451C7 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 83CBB9F71A601CBA00E9B192 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 2D02E47A1E0B4A5D006451C7;
remoteInfo = "react_native-tvOS";
};
3DAD3E831DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 00C302BB1ABCB91800DB3ED1 /* RCTImage.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 2D2A283A1D9B042B00D4039D;
remoteInfo = "RCTImage-tvOS";
};
3DAD3E871DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 78C398B01ACF4ADC00677621 /* RCTLinking.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 2D2A28471D9B043800D4039D;
remoteInfo = "RCTLinking-tvOS";
};
3DAD3E8B1DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 00C302D31ABCB9D200DB3ED1 /* RCTNetwork.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 2D2A28541D9B044C00D4039D;
remoteInfo = "RCTNetwork-tvOS";
};
3DAD3E8F1DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 139105B61AF99BAD00B5F7CC /* RCTSettings.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 2D2A28611D9B046600D4039D;
remoteInfo = "RCTSettings-tvOS";
};
3DAD3E931DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 832341B01AAA6A8300B99B32 /* RCTText.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 2D2A287B1D9B048500D4039D;
remoteInfo = "RCTText-tvOS";
};
3DAD3E981DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 139FDEE61B06529A00C62182 /* RCTWebSocket.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 2D2A28881D9B049200D4039D;
remoteInfo = "RCTWebSocket-tvOS";
};
3DAD3EA21DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 2D2A28131D9B038B00D4039D;
remoteInfo = "React-tvOS";
};
3DAD3EA41DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 3D3C059A1DE3340900C268FA;
remoteInfo = yoga;
};
3DAD3EA61DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 3D3C06751DE3340C00C268FA;
remoteInfo = "yoga-tvOS";
};
3DAD3EA81DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 3D3CD9251DE5FBEC00167DC4;
remoteInfo = cxxreact;
};
3DAD3EAA1DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 3D3CD9321DE5FBEE00167DC4;
remoteInfo = "cxxreact-tvOS";
};
3DAD3EAC1DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 3D3CD90B1DE5FBD600167DC4;
remoteInfo = jschelpers;
};
3DAD3EAE1DF850E9000B6D8A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 3D3CD9181DE5FBD800167DC4;
remoteInfo = "jschelpers-tvOS";
};
5E9157321DD0AC6500FF2AA8 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5E91572D1DD0AC6500FF2AA8 /* RCTAnimation.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 134814201AA4EA6300B7C361;
remoteInfo = RCTAnimation;
};
5E9157341DD0AC6500FF2AA8 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5E91572D1DD0AC6500FF2AA8 /* RCTAnimation.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 2D2A28201D9B03D100D4039D;
remoteInfo = "RCTAnimation-tvOS";
};
78C398B81ACF4ADC00677621 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 78C398B01ACF4ADC00677621 /* RCTLinking.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 134814201AA4EA6300B7C361;
remoteInfo = RCTLinking;
};
832341B41AAA6A8300B99B32 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 832341B01AAA6A8300B99B32 /* RCTText.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 58B5119B1A9E6C1200147676;
remoteInfo = RCTText;
};
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
008F07F21AC5B25A0029DE68 /* main.jsbundle */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = main.jsbundle; sourceTree = "<group>"; };
00C302A71ABCB8CE00DB3ED1 /* RCTActionSheet.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTActionSheet.xcodeproj; path = "../node_modules/react-native/Libraries/ActionSheetIOS/RCTActionSheet.xcodeproj"; sourceTree = "<group>"; };
00C302B51ABCB90400DB3ED1 /* RCTGeolocation.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTGeolocation.xcodeproj; path = "../node_modules/react-native/Libraries/Geolocation/RCTGeolocation.xcodeproj"; sourceTree = "<group>"; };
00C302BB1ABCB91800DB3ED1 /* RCTImage.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTImage.xcodeproj; path = "../node_modules/react-native/Libraries/Image/RCTImage.xcodeproj"; sourceTree = "<group>"; };
00C302D31ABCB9D200DB3ED1 /* RCTNetwork.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTNetwork.xcodeproj; path = "../node_modules/react-native/Libraries/Network/RCTNetwork.xcodeproj"; sourceTree = "<group>"; };
00C302DF1ABCB9EE00DB3ED1 /* RCTVibration.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTVibration.xcodeproj; path = "../node_modules/react-native/Libraries/Vibration/RCTVibration.xcodeproj"; sourceTree = "<group>"; };
00E356EE1AD99517003FC87E /* react_nativeTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = react_nativeTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
00E356F11AD99517003FC87E /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
00E356F21AD99517003FC87E /* react_nativeTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = react_nativeTests.m; sourceTree = "<group>"; };
139105B61AF99BAD00B5F7CC /* RCTSettings.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTSettings.xcodeproj; path = "../node_modules/react-native/Libraries/Settings/RCTSettings.xcodeproj"; sourceTree = "<group>"; };
139FDEE61B06529A00C62182 /* RCTWebSocket.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTWebSocket.xcodeproj; path = "../node_modules/react-native/Libraries/WebSocket/RCTWebSocket.xcodeproj"; sourceTree = "<group>"; };
13B07F961A680F5B00A75B9A /* react_native.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = react_native.app; sourceTree = BUILT_PRODUCTS_DIR; };
13B07FAF1A68108700A75B9A /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AppDelegate.h; path = react_native/AppDelegate.h; sourceTree = "<group>"; };
13B07FB01A68108700A75B9A /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AppDelegate.m; path = react_native/AppDelegate.m; sourceTree = "<group>"; };
13B07FB21A68108700A75B9A /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/LaunchScreen.xib; sourceTree = "<group>"; };
13B07FB51A68108700A75B9A /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = react_native/Images.xcassets; sourceTree = "<group>"; };
13B07FB61A68108700A75B9A /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = react_native/Info.plist; sourceTree = "<group>"; };
13B07FB71A68108700A75B9A /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = main.m; path = react_native/main.m; sourceTree = "<group>"; };
146833FF1AC3E56700842450 /* React.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = React.xcodeproj; path = "../node_modules/react-native/React/React.xcodeproj"; sourceTree = "<group>"; };
2D02E47B1E0B4A5D006451C7 /* react_native-tvOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "react_native-tvOS.app"; sourceTree = BUILT_PRODUCTS_DIR; };
2D02E4901E0B4A5D006451C7 /* react_native-tvOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "react_native-tvOSTests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
5E91572D1DD0AC6500FF2AA8 /* RCTAnimation.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTAnimation.xcodeproj; path = "../node_modules/react-native/Libraries/NativeAnimation/RCTAnimation.xcodeproj"; sourceTree = "<group>"; };
78C398B01ACF4ADC00677621 /* RCTLinking.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTLinking.xcodeproj; path = "../node_modules/react-native/Libraries/LinkingIOS/RCTLinking.xcodeproj"; sourceTree = "<group>"; };
832341B01AAA6A8300B99B32 /* RCTText.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTText.xcodeproj; path = "../node_modules/react-native/Libraries/Text/RCTText.xcodeproj"; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
00E356EB1AD99517003FC87E /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
140ED2AC1D01E1AD002B40FF /* libReact.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
13B07F8C1A680F5B00A75B9A /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
146834051AC3E58100842450 /* libReact.a in Frameworks */,
5E9157361DD0AC6A00FF2AA8 /* libRCTAnimation.a in Frameworks */,
00C302E51ABCBA2D00DB3ED1 /* libRCTActionSheet.a in Frameworks */,
00C302E71ABCBA2D00DB3ED1 /* libRCTGeolocation.a in Frameworks */,
00C302E81ABCBA2D00DB3ED1 /* libRCTImage.a in Frameworks */,
133E29F31AD74F7200F7D852 /* libRCTLinking.a in Frameworks */,
00C302E91ABCBA2D00DB3ED1 /* libRCTNetwork.a in Frameworks */,
139105C61AF99C1200B5F7CC /* libRCTSettings.a in Frameworks */,
832341BD1AAA6AB300B99B32 /* libRCTText.a in Frameworks */,
00C302EA1ABCBA2D00DB3ED1 /* libRCTVibration.a in Frameworks */,
139FDEF61B0652A700C62182 /* libRCTWebSocket.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
2D02E4781E0B4A5D006451C7 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
2D02E4C91E0B4AEC006451C7 /* libReact.a in Frameworks */,
2D02E4C21E0B4AEC006451C7 /* libRCTAnimation-tvOS.a in Frameworks */,
2D02E4C31E0B4AEC006451C7 /* libRCTImage-tvOS.a in Frameworks */,
2D02E4C41E0B4AEC006451C7 /* libRCTLinking-tvOS.a in Frameworks */,
2D02E4C51E0B4AEC006451C7 /* libRCTNetwork-tvOS.a in Frameworks */,
2D02E4C61E0B4AEC006451C7 /* libRCTSettings-tvOS.a in Frameworks */,
2D02E4C71E0B4AEC006451C7 /* libRCTText-tvOS.a in Frameworks */,
2D02E4C81E0B4AEC006451C7 /* libRCTWebSocket-tvOS.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
2D02E48D1E0B4A5D006451C7 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
00C302A81ABCB8CE00DB3ED1 /* Products */ = {
isa = PBXGroup;
children = (
00C302AC1ABCB8CE00DB3ED1 /* libRCTActionSheet.a */,
);
name = Products;
sourceTree = "<group>";
};
00C302B61ABCB90400DB3ED1 /* Products */ = {
isa = PBXGroup;
children = (
00C302BA1ABCB90400DB3ED1 /* libRCTGeolocation.a */,
);
name = Products;
sourceTree = "<group>";
};
00C302BC1ABCB91800DB3ED1 /* Products */ = {
isa = PBXGroup;
children = (
00C302C01ABCB91800DB3ED1 /* libRCTImage.a */,
3DAD3E841DF850E9000B6D8A /* libRCTImage-tvOS.a */,
);
name = Products;
sourceTree = "<group>";
};
00C302D41ABCB9D200DB3ED1 /* Products */ = {
isa = PBXGroup;
children = (
00C302DC1ABCB9D200DB3ED1 /* libRCTNetwork.a */,
3DAD3E8C1DF850E9000B6D8A /* libRCTNetwork-tvOS.a */,
);
name = Products;
sourceTree = "<group>";
};
00C302E01ABCB9EE00DB3ED1 /* Products */ = {
isa = PBXGroup;
children = (
00C302E41ABCB9EE00DB3ED1 /* libRCTVibration.a */,
);
name = Products;
sourceTree = "<group>";
};
00E356EF1AD99517003FC87E /* react_nativeTests */ = {
isa = PBXGroup;
children = (
00E356F21AD99517003FC87E /* react_nativeTests.m */,
00E356F01AD99517003FC87E /* Supporting Files */,
);
path = react_nativeTests;
sourceTree = "<group>";
};
00E356F01AD99517003FC87E /* Supporting Files */ = {
isa = PBXGroup;
children = (
00E356F11AD99517003FC87E /* Info.plist */,
);
name = "Supporting Files";
sourceTree = "<group>";
};
139105B71AF99BAD00B5F7CC /* Products */ = {
isa = PBXGroup;
children = (
139105C11AF99BAD00B5F7CC /* libRCTSettings.a */,
3DAD3E901DF850E9000B6D8A /* libRCTSettings-tvOS.a */,
);
name = Products;
sourceTree = "<group>";
};
139FDEE71B06529A00C62182 /* Products */ = {
isa = PBXGroup;
children = (
139FDEF41B06529B00C62182 /* libRCTWebSocket.a */,
3DAD3E991DF850E9000B6D8A /* libRCTWebSocket-tvOS.a */,
);
name = Products;
sourceTree = "<group>";
};
13B07FAE1A68108700A75B9A /* react_native */ = {
isa = PBXGroup;
children = (
008F07F21AC5B25A0029DE68 /* main.jsbundle */,
13B07FAF1A68108700A75B9A /* AppDelegate.h */,
13B07FB01A68108700A75B9A /* AppDelegate.m */,
13B07FB51A68108700A75B9A /* Images.xcassets */,
13B07FB61A68108700A75B9A /* Info.plist */,
13B07FB11A68108700A75B9A /* LaunchScreen.xib */,
13B07FB71A68108700A75B9A /* main.m */,
);
name = react_native;
sourceTree = "<group>";
};
146834001AC3E56700842450 /* Products */ = {
isa = PBXGroup;
children = (
146834041AC3E56700842450 /* libReact.a */,
3DAD3EA31DF850E9000B6D8A /* libReact.a */,
3DAD3EA51DF850E9000B6D8A /* libyoga.a */,
3DAD3EA71DF850E9000B6D8A /* libyoga.a */,
3DAD3EA91DF850E9000B6D8A /* libcxxreact.a */,
3DAD3EAB1DF850E9000B6D8A /* libcxxreact.a */,
3DAD3EAD1DF850E9000B6D8A /* libjschelpers.a */,
3DAD3EAF1DF850E9000B6D8A /* libjschelpers.a */,
);
name = Products;
sourceTree = "<group>";
};
5E91572E1DD0AC6500FF2AA8 /* Products */ = {
isa = PBXGroup;
children = (
5E9157331DD0AC6500FF2AA8 /* libRCTAnimation.a */,
5E9157351DD0AC6500FF2AA8 /* libRCTAnimation-tvOS.a */,
);
name = Products;
sourceTree = "<group>";
};
78C398B11ACF4ADC00677621 /* Products */ = {
isa = PBXGroup;
children = (
78C398B91ACF4ADC00677621 /* libRCTLinking.a */,
3DAD3E881DF850E9000B6D8A /* libRCTLinking-tvOS.a */,
);
name = Products;
sourceTree = "<group>";
};
832341AE1AAA6A7D00B99B32 /* Libraries */ = {
isa = PBXGroup;
children = (
5E91572D1DD0AC6500FF2AA8 /* RCTAnimation.xcodeproj */,
146833FF1AC3E56700842450 /* React.xcodeproj */,
00C302A71ABCB8CE00DB3ED1 /* RCTActionSheet.xcodeproj */,
00C302B51ABCB90400DB3ED1 /* RCTGeolocation.xcodeproj */,
00C302BB1ABCB91800DB3ED1 /* RCTImage.xcodeproj */,
78C398B01ACF4ADC00677621 /* RCTLinking.xcodeproj */,
00C302D31ABCB9D200DB3ED1 /* RCTNetwork.xcodeproj */,
139105B61AF99BAD00B5F7CC /* RCTSettings.xcodeproj */,
832341B01AAA6A8300B99B32 /* RCTText.xcodeproj */,
00C302DF1ABCB9EE00DB3ED1 /* RCTVibration.xcodeproj */,
139FDEE61B06529A00C62182 /* RCTWebSocket.xcodeproj */,
);
name = Libraries;
sourceTree = "<group>";
};
832341B11AAA6A8300B99B32 /* Products */ = {
isa = PBXGroup;
children = (
832341B51AAA6A8300B99B32 /* libRCTText.a */,
3DAD3E941DF850E9000B6D8A /* libRCTText-tvOS.a */,
);
name = Products;
sourceTree = "<group>";
};
83CBB9F61A601CBA00E9B192 = {
isa = PBXGroup;
children = (
13B07FAE1A68108700A75B9A /* react_native */,
832341AE1AAA6A7D00B99B32 /* Libraries */,
00E356EF1AD99517003FC87E /* react_nativeTests */,
83CBBA001A601CBA00E9B192 /* Products */,
);
indentWidth = 2;
sourceTree = "<group>";
tabWidth = 2;
};
83CBBA001A601CBA00E9B192 /* Products */ = {
isa = PBXGroup;
children = (
13B07F961A680F5B00A75B9A /* react_native.app */,
00E356EE1AD99517003FC87E /* react_nativeTests.xctest */,
2D02E47B1E0B4A5D006451C7 /* react_native-tvOS.app */,
2D02E4901E0B4A5D006451C7 /* react_native-tvOSTests.xctest */,
);
name = Products;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
00E356ED1AD99517003FC87E /* react_nativeTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 00E357021AD99517003FC87E /* Build configuration list for PBXNativeTarget "react_nativeTests" */;
buildPhases = (
00E356EA1AD99517003FC87E /* Sources */,
00E356EB1AD99517003FC87E /* Frameworks */,
00E356EC1AD99517003FC87E /* Resources */,
);
buildRules = (
);
dependencies = (
00E356F51AD99517003FC87E /* PBXTargetDependency */,
);
name = react_nativeTests;
productName = react_nativeTests;
productReference = 00E356EE1AD99517003FC87E /* react_nativeTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
13B07F861A680F5B00A75B9A /* react_native */ = {
isa = PBXNativeTarget;
buildConfigurationList = 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "react_native" */;
buildPhases = (
13B07F871A680F5B00A75B9A /* Sources */,
13B07F8C1A680F5B00A75B9A /* Frameworks */,
13B07F8E1A680F5B00A75B9A /* Resources */,
00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */,
);
buildRules = (
);
dependencies = (
);
name = react_native;
productName = "Hello World";
productReference = 13B07F961A680F5B00A75B9A /* react_native.app */;
productType = "com.apple.product-type.application";
};
2D02E47A1E0B4A5D006451C7 /* react_native-tvOS */ = {
isa = PBXNativeTarget;
buildConfigurationList = 2D02E4BA1E0B4A5E006451C7 /* Build configuration list for PBXNativeTarget "react_native-tvOS" */;
buildPhases = (
2D02E4771E0B4A5D006451C7 /* Sources */,
2D02E4781E0B4A5D006451C7 /* Frameworks */,
2D02E4791E0B4A5D006451C7 /* Resources */,
2D02E4CB1E0B4B27006451C7 /* Bundle React Native Code And Images */,
);
buildRules = (
);
dependencies = (
);
name = "react_native-tvOS";
productName = "react_native-tvOS";
productReference = 2D02E47B1E0B4A5D006451C7 /* react_native-tvOS.app */;
productType = "com.apple.product-type.application";
};
2D02E48F1E0B4A5D006451C7 /* react_native-tvOSTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 2D02E4BB1E0B4A5E006451C7 /* Build configuration list for PBXNativeTarget "react_native-tvOSTests" */;
buildPhases = (
2D02E48C1E0B4A5D006451C7 /* Sources */,
2D02E48D1E0B4A5D006451C7 /* Frameworks */,
2D02E48E1E0B4A5D006451C7 /* Resources */,
);
buildRules = (
);
dependencies = (
2D02E4921E0B4A5D006451C7 /* PBXTargetDependency */,
);
name = "react_native-tvOSTests";
productName = "react_native-tvOSTests";
productReference = 2D02E4901E0B4A5D006451C7 /* react_native-tvOSTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
83CBB9F71A601CBA00E9B192 /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 0610;
ORGANIZATIONNAME = Facebook;
TargetAttributes = {
00E356ED1AD99517003FC87E = {
CreatedOnToolsVersion = 6.2;
TestTargetID = 13B07F861A680F5B00A75B9A;
};
2D02E47A1E0B4A5D006451C7 = {
CreatedOnToolsVersion = 8.2.1;
ProvisioningStyle = Automatic;
};
2D02E48F1E0B4A5D006451C7 = {
CreatedOnToolsVersion = 8.2.1;
ProvisioningStyle = Automatic;
TestTargetID = 2D02E47A1E0B4A5D006451C7;
};
};
};
buildConfigurationList = 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "react_native" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = English;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 83CBB9F61A601CBA00E9B192;
productRefGroup = 83CBBA001A601CBA00E9B192 /* Products */;
projectDirPath = "";
projectReferences = (
{
ProductGroup = 00C302A81ABCB8CE00DB3ED1 /* Products */;
ProjectRef = 00C302A71ABCB8CE00DB3ED1 /* RCTActionSheet.xcodeproj */;
},
{
ProductGroup = 5E91572E1DD0AC6500FF2AA8 /* Products */;
ProjectRef = 5E91572D1DD0AC6500FF2AA8 /* RCTAnimation.xcodeproj */;
},
{
ProductGroup = 00C302B61ABCB90400DB3ED1 /* Products */;
ProjectRef = 00C302B51ABCB90400DB3ED1 /* RCTGeolocation.xcodeproj */;
},
{
ProductGroup = 00C302BC1ABCB91800DB3ED1 /* Products */;
ProjectRef = 00C302BB1ABCB91800DB3ED1 /* RCTImage.xcodeproj */;
},
{
ProductGroup = 78C398B11ACF4ADC00677621 /* Products */;
ProjectRef = 78C398B01ACF4ADC00677621 /* RCTLinking.xcodeproj */;
},
{
ProductGroup = 00C302D41ABCB9D200DB3ED1 /* Products */;
ProjectRef = 00C302D31ABCB9D200DB3ED1 /* RCTNetwork.xcodeproj */;
},
{
ProductGroup = 139105B71AF99BAD00B5F7CC /* Products */;
ProjectRef = 139105B61AF99BAD00B5F7CC /* RCTSettings.xcodeproj */;
},
{
ProductGroup = 832341B11AAA6A8300B99B32 /* Products */;
ProjectRef = 832341B01AAA6A8300B99B32 /* RCTText.xcodeproj */;
},
{
ProductGroup = 00C302E01ABCB9EE00DB3ED1 /* Products */;
ProjectRef = 00C302DF1ABCB9EE00DB3ED1 /* RCTVibration.xcodeproj */;
},
{
ProductGroup = 139FDEE71B06529A00C62182 /* Products */;
ProjectRef = 139FDEE61B06529A00C62182 /* RCTWebSocket.xcodeproj */;
},
{
ProductGroup = 146834001AC3E56700842450 /* Products */;
ProjectRef = 146833FF1AC3E56700842450 /* React.xcodeproj */;
},
);
projectRoot = "";
targets = (
13B07F861A680F5B00A75B9A /* react_native */,
00E356ED1AD99517003FC87E /* react_nativeTests */,
2D02E47A1E0B4A5D006451C7 /* react_native-tvOS */,
2D02E48F1E0B4A5D006451C7 /* react_native-tvOSTests */,
);
};
/* End PBXProject section */
/* Begin PBXReferenceProxy section */
00C302AC1ABCB8CE00DB3ED1 /* libRCTActionSheet.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libRCTActionSheet.a;
remoteRef = 00C302AB1ABCB8CE00DB3ED1 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
00C302BA1ABCB90400DB3ED1 /* libRCTGeolocation.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libRCTGeolocation.a;
remoteRef = 00C302B91ABCB90400DB3ED1 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
00C302C01ABCB91800DB3ED1 /* libRCTImage.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libRCTImage.a;
remoteRef = 00C302BF1ABCB91800DB3ED1 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
00C302DC1ABCB9D200DB3ED1 /* libRCTNetwork.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libRCTNetwork.a;
remoteRef = 00C302DB1ABCB9D200DB3ED1 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
00C302E41ABCB9EE00DB3ED1 /* libRCTVibration.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libRCTVibration.a;
remoteRef = 00C302E31ABCB9EE00DB3ED1 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
139105C11AF99BAD00B5F7CC /* libRCTSettings.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libRCTSettings.a;
remoteRef = 139105C01AF99BAD00B5F7CC /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
139FDEF41B06529B00C62182 /* libRCTWebSocket.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libRCTWebSocket.a;
remoteRef = 139FDEF31B06529B00C62182 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
146834041AC3E56700842450 /* libReact.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libReact.a;
remoteRef = 146834031AC3E56700842450 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3E841DF850E9000B6D8A /* libRCTImage-tvOS.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = "libRCTImage-tvOS.a";
remoteRef = 3DAD3E831DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3E881DF850E9000B6D8A /* libRCTLinking-tvOS.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = "libRCTLinking-tvOS.a";
remoteRef = 3DAD3E871DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3E8C1DF850E9000B6D8A /* libRCTNetwork-tvOS.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = "libRCTNetwork-tvOS.a";
remoteRef = 3DAD3E8B1DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3E901DF850E9000B6D8A /* libRCTSettings-tvOS.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = "libRCTSettings-tvOS.a";
remoteRef = 3DAD3E8F1DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3E941DF850E9000B6D8A /* libRCTText-tvOS.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = "libRCTText-tvOS.a";
remoteRef = 3DAD3E931DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3E991DF850E9000B6D8A /* libRCTWebSocket-tvOS.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = "libRCTWebSocket-tvOS.a";
remoteRef = 3DAD3E981DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3EA31DF850E9000B6D8A /* libReact.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libReact.a;
remoteRef = 3DAD3EA21DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3EA51DF850E9000B6D8A /* libyoga.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libyoga.a;
remoteRef = 3DAD3EA41DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3EA71DF850E9000B6D8A /* libyoga.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libyoga.a;
remoteRef = 3DAD3EA61DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3EA91DF850E9000B6D8A /* libcxxreact.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libcxxreact.a;
remoteRef = 3DAD3EA81DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3EAB1DF850E9000B6D8A /* libcxxreact.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libcxxreact.a;
remoteRef = 3DAD3EAA1DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3EAD1DF850E9000B6D8A /* libjschelpers.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libjschelpers.a;
remoteRef = 3DAD3EAC1DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
3DAD3EAF1DF850E9000B6D8A /* libjschelpers.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libjschelpers.a;
remoteRef = 3DAD3EAE1DF850E9000B6D8A /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
5E9157331DD0AC6500FF2AA8 /* libRCTAnimation.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libRCTAnimation.a;
remoteRef = 5E9157321DD0AC6500FF2AA8 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
5E9157351DD0AC6500FF2AA8 /* libRCTAnimation-tvOS.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = "libRCTAnimation-tvOS.a";
remoteRef = 5E9157341DD0AC6500FF2AA8 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
78C398B91ACF4ADC00677621 /* libRCTLinking.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libRCTLinking.a;
remoteRef = 78C398B81ACF4ADC00677621 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
832341B51AAA6A8300B99B32 /* libRCTText.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libRCTText.a;
remoteRef = 832341B41AAA6A8300B99B32 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
/* End PBXReferenceProxy section */
/* Begin PBXResourcesBuildPhase section */
00E356EC1AD99517003FC87E /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
13B07F8E1A680F5B00A75B9A /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */,
13B07FBD1A68108700A75B9A /* LaunchScreen.xib in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
2D02E4791E0B4A5D006451C7 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
2D02E4BD1E0B4A84006451C7 /* Images.xcassets in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
2D02E48E1E0B4A5D006451C7 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "Bundle React Native code and images";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "export NODE_BINARY=node\n../node_modules/react-native/scripts/react-native-xcode.sh";
};
2D02E4CB1E0B4B27006451C7 /* Bundle React Native Code And Images */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "Bundle React Native Code And Images";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "export NODE_BINARY=node\n../node_modules/react-native/scripts/react-native-xcode.sh";
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
00E356EA1AD99517003FC87E /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
00E356F31AD99517003FC87E /* react_nativeTests.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
13B07F871A680F5B00A75B9A /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
13B07FBC1A68108700A75B9A /* AppDelegate.m in Sources */,
13B07FC11A68108700A75B9A /* main.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
2D02E4771E0B4A5D006451C7 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
2D02E4BF1E0B4AB3006451C7 /* main.m in Sources */,
2D02E4BC1E0B4A80006451C7 /* AppDelegate.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
2D02E48C1E0B4A5D006451C7 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
2DCD954D1E0B4F2C00145EB5 /* react_nativeTests.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
00E356F51AD99517003FC87E /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 13B07F861A680F5B00A75B9A /* react_native */;
targetProxy = 00E356F41AD99517003FC87E /* PBXContainerItemProxy */;
};
2D02E4921E0B4A5D006451C7 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 2D02E47A1E0B4A5D006451C7 /* react_native-tvOS */;
targetProxy = 2D02E4911E0B4A5D006451C7 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
13B07FB11A68108700A75B9A /* LaunchScreen.xib */ = {
isa = PBXVariantGroup;
children = (
13B07FB21A68108700A75B9A /* Base */,
);
name = LaunchScreen.xib;
path = react_native;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
00E356F61AD99517003FC87E /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
INFOPLIST_FILE = react_nativeTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
OTHER_LDFLAGS = (
"-ObjC",
"-lc++",
);
PRODUCT_NAME = "$(TARGET_NAME)";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/react_native.app/react_native";
};
name = Debug;
};
00E356F71AD99517003FC87E /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
COPY_PHASE_STRIP = NO;
INFOPLIST_FILE = react_nativeTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
OTHER_LDFLAGS = (
"-ObjC",
"-lc++",
);
PRODUCT_NAME = "$(TARGET_NAME)";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/react_native.app/react_native";
};
name = Release;
};
13B07F941A680F5B00A75B9A /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CURRENT_PROJECT_VERSION = 1;
DEAD_CODE_STRIPPING = NO;
INFOPLIST_FILE = react_native/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
OTHER_LDFLAGS = (
"$(inherited)",
"-ObjC",
"-lc++",
);
PRODUCT_NAME = react_native;
VERSIONING_SYSTEM = "apple-generic";
};
name = Debug;
};
13B07F951A680F5B00A75B9A /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CURRENT_PROJECT_VERSION = 1;
INFOPLIST_FILE = react_native/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
OTHER_LDFLAGS = (
"$(inherited)",
"-ObjC",
"-lc++",
);
PRODUCT_NAME = react_native;
VERSIONING_SYSTEM = "apple-generic";
};
name = Release;
};
2D02E4971E0B4A5E006451C7 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = "App Icon & Top Shelf Image";
ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;
CLANG_ANALYZER_NONNULL = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_TESTABILITY = YES;
GCC_NO_COMMON_BLOCKS = YES;
INFOPLIST_FILE = "react_native-tvOS/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
OTHER_LDFLAGS = (
"-ObjC",
"-lc++",
);
PRODUCT_BUNDLE_IDENTIFIER = "com.facebook.REACT.react_native-tvOS";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = appletvos;
TARGETED_DEVICE_FAMILY = 3;
TVOS_DEPLOYMENT_TARGET = 9.2;
};
name = Debug;
};
2D02E4981E0B4A5E006451C7 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = "App Icon & Top Shelf Image";
ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;
CLANG_ANALYZER_NONNULL = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
GCC_NO_COMMON_BLOCKS = YES;
INFOPLIST_FILE = "react_native-tvOS/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
OTHER_LDFLAGS = (
"-ObjC",
"-lc++",
);
PRODUCT_BUNDLE_IDENTIFIER = "com.facebook.REACT.react_native-tvOS";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = appletvos;
TARGETED_DEVICE_FAMILY = 3;
TVOS_DEPLOYMENT_TARGET = 9.2;
};
name = Release;
};
2D02E4991E0B4A5E006451C7 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CLANG_ANALYZER_NONNULL = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_TESTABILITY = YES;
GCC_NO_COMMON_BLOCKS = YES;
INFOPLIST_FILE = "react_native-tvOSTests/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "com.facebook.REACT.react_native-tvOSTests";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = appletvos;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/react_native-tvOS.app/react_native-tvOS";
TVOS_DEPLOYMENT_TARGET = 10.1;
};
name = Debug;
};
2D02E49A1E0B4A5E006451C7 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CLANG_ANALYZER_NONNULL = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
GCC_NO_COMMON_BLOCKS = YES;
INFOPLIST_FILE = "react_native-tvOSTests/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "com.facebook.REACT.react_native-tvOSTests";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = appletvos;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/react_native-tvOS.app/react_native-tvOS";
TVOS_DEPLOYMENT_TARGET = 10.1;
};
name = Release;
};
83CBBA201A601CBA00E9B192 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_SYMBOLS_PRIVATE_EXTERN = NO;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
};
name = Debug;
};
83CBBA211A601CBA00E9B192 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = YES;
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
VALIDATE_PRODUCT = YES;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
00E357021AD99517003FC87E /* Build configuration list for PBXNativeTarget "react_nativeTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
00E356F61AD99517003FC87E /* Debug */,
00E356F71AD99517003FC87E /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "react_native" */ = {
isa = XCConfigurationList;
buildConfigurations = (
13B07F941A680F5B00A75B9A /* Debug */,
13B07F951A680F5B00A75B9A /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
2D02E4BA1E0B4A5E006451C7 /* Build configuration list for PBXNativeTarget "react_native-tvOS" */ = {
isa = XCConfigurationList;
buildConfigurations = (
2D02E4971E0B4A5E006451C7 /* Debug */,
2D02E4981E0B4A5E006451C7 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
2D02E4BB1E0B4A5E006451C7 /* Build configuration list for PBXNativeTarget "react_native-tvOSTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
2D02E4991E0B4A5E006451C7 /* Debug */,
2D02E49A1E0B4A5E006451C7 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "react_native" */ = {
isa = XCConfigurationList;
buildConfigurations = (
83CBBA201A601CBA00E9B192 /* Debug */,
83CBBA211A601CBA00E9B192 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 83CBB9F71A601CBA00E9B192 /* Project object */;
}
| lib/cli/test/snapshots/react_native/ios/react_native.xcodeproj/project.pbxproj | 0 | https://github.com/storybookjs/storybook/commit/ddc4e71fc285b8aa6bc9fef93683eb732d4f511d | [
0.0022364247124642134,
0.00020344965741969645,
0.0001640724512981251,
0.00017429237777832896,
0.000198859503143467
] |
{
"id": 0,
"code_window": [
" addControl(dir: NgControl): void {\n",
" this._later(_ => {\n",
" var container = this._findContainer(dir.path);\n",
" var c = new Control(\"\");\n",
" setUpControl(c, dir);\n",
" container.addControl(dir.name, c);\n",
" c.updateValidity();\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" var c = new Control();\n"
],
"file_path": "modules/angular2/src/forms/directives/ng_form.ts",
"type": "replace",
"edit_start_line_idx": 76
} | import {StringWrapper, isPresent, isBlank} from 'angular2/src/facade/lang';
import {Observable, EventEmitter, ObservableWrapper} from 'angular2/src/facade/async';
import {StringMap, StringMapWrapper, ListWrapper, List} from 'angular2/src/facade/collection';
import {Validators} from './validators';
/**
* Indicates that a Control is valid, i.e. that no errors exist in the input value.
*/
export const VALID = "VALID";
/**
* Indicates that a Control is invalid, i.e. that an error exists in the input value.
*/
export const INVALID = "INVALID";
export function isControl(c: Object): boolean {
return c instanceof AbstractControl;
}
function _find(c: AbstractControl, path: List<string | number>| string) {
if (isBlank(path)) return null;
if (!(path instanceof List)) {
path = StringWrapper.split(<string>path, new RegExp("/"));
}
if (ListWrapper.isEmpty(path)) return null;
return ListWrapper.reduce(<List<string | number>>path, (v, name) => {
if (v instanceof ControlGroup) {
return isPresent(v.controls[name]) ? v.controls[name] : null;
} else if (v instanceof ControlArray) {
var index = <number>name;
return isPresent(v.at(index)) ? v.at(index) : null;
} else {
return null;
}
}, c);
}
/**
* Omitting from external API doc as this is really an abstract internal concept.
*/
export class AbstractControl {
_value: any;
_status: string;
_errors: StringMap<string, any>;
_pristine: boolean;
_touched: boolean;
_parent: ControlGroup | ControlArray;
validator: Function;
_valueChanges: EventEmitter;
constructor(validator: Function) {
this.validator = validator;
this._pristine = true;
this._touched = false;
}
get value(): any { return this._value; }
get status(): string { return this._status; }
get valid(): boolean { return this._status === VALID; }
get errors(): StringMap<string, any> { return this._errors; }
get pristine(): boolean { return this._pristine; }
get dirty(): boolean { return !this.pristine; }
get touched(): boolean { return this._touched; }
get untouched(): boolean { return !this._touched; }
get valueChanges(): Observable { return this._valueChanges; }
markAsTouched(): void { this._touched = true; }
markAsDirty({onlySelf}: {onlySelf?: boolean} = {}): void {
onlySelf = isPresent(onlySelf) ? onlySelf : false;
this._pristine = false;
if (isPresent(this._parent) && !onlySelf) {
this._parent.markAsDirty({onlySelf: onlySelf});
}
}
setParent(parent) { this._parent = parent; }
updateValidity({onlySelf}: {onlySelf?: boolean} = {}): void {
onlySelf = isPresent(onlySelf) ? onlySelf : false;
this._errors = this.validator(this);
this._status = isPresent(this._errors) ? INVALID : VALID;
if (isPresent(this._parent) && !onlySelf) {
this._parent.updateValidity({onlySelf: onlySelf});
}
}
updateValueAndValidity({onlySelf, emitEvent}: {onlySelf?: boolean, emitEvent?: boolean} = {}):
void {
onlySelf = isPresent(onlySelf) ? onlySelf : false;
emitEvent = isPresent(emitEvent) ? emitEvent : true;
this._updateValue();
if (emitEvent) {
ObservableWrapper.callNext(this._valueChanges, this._value);
}
this._errors = this.validator(this);
this._status = isPresent(this._errors) ? INVALID : VALID;
if (isPresent(this._parent) && !onlySelf) {
this._parent.updateValueAndValidity({onlySelf: onlySelf, emitEvent: emitEvent});
}
}
find(path: List<string | number>| string): AbstractControl { return _find(this, path); }
getError(errorCode: string, path: List<string> = null): any {
var c = isPresent(path) && !ListWrapper.isEmpty(path) ? this.find(path) : this;
if (isPresent(c) && isPresent(c._errors)) {
return StringMapWrapper.get(c._errors, errorCode);
} else {
return null;
}
}
hasError(errorCode: string, path: List<string> = null): boolean {
return isPresent(this.getError(errorCode, path));
}
_updateValue(): void {}
}
/**
* Defines a part of a form that cannot be divided into other controls.
*
* `Control` is one of the three fundamental building blocks used to define forms in Angular, along
* with
* {@link ControlGroup} and {@link ControlArray}.
*/
export class Control extends AbstractControl {
_onChange: Function;
constructor(value: any, validator: Function = Validators.nullValidator) {
super(validator);
this._value = value;
this.updateValidity({onlySelf: true});
this._valueChanges = new EventEmitter();
}
updateValue(value: any,
{onlySelf, emitEvent, emitModelToViewChange}:
{onlySelf?: boolean, emitEvent?: boolean, emitModelToViewChange?: boolean} = {}):
void {
emitModelToViewChange = isPresent(emitModelToViewChange) ? emitModelToViewChange : true;
this._value = value;
if (isPresent(this._onChange) && emitModelToViewChange) this._onChange(this._value);
this.updateValueAndValidity({onlySelf: onlySelf, emitEvent: emitEvent});
}
registerOnChange(fn: Function): void { this._onChange = fn; }
}
/**
* Defines a part of a form, of fixed length, that can contain other controls.
*
* A ControlGroup aggregates the values and errors of each {@link Control} in the group. Thus, if
* one of the controls
* in a group is invalid, the entire group is invalid. Similarly, if a control changes its value,
* the entire group
* changes as well.
*
* `ControlGroup` is one of the three fundamental building blocks used to define forms in Angular,
* along with
* {@link Control} and {@link ControlArray}. {@link ControlArray} can also contain other controls,
* but is of variable
* length.
*/
export class ControlGroup extends AbstractControl {
controls: StringMap<string, AbstractControl>;
_optionals: StringMap<string, boolean>;
constructor(controls: StringMap<String, AbstractControl>,
optionals: StringMap<String, boolean> = null,
validator: Function = Validators.group) {
super(validator);
this.controls = controls;
this._optionals = isPresent(optionals) ? optionals : {};
this._valueChanges = new EventEmitter();
this._setParentForControls();
this._value = this._reduceValue();
this.updateValidity({onlySelf: true});
}
addControl(name: string, c: AbstractControl) {
this.controls[name] = c;
c.setParent(this);
}
removeControl(name: string) { StringMapWrapper.delete(this.controls, name); }
include(controlName: string): void {
StringMapWrapper.set(this._optionals, controlName, true);
this.updateValueAndValidity();
}
exclude(controlName: string): void {
StringMapWrapper.set(this._optionals, controlName, false);
this.updateValueAndValidity();
}
contains(controlName: string): boolean {
var c = StringMapWrapper.contains(this.controls, controlName);
return c && this._included(controlName);
}
_setParentForControls() {
StringMapWrapper.forEach(this.controls, (control, name) => { control.setParent(this); });
}
_updateValue() { this._value = this._reduceValue(); }
_reduceValue() {
return this._reduceChildren({}, (acc, control, name) => {
acc[name] = control.value;
return acc;
});
}
_reduceChildren(initValue: any, fn: Function) {
var res = initValue;
StringMapWrapper.forEach(this.controls, (control, name) => {
if (this._included(name)) {
res = fn(res, control, name);
}
});
return res;
}
_included(controlName: string): boolean {
var isOptional = StringMapWrapper.contains(this._optionals, controlName);
return !isOptional || StringMapWrapper.get(this._optionals, controlName);
}
}
/**
* Defines a part of a form, of variable length, that can contain other controls.
*
* A `ControlArray` aggregates the values and errors of each {@link Control} in the group. Thus, if
* one of the controls
* in a group is invalid, the entire group is invalid. Similarly, if a control changes its value,
* the entire group
* changes as well.
*
* `ControlArray` is one of the three fundamental building blocks used to define forms in Angular,
* along with {@link Control} and {@link ControlGroup}. {@link ControlGroup} can also contain
* other controls, but is of fixed length.
*/
export class ControlArray extends AbstractControl {
controls: List<AbstractControl>;
constructor(controls: List<AbstractControl>, validator: Function = Validators.array) {
super(validator);
this.controls = controls;
this._valueChanges = new EventEmitter();
this._setParentForControls();
this._updateValue();
this.updateValidity({onlySelf: true});
}
at(index: number): AbstractControl { return this.controls[index]; }
push(control: AbstractControl): void {
this.controls.push(control);
control.setParent(this);
this.updateValueAndValidity();
}
insert(index: number, control: AbstractControl): void {
ListWrapper.insert(this.controls, index, control);
control.setParent(this);
this.updateValueAndValidity();
}
removeAt(index: number): void {
ListWrapper.removeAt(this.controls, index);
this.updateValueAndValidity();
}
get length(): number { return this.controls.length; }
_updateValue() { this._value = ListWrapper.map(this.controls, (c) => c.value); }
_setParentForControls() {
ListWrapper.forEach(this.controls, (control) => { control.setParent(this); });
}
}
| modules/angular2/src/forms/model.ts | 1 | https://github.com/angular/angular/commit/5b597de18cb4a29f78dc3a576b9c6e45bff18ecf | [
0.9958930015563965,
0.033544961363077164,
0.00016287161270156503,
0.00024074065731838346,
0.17576435208320618
] |
{
"id": 0,
"code_window": [
" addControl(dir: NgControl): void {\n",
" this._later(_ => {\n",
" var container = this._findContainer(dir.path);\n",
" var c = new Control(\"\");\n",
" setUpControl(c, dir);\n",
" container.addControl(dir.name, c);\n",
" c.updateValidity();\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" var c = new Control();\n"
],
"file_path": "modules/angular2/src/forms/directives/ng_form.ts",
"type": "replace",
"edit_start_line_idx": 76
} | import {verifyNoBrowserErrors} from 'angular2/src/test_lib/e2e_util';
describe('md-grid-list', function() {
var url = 'examples/src/material/grid_list/index.html';
beforeEach(() => { browser.get(url); });
afterEach(verifyNoBrowserErrors);
it('should set tiles into different positions', () => {
var tiles = element.all(by.css('md-grid-list#complex md-grid-tile'));
// If the grid-list was not doing any layout, all of the tiles would have the same position.
// So our smoke test simply checks that any two tiles are in different positions.
expect(tiles.first().getLocation()).not.toEqual(tiles.last().getLocation());
});
});
| modules/examples/e2e_test/material/grid_list_spec.ts | 0 | https://github.com/angular/angular/commit/5b597de18cb4a29f78dc3a576b9c6e45bff18ecf | [
0.00018006679601967335,
0.00017710159590933472,
0.0001741363957989961,
0.00017710159590933472,
0.0000029652001103386283
] |
{
"id": 0,
"code_window": [
" addControl(dir: NgControl): void {\n",
" this._later(_ => {\n",
" var container = this._findContainer(dir.path);\n",
" var c = new Control(\"\");\n",
" setUpControl(c, dir);\n",
" container.addControl(dir.name, c);\n",
" c.updateValidity();\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" var c = new Control();\n"
],
"file_path": "modules/angular2/src/forms/directives/ng_form.ts",
"type": "replace",
"edit_start_line_idx": 76
} | import {Component, View, LifecycleEvent} from 'angular2/angular2';
import {isPresent} from 'angular2/src/facade/lang';
@Component({selector: '[md-button]:not([href])'})
@View({templateUrl: 'angular2_material/src/components/button/button.html'})
export class MdButton {
// TODO(jelbourn): Ink ripples.
}
@Component({
selector: '[md-button][href]',
properties: ['disabled'],
host: {'(click)': 'onClick($event)', '[tabIndex]': 'tabIndex'},
lifecycle: [LifecycleEvent.onChange]
})
@View({templateUrl: 'angular2_material/src/components/button/button.html'})
export class MdAnchor {
tabIndex: number;
/** Whether the component is disabled. */
disabled: boolean;
onClick(event) {
// A disabled anchor shouldn't navigate anywhere.
if (isPresent(this.disabled) && this.disabled !== false) {
event.preventDefault();
}
}
/** Invoked when a change is detected. */
onChange(_) {
// A disabled anchor should not be in the tab flow.
this.tabIndex = this.disabled ? -1 : 0;
}
}
| modules/angular2_material/src/components/button/button.ts | 0 | https://github.com/angular/angular/commit/5b597de18cb4a29f78dc3a576b9c6e45bff18ecf | [
0.00017732768901623785,
0.00017483235569670796,
0.0001720832078717649,
0.00017495926294941455,
0.0000019063894569626427
] |
{
"id": 0,
"code_window": [
" addControl(dir: NgControl): void {\n",
" this._later(_ => {\n",
" var container = this._findContainer(dir.path);\n",
" var c = new Control(\"\");\n",
" setUpControl(c, dir);\n",
" container.addControl(dir.name, c);\n",
" c.updateValidity();\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" var c = new Control();\n"
],
"file_path": "modules/angular2/src/forms/directives/ng_form.ts",
"type": "replace",
"edit_start_line_idx": 76
} | /// <reference path="../typings/node/node.d.ts" />
/// <reference path="../typings/fs-extra/fs-extra.d.ts" />
import fse = require('fs-extra');
import path = require('path');
import {wrapDiffingPlugin, DiffingBroccoliPlugin, DiffResult} from './diffing-broccoli-plugin';
var spawn = require('child_process').spawn;
var exec = require('child_process').exec;
function processToPromise(process) {
return new Promise(function(resolve, reject) {
process.on('close', function(code) {
if (code) {
reject(code);
} else {
resolve();
}
});
});
}
class DartFormatter implements DiffingBroccoliPlugin {
private DARTFMT: string;
private verbose: boolean;
private firstBuild: boolean = true;
constructor(public inputPath: string, public cachePath: string, options) {
if (!options.dartSDK) throw new Error("Missing Dart SDK");
this.DARTFMT = options.dartSDK.DARTFMT;
this.verbose = options.logs.dartfmt;
}
rebuild(treeDiff: DiffResult): Promise<any> {
let args = ['-w'];
let argsLength = 2;
let argPackages = [];
let firstBuild = this.firstBuild;
treeDiff.addedPaths.concat(treeDiff.changedPaths)
.forEach((changedFile) => {
let sourcePath = path.join(this.inputPath, changedFile);
let destPath = path.join(this.cachePath, changedFile);
if (!firstBuild && /\.dart$/.test(changedFile)) {
if ((argsLength + destPath.length + 2) >= 0x2000) {
// Win32 command line arguments length
argPackages.push(args);
args = ['-w'];
argsLength = 2;
}
args.push(destPath);
argsLength += destPath.length + 2;
}
fse.copySync(sourcePath, destPath);
});
treeDiff.removedPaths.forEach((removedFile) => {
let destPath = path.join(this.cachePath, removedFile);
fse.removeSync(destPath);
});
if (!firstBuild && args.length > 1) {
argPackages.push(args);
}
let execute = (args) => {
if (args.length < 2) return Promise.resolve();
return new Promise((resolve, reject) => {
exec(this.DARTFMT + ' ' + args.join(' '), (err, stdout, stderr) => {
if (this.verbose) {
console.log(stdout);
}
if (err) {
console.error(shortenFormatterOutput(stderr));
reject('Formatting failed.');
} else {
resolve();
}
});
});
};
if (firstBuild) {
// On firstBuild, format the entire cachePath
this.firstBuild = false;
return execute(['-w', this.cachePath]);
}
return Promise.all(argPackages.map(execute));
}
}
export default wrapDiffingPlugin(DartFormatter);
var ARROW_LINE = /^(\s+)\^+/;
var BEFORE_CHARS = 15;
var stripAnsi = require('strip-ansi');
function shortenFormatterOutput(formatterOutput) {
var lines = formatterOutput.split('\n');
var match, line;
for (var i = 0; i < lines.length; i += 1) {
line = lines[i];
if (match = stripAnsi(line).match(ARROW_LINE)) {
let leadingWhitespace = match[1].length;
let leadingCodeChars = Math.min(leadingWhitespace, BEFORE_CHARS);
lines[i] = line.substr(leadingWhitespace - leadingCodeChars);
lines[i - 1] = lines[i - 1].substr(leadingWhitespace - leadingCodeChars, 80) + '…';
}
}
return lines.join('\n');
}
| tools/broccoli/broccoli-dartfmt.ts | 0 | https://github.com/angular/angular/commit/5b597de18cb4a29f78dc3a576b9c6e45bff18ecf | [
0.00017798221961129457,
0.00017386591935064644,
0.00016754455282352865,
0.00017508991004433483,
0.0000030032028917048592
] |
{
"id": 1,
"code_window": [
" lifecycle: [LifecycleEvent.onChange],\n",
" exportAs: 'form'\n",
"})\n",
"export class NgModel extends NgControl {\n",
" _control = new Control(\"\");\n",
" _added = false;\n",
" update = new EventEmitter();\n",
" model: any;\n",
" viewModel: any;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" _control = new Control();\n"
],
"file_path": "modules/angular2/src/forms/directives/ng_model.ts",
"type": "replace",
"edit_start_line_idx": 38
} | import {
ddescribe,
describe,
it,
iit,
xit,
expect,
beforeEach,
afterEach,
el,
AsyncTestCompleter,
fakeAsync,
tick,
inject
} from 'angular2/test_lib';
import {ControlGroup, Control, ControlArray, Validators} from 'angular2/forms';
import {ObservableWrapper} from 'angular2/src/facade/async';
export function main() {
describe("Form Model", () => {
describe("Control", () => {
describe("validator", () => {
it("should run validator with the initial value", () => {
var c = new Control("value", Validators.required);
expect(c.valid).toEqual(true);
});
it("should rerun the validator when the value changes", () => {
var c = new Control("value", Validators.required);
c.updateValue(null);
expect(c.valid).toEqual(false);
});
it("should return errors", () => {
var c = new Control(null, Validators.required);
expect(c.errors).toEqual({"required": true});
});
});
describe("dirty", () => {
it("should be false after creating a control", () => {
var c = new Control("value");
expect(c.dirty).toEqual(false);
});
it("should be true after changing the value of the control", () => {
var c = new Control("value");
c.markAsDirty();
expect(c.dirty).toEqual(true);
});
});
describe("updateValue", () => {
var g, c;
beforeEach(() => {
c = new Control("oldValue");
g = new ControlGroup({"one": c});
});
it("should update the value of the control", () => {
c.updateValue("newValue");
expect(c.value).toEqual("newValue");
});
it("should invoke onChange if it is present", () => {
var onChange;
c.registerOnChange((v) => onChange = ["invoked", v]);
c.updateValue("newValue");
expect(onChange).toEqual(["invoked", "newValue"]);
});
it("should not invoke on change when explicitly specified", () => {
var onChange = null;
c.registerOnChange((v) => onChange = ["invoked", v]);
c.updateValue("newValue", {emitModelToViewChange: false});
expect(onChange).toBeNull();
});
it("should update the parent", () => {
c.updateValue("newValue");
expect(g.value).toEqual({"one": "newValue"});
});
it("should not update the parent when explicitly specified", () => {
c.updateValue("newValue", {onlySelf: true});
expect(g.value).toEqual({"one": "oldValue"});
});
it("should fire an event", fakeAsync(() => {
ObservableWrapper.subscribe(c.valueChanges,
(value) => { expect(value).toEqual("newValue"); });
c.updateValue("newValue");
tick();
}));
it("should not fire an event when explicitly specified", fakeAsync(() => {
ObservableWrapper.subscribe(c.valueChanges, (value) => { throw "Should not happen"; });
c.updateValue("newValue", {emitEvent: false});
tick();
}));
});
describe("valueChanges", () => {
var c;
beforeEach(() => { c = new Control("old"); });
it("should fire an event after the value has been updated",
inject([AsyncTestCompleter], (async) => {
ObservableWrapper.subscribe(c.valueChanges, (value) => {
expect(c.value).toEqual('new');
expect(value).toEqual('new');
async.done();
});
c.updateValue("new");
}));
it("should return a cold observable", inject([AsyncTestCompleter], (async) => {
c.updateValue("will be ignored");
ObservableWrapper.subscribe(c.valueChanges, (value) => {
expect(value).toEqual('new');
async.done();
});
c.updateValue("new");
}));
});
});
describe("ControlGroup", () => {
describe("value", () => {
it("should be the reduced value of the child controls", () => {
var g = new ControlGroup({"one": new Control("111"), "two": new Control("222")});
expect(g.value).toEqual({"one": "111", "two": "222"});
});
it("should be empty when there are no child controls", () => {
var g = new ControlGroup({});
expect(g.value).toEqual({});
});
it("should support nested groups", () => {
var g = new ControlGroup(
{"one": new Control("111"), "nested": new ControlGroup({"two": new Control("222")})});
expect(g.value).toEqual({"one": "111", "nested": {"two": "222"}});
g.controls["nested"].controls["two"].updateValue("333");
expect(g.value).toEqual({"one": "111", "nested": {"two": "333"}});
});
});
describe("validator", () => {
it("should run the validator with the initial value (valid)", () => {
var g = new ControlGroup({"one": new Control('value', Validators.required)});
expect(g.valid).toEqual(true);
expect(g.errors).toEqual(null);
});
it("should run the validator with the initial value (invalid)", () => {
var one = new Control(null, Validators.required);
var g = new ControlGroup({"one": one});
expect(g.valid).toEqual(false);
expect(g.errors).toEqual({"required": [one]});
});
it("should run the validator with the value changes", () => {
var c = new Control(null, Validators.required);
var g = new ControlGroup({"one": c});
c.updateValue("some value");
expect(g.valid).toEqual(true);
expect(g.errors).toEqual(null);
});
});
describe("dirty", () => {
var c, g;
beforeEach(() => {
c = new Control('value');
g = new ControlGroup({"one": c});
});
it("should be false after creating a control", () => { expect(g.dirty).toEqual(false); });
it("should be false after changing the value of the control", () => {
c.markAsDirty();
expect(g.dirty).toEqual(true);
});
});
describe("optional components", () => {
describe("contains", () => {
var group;
beforeEach(() => {
group = new ControlGroup(
{
"required": new Control("requiredValue"),
"optional": new Control("optionalValue")
},
{"optional": false});
});
// rename contains into has
it("should return false when the component is not included",
() => { expect(group.contains("optional")).toEqual(false); })
it("should return false when there is no component with the given name",
() => { expect(group.contains("something else")).toEqual(false); });
it("should return true when the component is included", () => {
expect(group.contains("required")).toEqual(true);
group.include("optional");
expect(group.contains("optional")).toEqual(true);
});
});
it("should not include an inactive component into the group value", () => {
var group = new ControlGroup(
{"required": new Control("requiredValue"), "optional": new Control("optionalValue")},
{"optional": false});
expect(group.value).toEqual({"required": "requiredValue"});
group.include("optional");
expect(group.value).toEqual({"required": "requiredValue", "optional": "optionalValue"});
});
it("should not run Validators on an inactive component", () => {
var group = new ControlGroup(
{
"required": new Control("requiredValue", Validators.required),
"optional": new Control("", Validators.required)
},
{"optional": false});
expect(group.valid).toEqual(true);
group.include("optional");
expect(group.valid).toEqual(false);
});
describe("valueChanges", () => {
var g, c1, c2;
beforeEach(() => {
c1 = new Control("old1");
c2 = new Control("old2");
g = new ControlGroup({"one": c1, "two": c2}, {"two": true});
});
it("should fire an event after the value has been updated",
inject([AsyncTestCompleter], (async) => {
ObservableWrapper.subscribe(g.valueChanges, (value) => {
expect(g.value).toEqual({'one': 'new1', 'two': 'old2'});
expect(value).toEqual({'one': 'new1', 'two': 'old2'});
async.done();
});
c1.updateValue("new1");
}));
it("should fire an event after the control's observable fired an event",
inject([AsyncTestCompleter], (async) => {
var controlCallbackIsCalled = false;
ObservableWrapper.subscribe(c1.valueChanges,
(value) => { controlCallbackIsCalled = true; });
ObservableWrapper.subscribe(g.valueChanges, (value) => {
expect(controlCallbackIsCalled).toBe(true);
async.done();
});
c1.updateValue("new1");
}));
it("should fire an event when a control is excluded",
inject([AsyncTestCompleter], (async) => {
ObservableWrapper.subscribe(g.valueChanges, (value) => {
expect(value).toEqual({'one': 'old1'});
async.done();
});
g.exclude("two");
}));
it("should fire an event when a control is included",
inject([AsyncTestCompleter], (async) => {
g.exclude("two");
ObservableWrapper.subscribe(g.valueChanges, (value) => {
expect(value).toEqual({'one': 'old1', 'two': 'old2'});
async.done();
});
g.include("two");
}));
it("should fire an event every time a control is updated",
inject([AsyncTestCompleter], (async) => {
var loggedValues = [];
ObservableWrapper.subscribe(g.valueChanges, (value) => {
loggedValues.push(value);
if (loggedValues.length == 2) {
expect(loggedValues)
.toEqual([{"one": "new1", "two": "old2"}, {"one": "new1", "two": "new2"}]);
async.done();
}
});
c1.updateValue("new1");
c2.updateValue("new2");
}));
xit("should not fire an event when an excluded control is updated",
inject([AsyncTestCompleter], (async) => {
// hard to test without hacking zones
}));
});
describe("getError", () => {
it("should return the error when it is present", () => {
var c = new Control("", Validators.required);
var g = new ControlGroup({"one": c});
expect(c.getError("required")).toEqual(true);
expect(g.getError("required", ["one"])).toEqual(true);
});
it("should return null otherwise", () => {
var c = new Control("not empty", Validators.required);
var g = new ControlGroup({"one": c});
expect(c.getError("invalid")).toEqual(null);
expect(g.getError("required", ["one"])).toEqual(null);
expect(g.getError("required", ["invalid"])).toEqual(null);
});
});
});
});
describe("ControlArray", () => {
describe("adding/removing", () => {
var a: ControlArray;
var c1, c2, c3;
beforeEach(() => {
a = new ControlArray([]);
c1 = new Control(1);
c2 = new Control(2);
c3 = new Control(3);
});
it("should support pushing", () => {
a.push(c1);
expect(a.length).toEqual(1);
expect(a.controls).toEqual([c1]);
});
it("should support removing", () => {
a.push(c1);
a.push(c2);
a.push(c3);
a.removeAt(1);
expect(a.controls).toEqual([c1, c3]);
});
it("should support inserting", () => {
a.push(c1);
a.push(c3);
a.insert(1, c2);
expect(a.controls).toEqual([c1, c2, c3]);
});
});
describe("value", () => {
it("should be the reduced value of the child controls", () => {
var a = new ControlArray([new Control(1), new Control(2)]);
expect(a.value).toEqual([1, 2]);
});
it("should be an empty array when there are no child controls", () => {
var a = new ControlArray([]);
expect(a.value).toEqual([]);
});
});
describe("validator", () => {
it("should run the validator with the initial value (valid)", () => {
var a = new ControlArray(
[new Control(1, Validators.required), new Control(2, Validators.required)]);
expect(a.valid).toBe(true);
expect(a.errors).toBe(null);
});
it("should run the validator with the initial value (invalid)", () => {
var a = new ControlArray([
new Control(1, Validators.required),
new Control(null, Validators.required),
new Control(2, Validators.required)
]);
expect(a.valid).toBe(false);
expect(a.errors).toEqual({"required": [a.controls[1]]});
});
it("should run the validator when the value changes", () => {
var a = new ControlArray([]);
var c = new Control(null, Validators.required);
a.push(c);
expect(a.valid).toBe(false);
c.updateValue("some value");
expect(a.valid).toBe(true);
expect(a.errors).toBe(null);
});
});
describe("dirty", () => {
var c: Control;
var a: ControlArray;
beforeEach(() => {
c = new Control('value');
a = new ControlArray([c]);
});
it("should be false after creating a control", () => { expect(a.dirty).toEqual(false); });
it("should be false after changing the value of the control", () => {
c.markAsDirty();
expect(a.dirty).toEqual(true);
});
});
describe("valueChanges", () => {
var a: ControlArray;
var c1, c2;
beforeEach(() => {
c1 = new Control("old1");
c2 = new Control("old2");
a = new ControlArray([c1, c2]);
});
it("should fire an event after the value has been updated",
inject([AsyncTestCompleter], (async) => {
ObservableWrapper.subscribe(a.valueChanges, (value) => {
expect(a.value).toEqual(['new1', 'old2']);
expect(value).toEqual(['new1', 'old2']);
async.done();
});
c1.updateValue("new1");
}));
it("should fire an event after the control's observable fired an event",
inject([AsyncTestCompleter], (async) => {
var controlCallbackIsCalled = false;
ObservableWrapper.subscribe(c1.valueChanges,
(value) => { controlCallbackIsCalled = true; });
ObservableWrapper.subscribe(a.valueChanges, (value) => {
expect(controlCallbackIsCalled).toBe(true);
async.done();
});
c1.updateValue("new1");
}));
it("should fire an event when a control is removed",
inject([AsyncTestCompleter], (async) => {
ObservableWrapper.subscribe(a.valueChanges, (value) => {
expect(value).toEqual(['old1']);
async.done();
});
a.removeAt(1);
}));
it("should fire an event when a control is added", inject([AsyncTestCompleter], (async) => {
a.removeAt(1);
ObservableWrapper.subscribe(a.valueChanges, (value) => {
expect(value).toEqual(['old1', 'old2']);
async.done();
});
a.push(c2);
}));
});
});
describe("find", () => {
it("should return null when path is null", () => {
var g = new ControlGroup({});
expect(g.find(null)).toEqual(null);
});
it("should return null when path is empty", () => {
var g = new ControlGroup({});
expect(g.find([])).toEqual(null);
});
it("should return null when path is invalid", () => {
var g = new ControlGroup({});
expect(g.find(["one", "two"])).toEqual(null);
});
it("should return a child of a control group", () => {
var g = new ControlGroup(
{"one": new Control("111"), "nested": new ControlGroup({"two": new Control("222")})});
expect(g.find(["nested", "two"]).value).toEqual("222");
expect(g.find(["one"]).value).toEqual("111");
expect(g.find("nested/two").value).toEqual("222");
expect(g.find("one").value).toEqual("111");
});
it("should return an element of an array", () => {
var g = new ControlGroup({"array": new ControlArray([new Control("111")])});
expect(g.find(["array", 0]).value).toEqual("111");
});
});
});
}
| modules/angular2/test/forms/model_spec.ts | 1 | https://github.com/angular/angular/commit/5b597de18cb4a29f78dc3a576b9c6e45bff18ecf | [
0.0014095891965553164,
0.00021482884767465293,
0.00016507646068930626,
0.00017043473781086504,
0.0002140761644113809
] |
{
"id": 1,
"code_window": [
" lifecycle: [LifecycleEvent.onChange],\n",
" exportAs: 'form'\n",
"})\n",
"export class NgModel extends NgControl {\n",
" _control = new Control(\"\");\n",
" _added = false;\n",
" update = new EventEmitter();\n",
" model: any;\n",
" viewModel: any;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" _control = new Control();\n"
],
"file_path": "modules/angular2/src/forms/directives/ng_model.ts",
"type": "replace",
"edit_start_line_idx": 38
} | library bar.ng_deps.dart;
import 'bar.dart';
import 'package:angular2/src/reflection/reflection.dart' as _ngRef;
import 'package:angular2/src/core/annotations_impl/annotations.dart';
export 'foo.dart';
var _visited = false;
void initReflector() {
if (_visited) return;
_visited = true;
_ngRef.reflector
..registerType(MyComponent, {
'factory': () => new MyComponent(),
'parameters': const [],
'annotations': const [const Component(selector: '[soup]')]
});
}
| modules/angular2/test/transform/directive_linker/simple_export_files/bar.ng_deps.dart | 0 | https://github.com/angular/angular/commit/5b597de18cb4a29f78dc3a576b9c6e45bff18ecf | [
0.00017524942813906819,
0.0001733619865262881,
0.000171474544913508,
0.0001733619865262881,
0.0000018874416127800941
] |
{
"id": 1,
"code_window": [
" lifecycle: [LifecycleEvent.onChange],\n",
" exportAs: 'form'\n",
"})\n",
"export class NgModel extends NgControl {\n",
" _control = new Control(\"\");\n",
" _added = false;\n",
" update = new EventEmitter();\n",
" model: any;\n",
" viewModel: any;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" _control = new Control();\n"
],
"file_path": "modules/angular2/src/forms/directives/ng_model.ts",
"type": "replace",
"edit_start_line_idx": 38
} | import {
describe,
ddescribe,
it,
iit,
xit,
xdescribe,
expect,
beforeEach,
el,
IS_DARTIUM
} from 'angular2/test_lib';
import {ProtoViewBuilder} from 'angular2/src/render/dom/view/proto_view_builder';
import {ASTWithSource, AST} from 'angular2/change_detection';
import {PropertyBindingType, ViewType} from 'angular2/src/render/api';
import {DOM} from 'angular2/src/dom/dom_adapter';
export function main() {
function emptyExpr() { return new ASTWithSource(new AST(), 'empty', 'empty'); }
describe('ProtoViewBuilder', () => {
var builder;
beforeEach(
() => { builder = new ProtoViewBuilder(DOM.createTemplate(''), ViewType.EMBEDDED); });
if (!IS_DARTIUM) {
describe('verification of properties', () => {
it('should throw for unknown properties', () => {
builder.bindElement(el('<div/>')).bindProperty('unknownProperty', emptyExpr());
expect(() => builder.build())
.toThrowError(
`Can't bind to 'unknownProperty' since it isn't a known property of the '<div>' element and there are no matching directives with a corresponding property`);
});
it('should allow unknown properties if a directive uses it', () => {
var binder = builder.bindElement(el('<div/>'));
binder.bindDirective(0).bindProperty('someDirProperty', emptyExpr(), 'directiveProperty');
binder.bindProperty('directiveProperty', emptyExpr());
expect(() => builder.build()).not.toThrow();
});
it('should allow unknown properties on custom elements', () => {
var binder = builder.bindElement(el('<some-custom/>'));
binder.bindProperty('unknownProperty', emptyExpr());
expect(() => builder.build()).not.toThrow();
});
it('should throw for unknown properties on custom elements if there is an ng component', () => {
var binder = builder.bindElement(el('<some-custom/>'));
binder.bindProperty('unknownProperty', emptyExpr());
binder.setComponentId('someComponent');
expect(() => builder.build())
.toThrowError(
`Can't bind to 'unknownProperty' since it isn't a known property of the '<some-custom>' element and there are no matching directives with a corresponding property`);
});
});
} else {
describe('verification of properties', () => {
// TODO(tbosch): This is just a temporary test that makes sure that the dart server and
// dart browser is in sync. Change this to "not contains notifyBinding"
// when https://github.com/angular/angular/issues/3019 is solved.
it('should throw for unknown properties', () => {
builder.bindElement(el('<div/>')).bindProperty('unknownProperty', emptyExpr());
expect(() => builder.build()).not.toThrow();
});
});
}
describe('property normalization', () => {
it('should normalize "innerHtml" to "innerHTML"', () => {
builder.bindElement(el('<div/>')).bindProperty('innerHtml', emptyExpr());
var pv = builder.build();
expect(pv.elementBinders[0].propertyBindings[0].property).toEqual('innerHTML');
});
it('should normalize "tabindex" to "tabIndex"', () => {
builder.bindElement(el('<div/>')).bindProperty('tabindex', emptyExpr());
var pv = builder.build();
expect(pv.elementBinders[0].propertyBindings[0].property).toEqual('tabIndex');
});
it('should normalize "readonly" to "readOnly"', () => {
builder.bindElement(el('<input/>')).bindProperty('readonly', emptyExpr());
var pv = builder.build();
expect(pv.elementBinders[0].propertyBindings[0].property).toEqual('readOnly');
});
});
describe('property binding types', () => {
it('should detect property names', () => {
builder.bindElement(el('<div/>')).bindProperty('tabindex', emptyExpr());
var pv = builder.build();
expect(pv.elementBinders[0].propertyBindings[0].type).toEqual(PropertyBindingType.PROPERTY);
});
it('should detect attribute names', () => {
builder.bindElement(el('<div/>')).bindProperty('attr.someName', emptyExpr());
var pv = builder.build();
expect(pv.elementBinders[0].propertyBindings[0].type)
.toEqual(PropertyBindingType.ATTRIBUTE);
});
it('should detect class names', () => {
builder.bindElement(el('<div/>')).bindProperty('class.someName', emptyExpr());
var pv = builder.build();
expect(pv.elementBinders[0].propertyBindings[0].type).toEqual(PropertyBindingType.CLASS);
});
it('should detect style names', () => {
builder.bindElement(el('<div/>')).bindProperty('style.someName', emptyExpr());
var pv = builder.build();
expect(pv.elementBinders[0].propertyBindings[0].type).toEqual(PropertyBindingType.STYLE);
});
it('should detect style units', () => {
builder.bindElement(el('<div/>')).bindProperty('style.someName.someUnit', emptyExpr());
var pv = builder.build();
expect(pv.elementBinders[0].propertyBindings[0].unit).toEqual('someUnit');
});
});
});
}
| modules/angular2/test/render/dom/view/proto_view_builder_spec.ts | 0 | https://github.com/angular/angular/commit/5b597de18cb4a29f78dc3a576b9c6e45bff18ecf | [
0.00017975132504943758,
0.00017601151193957776,
0.00017011877207551152,
0.00017647359345573932,
0.000002302537723153364
] |
{
"id": 1,
"code_window": [
" lifecycle: [LifecycleEvent.onChange],\n",
" exportAs: 'form'\n",
"})\n",
"export class NgModel extends NgControl {\n",
" _control = new Control(\"\");\n",
" _added = false;\n",
" update = new EventEmitter();\n",
" model: any;\n",
" viewModel: any;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" _control = new Control();\n"
],
"file_path": "modules/angular2/src/forms/directives/ng_model.ts",
"type": "replace",
"edit_start_line_idx": 38
} | <a name"2.0.0-alpha.31"></a>
### 2.0.0-alpha.31 (2015-07-14)
#### Bug Fixes
* **build:**
* remove the travis deploy step, which is broken. ([206c9bdd](https://github.com/angular/angular/commit/206c9bdd))
* reduce the deploy upload. ([4264bd3b](https://github.com/angular/angular/commit/4264bd3b))
* clang-format ([df877a7d](https://github.com/angular/angular/commit/df877a7d))
* **compiler:** keep `DOM.hasProperty` in sync between browser and transformer. ([b3a763a7](https://github.com/angular/angular/commit/b3a763a7), closes [#2984](https://github.com/angular/angular/issues/2984), [#2981](https://github.com/angular/angular/issues/2981))
* **css_shim:** fixes multiple uses of polyfill-unscoped-rule. ([749d0432](https://github.com/angular/angular/commit/749d0432))
* **di:**
* removed default visibility ([04baa46e](https://github.com/angular/angular/commit/04baa46e))
* do not use exceptions to detect if reflection is enabled ([a6210466](https://github.com/angular/angular/commit/a6210466))
* hostInjector and viewInjector support nested arrays ([0ed5dd0d](https://github.com/angular/angular/commit/0ed5dd0d))
* **example:** add missing todo ([1427d73b](https://github.com/angular/angular/commit/1427d73b))
* **package.json:** move some deps into dev deps. ([546a8f92](https://github.com/angular/angular/commit/546a8f92), closes [#2448](https://github.com/angular/angular/issues/2448))
* **router:**
* export lifecycle hooks in bundle ([97ef1c27](https://github.com/angular/angular/commit/97ef1c27))
* fix broken `HashLocationStrategy` string issue for dart ([d6dadc6e](https://github.com/angular/angular/commit/d6dadc6e))
* ensure that page refresh with hash URLs works ([c177d889](https://github.com/angular/angular/commit/c177d889), closes [#2920](https://github.com/angular/angular/issues/2920))
* **transform:** handle multiple interfaces in directive processor ([ac50ffca](https://github.com/angular/angular/commit/ac50ffca), closes [#2941](https://github.com/angular/angular/issues/2941))
* **transformer:**
* Event getters now use property name not event name ([cf103de4](https://github.com/angular/angular/commit/cf103de4))
* fix 'pub build' in examples ([62589293](https://github.com/angular/angular/commit/62589293))
* **tsconfig:** target should be lower case ([0792f1a7](https://github.com/angular/angular/commit/0792f1a7), closes [#2938](https://github.com/angular/angular/issues/2938))
#### Features
* upgrade clang-format to v1.0.28. ([45994a53](https://github.com/angular/angular/commit/45994a53))
* **build:** Allow building in windows without admin priviledges ([f1f57843](https://github.com/angular/angular/commit/f1f57843), closes [#2873](https://github.com/angular/angular/issues/2873))
* **forms:** changed all form directives to have basic control attributes ([3f7ebde0](https://github.com/angular/angular/commit/3f7ebde0))
* **license:** include license files in dev and dev.sfx bundles ([1eab4f5f](https://github.com/angular/angular/commit/1eab4f5f))
* **pipes:**
* add static append method to Pipes ([1eebceab](https://github.com/angular/angular/commit/1eebceab), closes [#2901](https://github.com/angular/angular/issues/2901))
* add date pipe ([b716046b](https://github.com/angular/angular/commit/b716046b), closes [#2877](https://github.com/angular/angular/issues/2877))
* add number (decimal, percent, currency) pipes ([3143d188](https://github.com/angular/angular/commit/3143d188))
* **query:** initial implementation of view query. ([7ee6963f](https://github.com/angular/angular/commit/7ee6963f), closes [#1935](https://github.com/angular/angular/issues/1935))
* **router:**
* introduce matrix params ([5677bf73](https://github.com/angular/angular/commit/5677bf73), closes [#2774](https://github.com/angular/angular/issues/2774), [#2989](https://github.com/angular/angular/issues/2989))
* lifecycle hooks ([a9a552c1](https://github.com/angular/angular/commit/a9a552c1), closes [#2640](https://github.com/angular/angular/issues/2640))
* **test:** add test bundle ([71c65b47](https://github.com/angular/angular/commit/71c65b47))
* **zone:** add "on event done" zone hook ([0e28297e](https://github.com/angular/angular/commit/0e28297e))
#### Breaking Changes
* Directives will use the Unbounded visibility by default, whereas before the change they used Self
([04baa46e](https://github.com/angular/angular/commit/04baa46e))
* This change renames all instances of PipeRegistry to Pipes.
As part of this change, the former "defaultPipes" export is
now a Pipes instance, instead of a map. The map that was previously
called "defaultPipes" no longer exists, but may be accessed via
defaultPipes.config.
([9a70f84e](https://github.com/angular/angular/commit/9a70f84e))
* We export InjectMetadata instead of InjectAnnotation
([b54e7214](https://github.com/angular/angular/commit/b54e7214))
<a name"2.0.0-alpha.30"></a>
### 2.0.0-alpha.30 (2015-07-07)
#### Bug Fixes
* handle errors w/o file information. ([e69af1a3](https://github.com/angular/angular/commit/e69af1a3))
* **.d.ts:** correct ComponentAnnotation inheritance ([12a427e1](https://github.com/angular/angular/commit/12a427e1), closes [#2356](https://github.com/angular/angular/issues/2356))
* **Http:** add support for headers ([883b5064](https://github.com/angular/angular/commit/883b5064))
* **angular2.d.ts:** show typing for Component, etc ([b10d7a2e](https://github.com/angular/angular/commit/b10d7a2e))
* **change_detection:**
* throw ChangeDetectionError in JIT mode ([c2efa23e](https://github.com/angular/angular/commit/c2efa23e))
* do not coalesce records with different directive indices ([d2774421](https://github.com/angular/angular/commit/d2774421))
* **compiler:** detect and strip data- prefix from bindings ([cd65fc2a](https://github.com/angular/angular/commit/cd65fc2a), closes [#2687](https://github.com/angular/angular/issues/2687), [#2719](https://github.com/angular/angular/issues/2719))
* **di:** injecting null causes a cyclic dependency ([d1393b05](https://github.com/angular/angular/commit/d1393b05))
* **forms:** Remove cyclic dependency ([e5405e4b](https://github.com/angular/angular/commit/e5405e4b), closes [#2856](https://github.com/angular/angular/issues/2856))
* **router:**
* allow generating links with numeric params ([d828664d](https://github.com/angular/angular/commit/d828664d))
* child routers should delegate navigation to the root router ([1c94c32f](https://github.com/angular/angular/commit/1c94c32f))
* **transformer:**
* Support prefixed annotations in the transformer. ([9e1158de](https://github.com/angular/angular/commit/9e1158de))
* Put paramater data in the same order as the reflected version. ([2b45bd2a](https://github.com/angular/angular/commit/2b45bd2a))
* Fix string interpolation for bindings. ([311b4772](https://github.com/angular/angular/commit/311b4772))
#### Features
* upgrade t2dart to 0.6.8. ([d381c5fc](https://github.com/angular/angular/commit/d381c5fc))
* **NgStyle:** Export NgStyle in angular2/directives ([edf5053b](https://github.com/angular/angular/commit/edf5053b), closes [#2878](https://github.com/angular/angular/issues/2878))
* **router:** support deep-linking to siblings ([286a249a](https://github.com/angular/angular/commit/286a249a), closes [#2807](https://github.com/angular/angular/issues/2807))
* **transformer:** Support @Injectable() on static functions ([7986e7ce](https://github.com/angular/angular/commit/7986e7ce))
* **typings:** mark void methods in angular2.d.ts ([a56d33d7](https://github.com/angular/angular/commit/a56d33d7))
<a name"2.0.0-alpha.29"></a>
### 2.0.0-alpha.29 (2015-07-01)
#### Bug Fixes
* export top-level pipe factories as const ([393f703a](https://github.com/angular/angular/commit/393f703a))
* **Router:** mark Pipeline and RouteRegistry as Injectable ([eea989be](https://github.com/angular/angular/commit/eea989be))
* **build:**
* Reduce rx typings to what we actually require. ([8bab6dd2](https://github.com/angular/angular/commit/8bab6dd2))
* add missing return types now enforced by linter ([44891996](https://github.com/angular/angular/commit/44891996))
* fix paths in `test.typings` task ([1c8a5896](https://github.com/angular/angular/commit/1c8a5896))
* **bundle:**
* don’t bundle traceur/reflect into benchpress - amended change ([d629ed7d](https://github.com/angular/angular/commit/d629ed7d))
* don’t bundle traceur/reflect into benchpress ([da4de21f](https://github.com/angular/angular/commit/da4de21f))
* **change detectors:** Fix deduping of protos in transformed dart mode. ([73a939e7](https://github.com/angular/angular/commit/73a939e7))
* **compiler:** don't trigger duplicated directives ([0598226e](https://github.com/angular/angular/commit/0598226e), closes [#2756](https://github.com/angular/angular/issues/2756), [#2568](https://github.com/angular/angular/issues/2568))
* **docs:**
* to run js test 'gulp docs' is needed ([3e650378](https://github.com/angular/angular/commit/3e650378), closes [#2762](https://github.com/angular/angular/issues/2762))
* link to clang-format ([f1cf5298](https://github.com/angular/angular/commit/f1cf5298))
* **dynamic_component_loader:** check whether the dynamically loaded component has already been destroyed ([d6cef88d](https://github.com/angular/angular/commit/d6cef88d), closes [#2748](https://github.com/angular/angular/issues/2748), [#2767](https://github.com/angular/angular/issues/2767))
* **transformer:**
* Add getters for `events`. ([5a21dc53](https://github.com/angular/angular/commit/5a21dc53))
* Don't hang on bad urls and log better errors ([d037c082](https://github.com/angular/angular/commit/d037c082))
* Fix annotation_matcher for NgForm directive. ([9c768501](https://github.com/angular/angular/commit/9c768501))
* **typings:** Minor issues preventing angular2.d.ts from working in TS 1.4. ([7a4a3c85](https://github.com/angular/angular/commit/7a4a3c85))
#### Features
* upgrade clang-format and gulp-clang-format. ([1f7296c0](https://github.com/angular/angular/commit/1f7296c0))
* **NgStyle:** add new NgStyle directive ([b50edfd1](https://github.com/angular/angular/commit/b50edfd1), closes [#2665](https://github.com/angular/angular/issues/2665))
* **async:** added PromiseWrapper.wrap ([b688dee4](https://github.com/angular/angular/commit/b688dee4))
* **benchpress:** initial support for firefox ([0949a4b0](https://github.com/angular/angular/commit/0949a4b0), closes [#2419](https://github.com/angular/angular/issues/2419))
* **build:** add tslint to the build. ([bc585f27](https://github.com/angular/angular/commit/bc585f27))
* **di:**
* removed app injector ([f0e962c5](https://github.com/angular/angular/commit/f0e962c5))
* changed InstantiationError to print the original stack ([eb0fd796](https://github.com/angular/angular/commit/eb0fd796))
* **facade:** add ListWrapper.toJSON method ([23350755](https://github.com/angular/angular/commit/23350755))
* **http:** refactor library to work in dart ([55bf0e55](https://github.com/angular/angular/commit/55bf0e55), closes [#2415](https://github.com/angular/angular/issues/2415))
* **lang:** added originalException and originalStack to BaseException ([56245c6a](https://github.com/angular/angular/commit/56245c6a))
* **pipes:**
* add limitTo pipe ([0b502588](https://github.com/angular/angular/commit/0b502588))
* support arguments in transform function ([600d53c6](https://github.com/angular/angular/commit/600d53c6))
* **router:** support deep-linking to anywhere in the app ([f66ce096](https://github.com/angular/angular/commit/f66ce096), closes [#2642](https://github.com/angular/angular/issues/2642))
* **transformers:** provide a flag to disable inlining views ([dcdd7306](https://github.com/angular/angular/commit/dcdd7306), closes [#2658](https://github.com/angular/angular/issues/2658))
#### Breaking Changes
*
THe appInjector property has been removed. Instead use viewInjector or hostInjector.
([f0e962c5](https://github.com/angular/angular/commit/f0e962c5))
* The Http module previously would return RxJS Observables from method calls
of the Http class. In order to support Dart, the module was refactored to
return the EventEmitter abstraction instead, which does not contain the same
combinators or subscription semantics as an RxJS Observable. However, the
EventEmitter provides a toRx() method which will return an RxJS Subject,
providing the same subscription and combinator conveniences as were
available prior to this refactor.
This is temporary, until issue #2794 is resolved, when Observables will
again be returned directly from Http class methods.
([34eaf65a](https://github.com/angular/angular/commit/34eaf65a))
* HttpFactory is no longer available.
This factory provided a function alternative to the `request` method of the
Http class, but added no real value. The additional factory required an
additional IHttp interface, an odd way to inject while preserving type information
(`@Inject(HttpFactory) http:IHttp`), and required additional documentation in the
http module.
Closes #2564
([146dbf12](https://github.com/angular/angular/commit/146dbf12))
<a name"2.0.0-alpha.28"></a>
### 2.0.0-alpha.28 (2015-06-24)
#### Bug Fixes
* **ShadowDomStrategy:** always inline import rules ([1c4d233f](https://github.com/angular/angular/commit/1c4d233f), closes [#1694](https://github.com/angular/angular/issues/1694))
* **XHRImpl:** file:/// and IE9 bugs ([cd735c48](https://github.com/angular/angular/commit/cd735c48))
* **annotations:** swap DirectiveArgs & ComponentArgs ([dcc4bc27](https://github.com/angular/angular/commit/dcc4bc27))
* **benchmarks:** add waits for naive scrolling benchmark to ensure loading ([d8929c1d](https://github.com/angular/angular/commit/d8929c1d), closes [#1706](https://github.com/angular/angular/issues/1706))
* **benchpress:** do not throw on unkown frame timestamp event ([ed3af5f7](https://github.com/angular/angular/commit/ed3af5f7), closes [#2622](https://github.com/angular/angular/issues/2622))
* **change detection:** preserve memoized results from pure functions ([5beaf6d7](https://github.com/angular/angular/commit/5beaf6d7))
* **compiler:** make text interpolation more robust ([9d4111d6](https://github.com/angular/angular/commit/9d4111d6), closes [#2591](https://github.com/angular/angular/issues/2591))
* **docs:** Fix docs for Directive.compileChildren ([9700e806](https://github.com/angular/angular/commit/9700e806))
* **injectors:** sync injector tree with dom element tree. ([d800d2f5](https://github.com/angular/angular/commit/d800d2f5))
* **parse5:** do not try to insert empty text node ([0a2f6ddc](https://github.com/angular/angular/commit/0a2f6ddc))
* **render:** fix failing tests in dynamic_component_loader.ts ([6149ce28](https://github.com/angular/angular/commit/6149ce28))
* **router:** return promise with error handler ([bc798b18](https://github.com/angular/angular/commit/bc798b18))
* **transformer:** Throw unimplemented errors in HtmlAdapter. ([f9d72bd8](https://github.com/angular/angular/commit/f9d72bd8), closes [#2624](https://github.com/angular/angular/issues/2624), [#2627](https://github.com/angular/angular/issues/2627))
* **views:** remove dynamic component views, free host views, free embedded views ([5dee8e26](https://github.com/angular/angular/commit/5dee8e26), closes [#2472](https://github.com/angular/angular/issues/2472), [#2339](https://github.com/angular/angular/issues/2339))
#### Features
* update clang-format to 1.0.21. ([254e58c2](https://github.com/angular/angular/commit/254e58c2))
* remove MapWrapper.clear(). ([94136201](https://github.com/angular/angular/commit/94136201))
* remove MapWrapper.contains(). ([dfd30910](https://github.com/angular/angular/commit/dfd30910))
* remove MapWrapper.create()/get()/set(). ([be7ac9fd](https://github.com/angular/angular/commit/be7ac9fd))
* add constructors without type arguments. ([35e882e7](https://github.com/angular/angular/commit/35e882e7))
* upgrade ts2dart to 0.6.4. ([58b38c92](https://github.com/angular/angular/commit/58b38c92))
* **CSSClass:** add support for string and array expresions ([8c993dca](https://github.com/angular/angular/commit/8c993dca), closes [#2025](https://github.com/angular/angular/issues/2025))
* **compiler:** detect dangling property bindings ([d7b9345b](https://github.com/angular/angular/commit/d7b9345b), closes [#2598](https://github.com/angular/angular/issues/2598))
* **element_injector:** support multiple injectables with the same token ([c899b0a7](https://github.com/angular/angular/commit/c899b0a7))
* **host:** limits host properties to renames ([92ffc465](https://github.com/angular/angular/commit/92ffc465))
* **mock:** add mock module and bundle ([29323777](https://github.com/angular/angular/commit/29323777), closes [#2325](https://github.com/angular/angular/issues/2325))
* **query:** added support for querying by var bindings ([b0e2ebda](https://github.com/angular/angular/commit/b0e2ebda))
* **render:** don’t use the reflector for setting properties ([0a51ccbd](https://github.com/angular/angular/commit/0a51ccbd), closes [#2637](https://github.com/angular/angular/issues/2637))
* **router:**
* add support for hash-based location ([a67f2314](https://github.com/angular/angular/commit/a67f2314), closes [#2555](https://github.com/angular/angular/issues/2555))
* enforce usage of ... syntax for parent to child component routes ([2d2ae9b8](https://github.com/angular/angular/commit/2d2ae9b8))
* **transformers:** inline styleUrls to view directive ([f2ef90b2](https://github.com/angular/angular/commit/f2ef90b2), closes [#2566](https://github.com/angular/angular/issues/2566))
* **typings:** add typing specs ([24646e7e](https://github.com/angular/angular/commit/24646e7e))
#### Breaking Changes
* compiler will throw on binding to non-existing properties.
Till now it was possible to have a binding to a non-existing property,
ex.: `<div [foo]="exp">`. From now on this is compilation error - any
property binding needs to have at least one associated property:
eaither on an HTML element or on any directive associated with a
given element (directives' properites need to be declared using the
`properties` field in the `@Directive` / `@Component` annotation).
Closes #2598
([d7b9345b](https://github.com/angular/angular/commit/d7b9345b))
*
This PR remove an ability to use pipes in the properties config. Instead, inject the pipe registry.
([20a8f0db](https://github.com/angular/angular/commit/20a8f0db))
<a name"2.0.0-alpha.27"></a>
### 2.0.0-alpha.27 (2015-06-16)
#### Bug Fixes
* makes NgModel work in strict mode ([eb3586d7](https://github.com/angular/angular/commit/eb3586d7))
* Class factory now adds annotations ([bc9e482b](https://github.com/angular/angular/commit/bc9e482b))
* improve type safety by typing `refs`. ([4ae7df27](https://github.com/angular/angular/commit/4ae7df27))
* improve type of TreeNode.children. ([c3c2ad14](https://github.com/angular/angular/commit/c3c2ad14))
* add types for ts2dart's façade handling. ([f3d74185](https://github.com/angular/angular/commit/f3d74185))
* rename FORWARD_REF to forwardRef in the Angular code base. ([c4ecbf0a](https://github.com/angular/angular/commit/c4ecbf0a))
* declare var global. ([13466604](https://github.com/angular/angular/commit/13466604))
* Improve error message on missing dependency ([2ccc65d7](https://github.com/angular/angular/commit/2ccc65d7))
* compare strings with StringWrapper.equals ([633cf636](https://github.com/angular/angular/commit/633cf636))
* corrected var/# parsing in template ([a4183971](https://github.com/angular/angular/commit/a4183971), closes [#2084](https://github.com/angular/angular/issues/2084))
* increase the stack frame size for tests ([ab8eb4f6](https://github.com/angular/angular/commit/ab8eb4f6))
* include error message in the stack trace ([8d081ea7](https://github.com/angular/angular/commit/8d081ea7))
* **Compiler:** fix text nodes after content tags ([d599fd34](https://github.com/angular/angular/commit/d599fd34), closes [#2095](https://github.com/angular/angular/issues/2095))
* **DirectiveMetadata:** add support for events, changeDetection ([b4e82b8b](https://github.com/angular/angular/commit/b4e82b8b))
* **JsonPipe:** always transform to json ([e77710a3](https://github.com/angular/angular/commit/e77710a3))
* **Parser:** Parse pipes in arguments ([f9745327](https://github.com/angular/angular/commit/f9745327), closes [#1680](https://github.com/angular/angular/issues/1680))
* **ShadowDom:** fix emulation integration spec to test all 3 strategies ([6e385154](https://github.com/angular/angular/commit/6e385154), closes [#2546](https://github.com/angular/angular/issues/2546))
* **analzyer:** removed unused imports ([902759e1](https://github.com/angular/angular/commit/902759e1))
* **benchmarks:** Do not apply the angular transformer to e2e tests ([cee26826](https://github.com/angular/angular/commit/cee26826))
* **bootstrap:** temporary disable jit change detection because of a bug in handling pure functio ([9908def8](https://github.com/angular/angular/commit/9908def8))
* **broccoli:** ensure that inputTrees are stable ([928ec1c5](https://github.com/angular/angular/commit/928ec1c5))
* **build:**
* ensure that asset files are copied over to example directories ([60b97b27](https://github.com/angular/angular/commit/60b97b27))
* Minify files for angular2.min.js bundle ([76797dfb](https://github.com/angular/angular/commit/76797dfb))
* only pass ts files to ts2dart transpilation. ([b5431e4c](https://github.com/angular/angular/commit/b5431e4c))
* **bundle:** makes interfaces.ts non-empty when transpiled. ([83e99fc7](https://github.com/angular/angular/commit/83e99fc7))
* **change detect:** Fix bug in JIT change detectors ([e0fbd4b6](https://github.com/angular/angular/commit/e0fbd4b6))
* **ci:** remove non-existent gulp task from test_e2e_dart ([1cf807c3](https://github.com/angular/angular/commit/1cf807c3), closes [#2509](https://github.com/angular/angular/issues/2509))
* **dartfmt:** don't break win32 command line limit ([617d6931](https://github.com/angular/angular/commit/617d6931), closes [#2420](https://github.com/angular/angular/issues/2420), [#1875](https://github.com/angular/angular/issues/1875))
* **diffing-broccoli-plugin:** wrapped trees are always stable ([7611f92f](https://github.com/angular/angular/commit/7611f92f))
* **docs:**
* order class members in order of declaration ([ea27704e](https://github.com/angular/angular/commit/ea27704e), closes [#2569](https://github.com/angular/angular/issues/2569))
* update link paths in annotations ([dd23bab3](https://github.com/angular/angular/commit/dd23bab3), closes [#2475](https://github.com/angular/angular/issues/2475))
* ensure no duplicates in alias names of docs ([05d02fa9](https://github.com/angular/angular/commit/05d02fa9))
* Working generated angular2.d.ts ([7141c15e](https://github.com/angular/angular/commit/7141c15e))
* **dynamic_component_loader:**
* Fix for ts2dart issue ([bbfb4e1d](https://github.com/angular/angular/commit/bbfb4e1d))
* implemented dispose for dynamically-loaded components ([21dcfc89](https://github.com/angular/angular/commit/21dcfc89))
* **element_injector:** changed visibility rules to expose hostInjector of the component to its shadow d ([c51aef9f](https://github.com/angular/angular/commit/c51aef9f))
* **forms:**
* updated form examples to contain select elements ([c34cb014](https://github.com/angular/angular/commit/c34cb014))
* fixed the handling of the select element ([f1541e65](https://github.com/angular/angular/commit/f1541e65))
* fixed the selector of NgRequiredValidator ([35197acc](https://github.com/angular/angular/commit/35197acc))
* getError does not work without path ([a858f6ac](https://github.com/angular/angular/commit/a858f6ac))
* **life_cycle:** throw when recursively reentering LifeCycle.tick ([af35ab56](https://github.com/angular/angular/commit/af35ab56))
* **locals:** improved an error message ([4eb8c9b2](https://github.com/angular/angular/commit/4eb8c9b2))
* **ng_zone:** updated zone not to run onTurnDown when invoking run synchronously from onTurnDo ([15dab7c5](https://github.com/angular/angular/commit/15dab7c5))
* **npm:** update scripts and readme for npm packages. ([8923103c](https://github.com/angular/angular/commit/8923103c), closes [#2377](https://github.com/angular/angular/issues/2377))
* **router:**
* ensure that root URL redirect doesn't redirect non-root URLs ([73d15250](https://github.com/angular/angular/commit/73d15250), closes [#2221](https://github.com/angular/angular/issues/2221))
* rethrow exceptions ([5782f063](https://github.com/angular/angular/commit/5782f063), closes [#2391](https://github.com/angular/angular/issues/2391))
* avoid two slash values between the baseHref and the path ([cdc7b03e](https://github.com/angular/angular/commit/cdc7b03e))
* do not prepend the root URL with a starting slash ([e372cc77](https://github.com/angular/angular/commit/e372cc77))
* **selector:** select by attribute independent of value and order ([9bad70be](https://github.com/angular/angular/commit/9bad70be), closes [#2513](https://github.com/angular/angular/issues/2513))
* **shadow_dom:** moves the imported nodes into the correct location. ([92d56584](https://github.com/angular/angular/commit/92d56584))
* **shrinkwrap:** restore fsevents dependency ([833048f3](https://github.com/angular/angular/commit/833048f3), closes [#2511](https://github.com/angular/angular/issues/2511))
* **view:** local variables override local variables set by ng-for ([d8e27953](https://github.com/angular/angular/commit/d8e27953))
#### Features
* allow Type.annotations = Component(...).View(...) ([b2c66949](https://github.com/angular/angular/commit/b2c66949), closes [#2577](https://github.com/angular/angular/issues/2577))
* support decorator chaining and class creation in ES5 ([c3ae34f0](https://github.com/angular/angular/commit/c3ae34f0), closes [#2534](https://github.com/angular/angular/issues/2534))
* update ts2dart to 0.6.1. ([96137724](https://github.com/angular/angular/commit/96137724))
* adjust formatting for clang-format v1.0.19. ([a6e71239](https://github.com/angular/angular/commit/a6e71239))
* upgrade to clang-format v1.0.19. ([1c2abbc6](https://github.com/angular/angular/commit/1c2abbc6))
* **AstTranformer:** add support for missing nodes ([da60381c](https://github.com/angular/angular/commit/da60381c))
* **BaseRequestOptions:** add merge method to make copies of options ([93596dff](https://github.com/angular/angular/commit/93596dff))
* **Directive:** Have a single Directive.host which mimics HTML ([f3b49378](https://github.com/angular/angular/commit/f3b49378), closes [#2268](https://github.com/angular/angular/issues/2268))
* **ElementInjector:** throw if multiple directives define the same host injectable ([6a6b43de](https://github.com/angular/angular/commit/6a6b43de))
* **Events:** allow a different event vs field name ([29c72abc](https://github.com/angular/angular/commit/29c72abc), closes [#2272](https://github.com/angular/angular/issues/2272), [#2344](https://github.com/angular/angular/issues/2344))
* **FakeAsync:** check pending timers at the end of fakeAsync in Dart ([53694eb6](https://github.com/angular/angular/commit/53694eb6))
* **Http:** add Http class ([b68e561c](https://github.com/angular/angular/commit/b68e561c), closes [#2530](https://github.com/angular/angular/issues/2530))
* **Parser:**
* support if statements in actions ([7d328799](https://github.com/angular/angular/commit/7d328799), closes [#2022](https://github.com/angular/angular/issues/2022))
* implement Unparser ([331a051e](https://github.com/angular/angular/commit/331a051e), closes [#1949](https://github.com/angular/angular/issues/1949), [#2395](https://github.com/angular/angular/issues/2395))
* **View:** add support for styleUrls and styles ([ac3e624d](https://github.com/angular/angular/commit/ac3e624d), closes [#2382](https://github.com/angular/angular/issues/2382))
* **benchpress:**
* more smoothness metrics ([35589a6b](https://github.com/angular/angular/commit/35589a6b))
* add mean frame time metric ([6834c499](https://github.com/angular/angular/commit/6834c499), closes [#2474](https://github.com/angular/angular/issues/2474))
* **broccoli:**
* improve merge-trees plugin and add "overwrite" option ([dc8dac7c](https://github.com/angular/angular/commit/dc8dac7c))
* add diffing MergeTrees plugin ([4ee3fdaf](https://github.com/angular/angular/commit/4ee3fdaf), closes [#1815](https://github.com/angular/angular/issues/1815), [#2064](https://github.com/angular/angular/issues/2064))
* **build:** add `test.unit.dartvm` for a faster roundtrip of dartvm tests ([46eeee6b](https://github.com/angular/angular/commit/46eeee6b))
* **change detect:** Throw on attempts to use dehydrated detector ([b6e95bb9](https://github.com/angular/angular/commit/b6e95bb9))
* **diffing-broccoli-plugin:** support multiple inputTrees ([41ae8e76](https://github.com/angular/angular/commit/41ae8e76), closes [#1815](https://github.com/angular/angular/issues/1815), [#2064](https://github.com/angular/angular/issues/2064))
* **e2e:** added e2e tests for forms ([552d1ed6](https://github.com/angular/angular/commit/552d1ed6))
* **facade:** add isMap method ([548f3dd5](https://github.com/angular/angular/commit/548f3dd5))
* **forms:**
* set exportAs to form for all form related directives ([e7e82cbe](https://github.com/angular/angular/commit/e7e82cbe))
* export validator directives as part of formDirectives ([73bce402](https://github.com/angular/angular/commit/73bce402))
* changed forms to capture submit events and fires synthetic ng-submit events ([5fc23cae](https://github.com/angular/angular/commit/5fc23cae))
* added hasError and getError methods to all controls ([1a4d2374](https://github.com/angular/angular/commit/1a4d2374))
* **forms.ts:** formInjectables with FormBuilder ([a6cb86ba](https://github.com/angular/angular/commit/a6cb86ba), closes [#2367](https://github.com/angular/angular/issues/2367))
* **http:** add basic http service ([21568106](https://github.com/angular/angular/commit/21568106), closes [#2028](https://github.com/angular/angular/issues/2028))
* **query:**
* notify on changes ([5bfcca2d](https://github.com/angular/angular/commit/5bfcca2d))
* adds support for descendants and more list apis. ([355ab5b3](https://github.com/angular/angular/commit/355ab5b3))
* **router:**
* allow configuring app base href via token ([cab1d0ef](https://github.com/angular/angular/commit/cab1d0ef))
* add routing to async components ([cd95e078](https://github.com/angular/angular/commit/cd95e078))
* **transform:** update for Directive.host ([591f742d](https://github.com/angular/angular/commit/591f742d))
* **transformers:** updated transformers ([e5419feb](https://github.com/angular/angular/commit/e5419feb))
* **view:** added support for exportAs, so any directive can be assigned to a variable ([69b75b7f](https://github.com/angular/angular/commit/69b75b7f))
#### Breaking Changes
* By default Query only queries direct children.
([355ab5b3](https://github.com/angular/angular/commit/355ab5b3))
*
Before
@Directive({
hostListeners: {'event': 'statement'},
hostProperties: {'expression': 'hostProp'},
hostAttributes: {'attr': 'value'},
hostActions: {'action': 'statement'}
})
After
@Directive({
host: {
'(event)': 'statement',
'[hostProp]': 'expression' // k & v swapped
'attr': 'value',
'@action': 'statement'
}
})
([f3b49378](https://github.com/angular/angular/commit/f3b49378))
*
no longer cache ref
([e77710a3](https://github.com/angular/angular/commit/e77710a3))
<a name"2.0.0-alpha.26"></a>
### 2.0.0-alpha.26 (2015-06-03)
#### Bug Fixes
* format a file that slipped in. ([471a1b6d](https://github.com/angular/angular/commit/471a1b6d))
* fix clang errors ([01fb8e66](https://github.com/angular/angular/commit/01fb8e66))
* **ShadowCss:** keyframes tests failing in Safari ([4c8e11a5](https://github.com/angular/angular/commit/4c8e11a5), closes [#2283](https://github.com/angular/angular/issues/2283))
* **Tools:** Moves files out of dart2js/**/web. ([40150379](https://github.com/angular/angular/commit/40150379))
* **ast:** fix the size of a list in _evalListCache ([0387221d](https://github.com/angular/angular/commit/0387221d))
* **benchpress:**
* support nested intervals ([c280fe81](https://github.com/angular/angular/commit/c280fe81))
* add index to root of module ([383f0a1f](https://github.com/angular/angular/commit/383f0a1f))
* **binding:** unbalanced curly brackets in documentation ([a80921b4](https://github.com/angular/angular/commit/a80921b4))
* **browser_adapter:**
* HTMLStyleElement.innerText does not trigger creation of CSS rules (Firefox) ([b2a24e02](https://github.com/angular/angular/commit/b2a24e02))
* event creation fails (IE11, Firefox) ([665ccafd](https://github.com/angular/angular/commit/665ccafd))
* element.getBoundingClientRect fails when element not in DOM (IE11) ([f35dbb99](https://github.com/angular/angular/commit/f35dbb99))
* element.matches only available with prefix (IE11) ([a393f84f](https://github.com/angular/angular/commit/a393f84f))
* assigning null to document.title sets the title to "null" (IE11, Firefox) ([92c2c33a](https://github.com/angular/angular/commit/92c2c33a))
* **build:**
* remove nonexistant dart format task from gulpfile ([f74d7727](https://github.com/angular/angular/commit/f74d7727))
* make dart formatter errors more readable ([31b66878](https://github.com/angular/angular/commit/31b66878))
* also run ts tests in node. ([05774f6c](https://github.com/angular/angular/commit/05774f6c))
* **collection:**
* iterator on Map keys is not supported (Safari) ([4b98ed11](https://github.com/angular/angular/commit/4b98ed11), closes [#2096](https://github.com/angular/angular/issues/2096))
* new Map(iterable) is not supported (Safari) ([d308e55e](https://github.com/angular/angular/commit/d308e55e))
* new Set(iterable) is not supported (IE11, Safari) ([57b88ec2](https://github.com/angular/angular/commit/57b88ec2), closes [#2063](https://github.com/angular/angular/issues/2063))
* **core:** resurrect OnChange interface ([d48fae35](https://github.com/angular/angular/commit/d48fae35))
* **dartdocs:** Hide duplicate exports from guinness. ([17e1d7f1](https://github.com/angular/angular/commit/17e1d7f1))
* **deps:** Update clang-format to 1.0.14. ([15f1eb28](https://github.com/angular/angular/commit/15f1eb28))
* **di:** allow `@Inject(…)` to work in dart2js and dynamic reflection ([4a3fd5e8](https://github.com/angular/angular/commit/4a3fd5e8), closes [#2185](https://github.com/angular/angular/issues/2185))
* **docs:** generate d.ts file only for angular2/angular2. ([0a0b84a0](https://github.com/angular/angular/commit/0a0b84a0))
* **dom:**
* allow to correctly clone document fragments ([2351896c](https://github.com/angular/angular/commit/2351896c))
* `querySelectorAll` should only query child nodes ([307011a9](https://github.com/angular/angular/commit/307011a9))
* **example:** unused event ([f83f1ee0](https://github.com/angular/angular/commit/f83f1ee0))
* **examples:** update form example to use NgIf ([1ad65582](https://github.com/angular/angular/commit/1ad65582))
* **facade:**
* Make PromiseWrapper#all semantics equivalent ([22f59252](https://github.com/angular/angular/commit/22f59252))
* Fix bug in TS indexOf ([cda35101](https://github.com/angular/angular/commit/cda35101))
* **fake_async:** fixed fakeAsync to throw instead of crashing on cjs ([5c53cf64](https://github.com/angular/angular/commit/5c53cf64))
* **forms:** disabled form tests on cjs until fakeAsync is fixed ([cd52d8a3](https://github.com/angular/angular/commit/cd52d8a3))
* **gulp:** prevent duplicate error messages ([381d4cb3](https://github.com/angular/angular/commit/381d4cb3), closes [#2021](https://github.com/angular/angular/issues/2021))
* **injectable:** add missing @Injectables annotations ([0c7f05f5](https://github.com/angular/angular/commit/0c7f05f5), closes [#2173](https://github.com/angular/angular/issues/2173))
* **package.json:** add `reflect-metadata` to package.json ([60801777](https://github.com/angular/angular/commit/60801777), closes [#2170](https://github.com/angular/angular/issues/2170))
* **render:**
* only look for content tags in views that might have them. ([ba7956f5](https://github.com/angular/angular/commit/ba7956f5), closes [#2297](https://github.com/angular/angular/issues/2297))
* don’t store a document fragment as bound element ([24bc4b66](https://github.com/angular/angular/commit/24bc4b66))
* **router:** event.defaultPrevented is not reliable (IE11) ([2287938f](https://github.com/angular/angular/commit/2287938f))
* **selector:** support multiple `:not` clauses ([62a95823](https://github.com/angular/angular/commit/62a95823), closes [#2243](https://github.com/angular/angular/issues/2243))
* **test:**
* clang formatting errors ([05d66bba](https://github.com/angular/angular/commit/05d66bba))
* solve CSS discrepancies across browsers ([fb42d590](https://github.com/angular/angular/commit/fb42d590), closes [#2177](https://github.com/angular/angular/issues/2177))
* use a not expandable CSS rule in ShadowCSS spec (Firefox) ([588fbfd8](https://github.com/angular/angular/commit/588fbfd8), closes [#2061](https://github.com/angular/angular/issues/2061))
* adds longer timers for NgZone and PromisePipe tests (IE11) ([661a0479](https://github.com/angular/angular/commit/661a0479), closes [#2055](https://github.com/angular/angular/issues/2055))
* native shadow DOM is required (IE11, Firefox) ([9802debf](https://github.com/angular/angular/commit/9802debf))
* function.name is not available (IE11) ([5103f080](https://github.com/angular/angular/commit/5103f080))
* **tests:** disable mobile emulation so benchmarks run on current chrome ([b071b66b](https://github.com/angular/angular/commit/b071b66b))
* **types:** parametrize QueryList. ([552985e3](https://github.com/angular/angular/commit/552985e3))
#### Features
* add support for the safe navigation (aka Elvis) operator ([a9be2ebf](https://github.com/angular/angular/commit/a9be2ebf), closes [#791](https://github.com/angular/angular/issues/791))
* **Directive:** convert properties to an array ([d7df853b](https://github.com/angular/angular/commit/d7df853b), closes [#2013](https://github.com/angular/angular/issues/2013))
* **ElementInjector:** support an arbitrary number of bindings ([b1c9bf14](https://github.com/angular/angular/commit/b1c9bf14), closes [#1853](https://github.com/angular/angular/issues/1853))
* **OpaqueToken:** now a const constructor ([c571b269](https://github.com/angular/angular/commit/c571b269))
* **RegExpWrapper:** implement a test method ([551586ce](https://github.com/angular/angular/commit/551586ce))
* **benchpress:** Add extension for ff metrics reporting ([b390f441](https://github.com/angular/angular/commit/b390f441), closes [#1976](https://github.com/angular/angular/issues/1976))
* **binding:** throw on binding to a blank alias ([ec2d8cc2](https://github.com/angular/angular/commit/ec2d8cc2), closes [#2068](https://github.com/angular/angular/issues/2068))
* **broccoli:** add incremental dartfmt plugin ([e5d06e47](https://github.com/angular/angular/commit/e5d06e47), closes [#2211](https://github.com/angular/angular/issues/2211))
* **change_detection:** added onInit and onCheck hooks ([c39c8ebc](https://github.com/angular/angular/commit/c39c8ebc))
* **change_detection.ts:** export PipeFactory ([93f464a1](https://github.com/angular/angular/commit/93f464a1), closes [#2245](https://github.com/angular/angular/issues/2245))
* **core:**
* added support for detecting lifecycle events based on interfaces ([30b6542f](https://github.com/angular/angular/commit/30b6542f))
* added missing interfaces for onDestroy and onAllChangesDone lifecycle events ([2b6a6530](https://github.com/angular/angular/commit/2b6a6530))
* **di:** added optional self parameter to Parent, Ancestor, and Unbounded ([34cfc9f4](https://github.com/angular/angular/commit/34cfc9f4))
* **dom:** add `setData()` method. ([6f3368ef](https://github.com/angular/angular/commit/6f3368ef))
* **facade:** add read/write access to global variables ([cdf791f0](https://github.com/angular/angular/commit/cdf791f0))
* **fakeAsync:** flush the microtasks before returning ([c7572ac1](https://github.com/angular/angular/commit/c7572ac1), closes [#2269](https://github.com/angular/angular/issues/2269))
* **form:** implemented an imperative way of updating the view by updating the value of a co ([652ed0cf](https://github.com/angular/angular/commit/652ed0cf))
* **forms:**
* added support for status classes ([3baf815d](https://github.com/angular/angular/commit/3baf815d))
* added touched and untouched to Control ([ec3a7828](https://github.com/angular/angular/commit/ec3a7828))
* renamed control, control-group into ng-control and ng-control-group ([f543834b](https://github.com/angular/angular/commit/f543834b))
* changed the selector of TemplatdrivenFormDirective to match <form> ([6bef1c41](https://github.com/angular/angular/commit/6bef1c41))
* added ng-model ([559f54e9](https://github.com/angular/angular/commit/559f54e9))
* implemented template-driven forms ([a9d6fd9a](https://github.com/angular/angular/commit/a9d6fd9a))
* **key_event:** alias esc to escape ([10bc7e94](https://github.com/angular/angular/commit/10bc7e94), closes [#2010](https://github.com/angular/angular/issues/2010))
* **reflector:** added a method to get type's interfaces ([34d75e89](https://github.com/angular/angular/commit/34d75e89))
* **render:** re-export render and export `DirectiveResolver` ([662da0d7](https://github.com/angular/angular/commit/662da0d7), closes [#2026](https://github.com/angular/angular/issues/2026))
* **router:** add the router bundle to the bundle task. ([05fa9bc9](https://github.com/angular/angular/commit/05fa9bc9))
* **router.js:**
* export router injectables ([28ee0612](https://github.com/angular/angular/commit/28ee0612))
* export routerDirectives ([1f20ef97](https://github.com/angular/angular/commit/1f20ef97))
* **test:**
* added not.toBeNull ([74882c6c](https://github.com/angular/angular/commit/74882c6c))
* add element probe ([f9908cd4](https://github.com/angular/angular/commit/f9908cd4), closes [#1992](https://github.com/angular/angular/issues/1992))
* **test_lib:**
* add method to compare stringified DOM element ([c6335c12](https://github.com/angular/angular/commit/c6335c12), closes [#2106](https://github.com/angular/angular/issues/2106))
* add `containsRegex` ([23d59df8](https://github.com/angular/angular/commit/23d59df8))
* **tests:** add TestComponentBuilder ([c32dbad7](https://github.com/angular/angular/commit/c32dbad7), closes [#1812](https://github.com/angular/angular/issues/1812))
* **transformers:** added support for lifecycle events ([f19970a4](https://github.com/angular/angular/commit/f19970a4))
* **view:**
* introduce free embedded views ([5030ffb0](https://github.com/angular/angular/commit/5030ffb0))
* add `AppViewListener` interface ([75578f41](https://github.com/angular/angular/commit/75578f41))
#### Breaking Changes
*
- `Renderer.detachFreeHostView` was renamed to
`Renderer.detachFreeView`
- `DomRenderer.getHostElement()` was generalized into
`DomRenderer.getRootNodes()`
([5030ffb0](https://github.com/angular/angular/commit/5030ffb0))
*
now a `const` constructor
([c571b269](https://github.com/angular/angular/commit/c571b269))
*
Before
@Directive(properties: {
'sameName': 'sameName',
'directiveProp': 'elProp | pipe'
})
After
@Directive(properties: [
'sameName',
'directiveProp: elProp | pipe'
])
([d7df853b](https://github.com/angular/angular/commit/d7df853b))
<a name"2.0.0-alpha.25"></a>
### 2.0.0-alpha.25 (2015-05-21)
#### Bug Fixes
* don't call onAllChangesDone on checkNoChanges ([a664f5a6](https://github.com/angular/angular/commit/a664f5a6))
* **XHRImpl:** fix errors, add a spec ([91ccc9af](https://github.com/angular/angular/commit/91ccc9af), closes [#1715](https://github.com/angular/angular/issues/1715))
* **browser:** template elements should have content imported instead of the element itself. ([c9ab8e4b](https://github.com/angular/angular/commit/c9ab8e4b))
* **di:** changed host and view injector to respect visibility ([705ee46f](https://github.com/angular/angular/commit/705ee46f))
* **element_injector:**
* fixed element injector to inject view dependencies into its components ([b6b52e62](https://github.com/angular/angular/commit/b6b52e62))
* fixed element injector to resolve dependencies of regular services ([28c2b8f4](https://github.com/angular/angular/commit/28c2b8f4))
* **forms:** changed forms to create only one value accessor instead of always creating Defau ([30c3e5a8](https://github.com/angular/angular/commit/30c3e5a8))
* **gulp:** continue watching when tasks throw ([ac28ac32](https://github.com/angular/angular/commit/ac28ac32), closes [#1915](https://github.com/angular/angular/issues/1915))
* **router:** router link should navigate to non-base Url. ([c4528321](https://github.com/angular/angular/commit/c4528321))
* **test_lib:** fixes nested beforeEach. ([826af401](https://github.com/angular/angular/commit/826af401))
#### Features
* **CD:** add support for === and !== ([0ae89ac0](https://github.com/angular/angular/commit/0ae89ac0))
* **PromisePipe:** remove ref onDestroy ([4afd2b41](https://github.com/angular/angular/commit/4afd2b41))
* **di:** changed toFactory to support dependency annotations ([f210c41c](https://github.com/angular/angular/commit/f210c41c))
* **forms:** migrated forms to typescript ([00c3693d](https://github.com/angular/angular/commit/00c3693d))
* **injector:** support forwardRef in toAlias ([fed86fc8](https://github.com/angular/angular/commit/fed86fc8))
<a name"2.0.0-alpha.24"></a>
### 2.0.0-alpha.24 (2015-05-19)
#### Bug Fixes
* **Compiler:** add an error when a directive is null or undefined ([25cd6e43](https://github.com/angular/angular/commit/25cd6e43), closes [#1908](https://github.com/angular/angular/issues/1908))
* **benchmark:**
* change If for NgIf ([cdbb2473](https://github.com/angular/angular/commit/cdbb2473))
* fixes ng-if ng-for renaming for templates. ([38926f71](https://github.com/angular/angular/commit/38926f71))
* **build:** npm shrinkwrap to pick up changed SHA1. ([04a9eb88](https://github.com/angular/angular/commit/04a9eb88))
* **directives:** fix import path ([c20060d2](https://github.com/angular/angular/commit/c20060d2))
* **errors:** require passing stack traces explicitly in ng2 own code ([8ab77353](https://github.com/angular/angular/commit/8ab77353))
* **examples:** prefix directives with Ng ([0e82970a](https://github.com/angular/angular/commit/0e82970a))
* **facade:** MapWrapper.createFromPairs ([af9dcad8](https://github.com/angular/angular/commit/af9dcad8), closes [#1640](https://github.com/angular/angular/issues/1640))
* **ng1 benchmarks:** revert *ng-if to ng-if ([909233f7](https://github.com/angular/angular/commit/909233f7))
* **router:**
* use appRootComponentToken to get root route configs ([791caf00](https://github.com/angular/angular/commit/791caf00), closes [#1947](https://github.com/angular/angular/issues/1947))
* improve route matching priorities ([5db89071](https://github.com/angular/angular/commit/5db89071))
* generate links for router-link with baseHref ([390cfb79](https://github.com/angular/angular/commit/390cfb79))
* sort possible routes by cost ([17392f66](https://github.com/angular/angular/commit/17392f66))
* **tree-differ:** treat symlinks to deleted paths as removals ([aad57954](https://github.com/angular/angular/commit/aad57954), closes [#1961](https://github.com/angular/angular/issues/1961))
#### Features
* allow for forward references in injection ([1eea2b25](https://github.com/angular/angular/commit/1eea2b25), closes [#1891](https://github.com/angular/angular/issues/1891))
* **change_detection:**
* json pipe ([98603824](https://github.com/angular/angular/commit/98603824), closes [#1957](https://github.com/angular/angular/issues/1957))
* uppercase and lowercase pipes ([7a4a6353](https://github.com/angular/angular/commit/7a4a6353))
* implemented change detection that can be configured with pregenerated change det ([08f21dbf](https://github.com/angular/angular/commit/08f21dbf))
* **compiler:**
* special-case class attribute in hostAttributes ([3011cd86](https://github.com/angular/angular/commit/3011cd86), closes [#1774](https://github.com/angular/angular/issues/1774), [#1841](https://github.com/angular/angular/issues/1841))
* added support for [()] syntax ([685a6507](https://github.com/angular/angular/commit/685a6507))
* **di:**
* added hostInjector and viewInjector to the Directive annotation ([b066b8d1](https://github.com/angular/angular/commit/b066b8d1))
* removed publishAs ([3a53f679](https://github.com/angular/angular/commit/3a53f679))
* **element_injector:** allow @Optional for ProtoViewRef ([bb2eda2d](https://github.com/angular/angular/commit/bb2eda2d))
* **errors:** preserve stack traces of user exceptions in Dart ([b6f29b44](https://github.com/angular/angular/commit/b6f29b44))
* **facade:** toUpperCase and toLowerCase ([557d54b3](https://github.com/angular/angular/commit/557d54b3))
* **fakeAsync:** allow simulating the passage of time ([0f002a5b](https://github.com/angular/angular/commit/0f002a5b))
* **forms:** improved error messages ([11e43851](https://github.com/angular/angular/commit/11e43851), closes [#1839](https://github.com/angular/angular/issues/1839))
* **pipe:** reexported pipes to genereate docs ([155b1e2b](https://github.com/angular/angular/commit/155b1e2b))
#### Breaking Changes
* `AppViewManager.createInPlaceHostView` is replaced by
`AppViewManager.createRootHostView` (for bootstrap) and
`AppViewManager.createFreeHostView` (for imperative components).
The later creates new host elements that are not attached anywhere.
To attach them, use `DomRenderer.getHostElement(hostviewRef)`
to get the host element.
Closes #1920
([421d8916](https://github.com/angular/angular/commit/421d8916))
* - renames `DirectiveMetadataReader` into `DirectiveResolver`
and removes `src/core/compiler/directive_metadata`.
Fixes #1712
Fixes #1713
([ecb06801](https://github.com/angular/angular/commit/ecb06801))
<a name"2.0.0-alpha.23"></a>
### 2.0.0-alpha.23 (2015-05-12)
#### Bug Fixes
* **change_detection:** updated dynamic change detector not to mutate when throwing ([d717529e](https://github.com/angular/angular/commit/d717529e), closes [#1762](https://github.com/angular/angular/issues/1762))
* **dart:** Remove unused imports. ([4ce0d5e0](https://github.com/angular/angular/commit/4ce0d5e0))
* **forms:** export directives as const in Dart ([5036086f](https://github.com/angular/angular/commit/5036086f), closes [#1283](https://github.com/angular/angular/issues/1283))
* **gulpfile:** fixed test.unit.dart to format dart code before running test ([92d6aa1f](https://github.com/angular/angular/commit/92d6aa1f))
* **location:** dartium does not like pushState with null. ([c2a42d5d](https://github.com/angular/angular/commit/c2a42d5d))
* **router:**
* add baseUrl to relative paths, but not absolute. ([a5741541](https://github.com/angular/angular/commit/a5741541), closes [#1783](https://github.com/angular/angular/issues/1783))
* reuse common parent components ([ac80df09](https://github.com/angular/angular/commit/ac80df09))
* router-link works without params ([77d1fc14](https://github.com/angular/angular/commit/77d1fc14))
* strip base href from URLs when navigating ([853d1de6](https://github.com/angular/angular/commit/853d1de6))
* **test_lib:** spy funcs should match null arguments ([84dc6ae7](https://github.com/angular/angular/commit/84dc6ae7))
* **transformer:** remove classDefParser in favor of hardcoded strings to speed up build ([01d5c295](https://github.com/angular/angular/commit/01d5c295))
* **view:** fixed ProtoViewFactory to get all property bindings ([7f976381](https://github.com/angular/angular/commit/7f976381))
#### Features
* **PromisePipe:** add pipe for promises ([74987585](https://github.com/angular/angular/commit/74987585))
* **VmTurnZone:** Rework the implementation to minimize change detection runs ([e8a6c95e](https://github.com/angular/angular/commit/e8a6c95e))
* **change_detection.js:** export null pipes ([4b62a722](https://github.com/angular/angular/commit/4b62a722), closes [#1624](https://github.com/angular/angular/issues/1624))
* **compiler:**
* added support for host actions ([f9c1de46](https://github.com/angular/angular/commit/f9c1de46))
* allow setting attributes on a host element ([51839ca6](https://github.com/angular/angular/commit/51839ca6), closes [#1402](https://github.com/angular/angular/issues/1402))
* **di:**
* support type literals in DI ([358a6750](https://github.com/angular/angular/commit/358a6750))
* expose parent injector ([2185e7ce](https://github.com/angular/angular/commit/2185e7ce))
* components can self-publish via publishAs ([1a0da11e](https://github.com/angular/angular/commit/1a0da11e))
* **directives:** export collection of core directives ([a5638a94](https://github.com/angular/angular/commit/a5638a94), closes [#1524](https://github.com/angular/angular/issues/1524))
* **dom:** add getBaseHref method ([05219a54](https://github.com/angular/angular/commit/05219a54))
* **facade:** add equals method to StringMapWrapper ([aff85b50](https://github.com/angular/angular/commit/aff85b50))
* **gulpfuile:** added watch.js.dev ([3256ff1c](https://github.com/angular/angular/commit/3256ff1c))
* **lang:** support const expressions in TS/JS and Dart ([4665726f](https://github.com/angular/angular/commit/4665726f), closes [#1796](https://github.com/angular/angular/issues/1796))
* **material:**
* add early version of md-grid-list. ([8ef183b5](https://github.com/angular/angular/commit/8ef183b5), closes [#1683](https://github.com/angular/angular/issues/1683))
* early version of md-input ([ad239218](https://github.com/angular/angular/commit/ad239218), closes [#1753](https://github.com/angular/angular/issues/1753))
* **view:** allow to transplant a view into a ViewContainer at another place. ([4f3433b5](https://github.com/angular/angular/commit/4f3433b5), closes [#1492](https://github.com/angular/angular/issues/1492))
#### Breaking Changes
*
VmTurnZone has been renamed to NgZone.
- The public API has not chnanged,
- The "outer" zone is now named "mount" zone (private to NgZone).
([e11c2054](https://github.com/angular/angular/commit/e11c2054))
*
A collection of all the form directives is exported
under `formDirectives`
while those were previously available
under `FormDirectives`.
Closes #1804
([229e770a](https://github.com/angular/angular/commit/229e770a))
<a name"2.0.0-alpha.22"></a>
### 2.0.0-alpha.22 (2015-05-07)
#### Bug Fixes
* **brocolli:** escape special regexp characters when building regexps ([a58c9f83](https://github.com/angular/angular/commit/a58c9f83), closes [#1721](https://github.com/angular/angular/issues/1721), [#1752](https://github.com/angular/angular/issues/1752))
* **build:**
* build the broccoli tools with correct typescript version. ([6bba289a](https://github.com/angular/angular/commit/6bba289a))
* use correct tsd command to get typings at requested versions ([1205f54d](https://github.com/angular/angular/commit/1205f54d))
* revert typescript upgrade which broke the build. ([b5032fd3](https://github.com/angular/angular/commit/b5032fd3))
* refer to newest version of hammerjs typings ([a7a94636](https://github.com/angular/angular/commit/a7a94636))
* **bundle:** update the bundle config to point to rx.js ([cf322130](https://github.com/angular/angular/commit/cf322130))
* **change_detector:** ensure that locals are only used when implicit receiver ([d4925b61](https://github.com/angular/angular/commit/d4925b61), closes [#1542](https://github.com/angular/angular/issues/1542))
* **compiler:**
* clone templates before compiling them ([9e8d31d5](https://github.com/angular/angular/commit/9e8d31d5), closes [#1058](https://github.com/angular/angular/issues/1058))
* changed the compiler to set up event listeners and host properties on host view ([e3c11045](https://github.com/angular/angular/commit/e3c11045), closes [#1584](https://github.com/angular/angular/issues/1584))
* only sets viewDefinition absUrl if the view has either a template or templateUrl ([3d625463](https://github.com/angular/angular/commit/3d625463), closes [#1326](https://github.com/angular/angular/issues/1326), [#1327](https://github.com/angular/angular/issues/1327))
* **decorators:**
* incorrect annotation to decorator adapter ([b0c735f7](https://github.com/angular/angular/commit/b0c735f7))
* fixed decorators ([49777648](https://github.com/angular/angular/commit/49777648))
* fixes decorator reflection. ([be7504d4](https://github.com/angular/angular/commit/be7504d4))
* updates missing benchmark and fixes typo. ([87dcd5eb](https://github.com/angular/angular/commit/87dcd5eb))
* **decorators.es6:** export Directive decorator ([93c331d1](https://github.com/angular/angular/commit/93c331d1), closes [#1688](https://github.com/angular/angular/issues/1688))
* **di:** improve error messages for invalid bindings ([ee1b574b](https://github.com/angular/angular/commit/ee1b574b), closes [#1515](https://github.com/angular/angular/issues/1515), [#1573](https://github.com/angular/angular/issues/1573))
* **docs:** fix broken docs test after addition of .ts extension to dgeni regex. ([62bf777e](https://github.com/angular/angular/commit/62bf777e))
* **exception_handler:** log errors via `console.error` ([ead21c91](https://github.com/angular/angular/commit/ead21c91))
* **formatter:** point to the newest clang-format ([51c47792](https://github.com/angular/angular/commit/51c47792))
* **router:**
* fix for leading slash in dart ([c9cec600](https://github.com/angular/angular/commit/c9cec600))
* navigate on popstate event ([2713b787](https://github.com/angular/angular/commit/2713b787))
* throw if config does not contain required fields ([259f872c](https://github.com/angular/angular/commit/259f872c))
* infer top-level routing from app component ([46ad3552](https://github.com/angular/angular/commit/46ad3552), closes [#1600](https://github.com/angular/angular/issues/1600))
* use lists for RouteConfig annotations ([4965226f](https://github.com/angular/angular/commit/4965226f))
* **view:** changed view manager to hydrate change detector after creating directives ([c1579222](https://github.com/angular/angular/commit/c1579222))
#### Features
* **benchmark:** added an implementation of the tree benchmark in React ([e4342743](https://github.com/angular/angular/commit/e4342743))
* **benchmarks:** Add basic dart transformer benchmarks. ([1864f60a](https://github.com/angular/angular/commit/1864f60a))
* **decorators:**
* adds decorator versions of DI annotations. ([457c15cd](https://github.com/angular/angular/commit/457c15cd))
* adds support for parameter decorators. ([f863ea0d](https://github.com/angular/angular/commit/f863ea0d))
* adds decorators to be used by TS and Babel transpiled apps. ([fb67e373](https://github.com/angular/angular/commit/fb67e373))
* **dom:** add location and history as DOM-like APIs. ([f356d033](https://github.com/angular/angular/commit/f356d033))
* **material:** add prototype dialog component w/ demo. ([f88c4b77](https://github.com/angular/angular/commit/f88c4b77))
* **router:**
* adds the router to the self-executing bundle. ([8e1d53b5](https://github.com/angular/angular/commit/8e1d53b5))
* export decorator version of RouteConfig ([75da6e4c](https://github.com/angular/angular/commit/75da6e4c))
* route redirects ([91533313](https://github.com/angular/angular/commit/91533313))
* sibling outlets ([9d5c33f9](https://github.com/angular/angular/commit/9d5c33f9))
* export routerInjectables ([ef7014fe](https://github.com/angular/angular/commit/ef7014fe))
* add location service ([ea546f50](https://github.com/angular/angular/commit/ea546f50))
#### Breaking Changes
* Previously, `Directive` was the abstract base class of several directives.
Now, `Directive` is the former `Decorator`, and `Component` inherits from it.
([f75a50c1](https://github.com/angular/angular/commit/f75a50c1))
* A dynamic component is just a component that has no @View annotation…
([8faf6364](https://github.com/angular/angular/commit/8faf6364))
<a name="2.0.0-alpha.21"></a>
# 2.0.0-alpha.21 (2015-04-27)
## Features
- **dart/transform:** Dedup getters, setters, & methods
([15376a6d](https://github.com/angular/angular/commit/15376a6d243740c73cf90f55525d1710cdd156f5))
- **facade:** add isType method
([e617ca63](https://github.com/angular/angular/commit/e617ca6323902bd98c0f1eb990b82f6b8d3c98e3))
- **parser:** support === and !== operators
([afe0e454](https://github.com/angular/angular/commit/afe0e454537f9252f9cf313647e649cfa464f96f),
[#1496](https://github.com/angular/angular/issues/1496), [#1500](https://github.com/angular/angular/issues/1500))
- **router:** add initial implementation
([1b2754da](https://github.com/angular/angular/commit/1b2754dacdd15e8fea429d56cdacb28eae76d2b1))
- **view:** reimplemented property setters using change detection
([8ccafb05](https://github.com/angular/angular/commit/8ccafb0524e3ac4c51af34ef88e0fe27482336a6))
## Performance Improvements
- **benchmarks:**
- benchmark that measure cost of dynamic components
([427f0d02](https://github.com/angular/angular/commit/427f0d021c51ea6923edd07574a4cc74a1ef84e6))
- benchmark measuring cost of decorators (fixes #1479)
([9fc9d535](https://github.com/angular/angular/commit/9fc9d535667c620017367877dbc2a3bc56d358b7))
## Other (malformed commit messages)
- **other:**
- feat: alllow specifying directives as bindings
([4bab25b3](https://github.com/angular/angular/commit/4bab25b3666f4247434ad5cb871906fb063fef51),
[#1498](https://github.com/angular/angular/issues/1498))
- fix: export ShadowDom strategies
([6896305e](https://github.com/angular/angular/commit/6896305e34082c246769829e4258631c1d2363d1),
[#1510](https://github.com/angular/angular/issues/1510), [#1511](https://github.com/angular/angular/issues/1511))
| CHANGELOG.md | 0 | https://github.com/angular/angular/commit/5b597de18cb4a29f78dc3a576b9c6e45bff18ecf | [
0.7925148606300354,
0.0102029824629426,
0.00016187207074835896,
0.0001664752053329721,
0.08857937902212143
] |
{
"id": 2,
"code_window": [
" */\n",
"export class Control extends AbstractControl {\n",
" _onChange: Function;\n",
"\n",
" constructor(value: any, validator: Function = Validators.nullValidator) {\n",
" super(validator);\n",
" this._value = value;\n",
" this.updateValidity({onlySelf: true});\n",
" this._valueChanges = new EventEmitter();\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" constructor(value: any = null, validator: Function = Validators.nullValidator) {\n"
],
"file_path": "modules/angular2/src/forms/model.ts",
"type": "replace",
"edit_start_line_idx": 146
} | import {StringWrapper, isPresent, isBlank} from 'angular2/src/facade/lang';
import {Observable, EventEmitter, ObservableWrapper} from 'angular2/src/facade/async';
import {StringMap, StringMapWrapper, ListWrapper, List} from 'angular2/src/facade/collection';
import {Validators} from './validators';
/**
* Indicates that a Control is valid, i.e. that no errors exist in the input value.
*/
export const VALID = "VALID";
/**
* Indicates that a Control is invalid, i.e. that an error exists in the input value.
*/
export const INVALID = "INVALID";
export function isControl(c: Object): boolean {
return c instanceof AbstractControl;
}
function _find(c: AbstractControl, path: List<string | number>| string) {
if (isBlank(path)) return null;
if (!(path instanceof List)) {
path = StringWrapper.split(<string>path, new RegExp("/"));
}
if (ListWrapper.isEmpty(path)) return null;
return ListWrapper.reduce(<List<string | number>>path, (v, name) => {
if (v instanceof ControlGroup) {
return isPresent(v.controls[name]) ? v.controls[name] : null;
} else if (v instanceof ControlArray) {
var index = <number>name;
return isPresent(v.at(index)) ? v.at(index) : null;
} else {
return null;
}
}, c);
}
/**
* Omitting from external API doc as this is really an abstract internal concept.
*/
export class AbstractControl {
_value: any;
_status: string;
_errors: StringMap<string, any>;
_pristine: boolean;
_touched: boolean;
_parent: ControlGroup | ControlArray;
validator: Function;
_valueChanges: EventEmitter;
constructor(validator: Function) {
this.validator = validator;
this._pristine = true;
this._touched = false;
}
get value(): any { return this._value; }
get status(): string { return this._status; }
get valid(): boolean { return this._status === VALID; }
get errors(): StringMap<string, any> { return this._errors; }
get pristine(): boolean { return this._pristine; }
get dirty(): boolean { return !this.pristine; }
get touched(): boolean { return this._touched; }
get untouched(): boolean { return !this._touched; }
get valueChanges(): Observable { return this._valueChanges; }
markAsTouched(): void { this._touched = true; }
markAsDirty({onlySelf}: {onlySelf?: boolean} = {}): void {
onlySelf = isPresent(onlySelf) ? onlySelf : false;
this._pristine = false;
if (isPresent(this._parent) && !onlySelf) {
this._parent.markAsDirty({onlySelf: onlySelf});
}
}
setParent(parent) { this._parent = parent; }
updateValidity({onlySelf}: {onlySelf?: boolean} = {}): void {
onlySelf = isPresent(onlySelf) ? onlySelf : false;
this._errors = this.validator(this);
this._status = isPresent(this._errors) ? INVALID : VALID;
if (isPresent(this._parent) && !onlySelf) {
this._parent.updateValidity({onlySelf: onlySelf});
}
}
updateValueAndValidity({onlySelf, emitEvent}: {onlySelf?: boolean, emitEvent?: boolean} = {}):
void {
onlySelf = isPresent(onlySelf) ? onlySelf : false;
emitEvent = isPresent(emitEvent) ? emitEvent : true;
this._updateValue();
if (emitEvent) {
ObservableWrapper.callNext(this._valueChanges, this._value);
}
this._errors = this.validator(this);
this._status = isPresent(this._errors) ? INVALID : VALID;
if (isPresent(this._parent) && !onlySelf) {
this._parent.updateValueAndValidity({onlySelf: onlySelf, emitEvent: emitEvent});
}
}
find(path: List<string | number>| string): AbstractControl { return _find(this, path); }
getError(errorCode: string, path: List<string> = null): any {
var c = isPresent(path) && !ListWrapper.isEmpty(path) ? this.find(path) : this;
if (isPresent(c) && isPresent(c._errors)) {
return StringMapWrapper.get(c._errors, errorCode);
} else {
return null;
}
}
hasError(errorCode: string, path: List<string> = null): boolean {
return isPresent(this.getError(errorCode, path));
}
_updateValue(): void {}
}
/**
* Defines a part of a form that cannot be divided into other controls.
*
* `Control` is one of the three fundamental building blocks used to define forms in Angular, along
* with
* {@link ControlGroup} and {@link ControlArray}.
*/
export class Control extends AbstractControl {
_onChange: Function;
constructor(value: any, validator: Function = Validators.nullValidator) {
super(validator);
this._value = value;
this.updateValidity({onlySelf: true});
this._valueChanges = new EventEmitter();
}
updateValue(value: any,
{onlySelf, emitEvent, emitModelToViewChange}:
{onlySelf?: boolean, emitEvent?: boolean, emitModelToViewChange?: boolean} = {}):
void {
emitModelToViewChange = isPresent(emitModelToViewChange) ? emitModelToViewChange : true;
this._value = value;
if (isPresent(this._onChange) && emitModelToViewChange) this._onChange(this._value);
this.updateValueAndValidity({onlySelf: onlySelf, emitEvent: emitEvent});
}
registerOnChange(fn: Function): void { this._onChange = fn; }
}
/**
* Defines a part of a form, of fixed length, that can contain other controls.
*
* A ControlGroup aggregates the values and errors of each {@link Control} in the group. Thus, if
* one of the controls
* in a group is invalid, the entire group is invalid. Similarly, if a control changes its value,
* the entire group
* changes as well.
*
* `ControlGroup` is one of the three fundamental building blocks used to define forms in Angular,
* along with
* {@link Control} and {@link ControlArray}. {@link ControlArray} can also contain other controls,
* but is of variable
* length.
*/
export class ControlGroup extends AbstractControl {
controls: StringMap<string, AbstractControl>;
_optionals: StringMap<string, boolean>;
constructor(controls: StringMap<String, AbstractControl>,
optionals: StringMap<String, boolean> = null,
validator: Function = Validators.group) {
super(validator);
this.controls = controls;
this._optionals = isPresent(optionals) ? optionals : {};
this._valueChanges = new EventEmitter();
this._setParentForControls();
this._value = this._reduceValue();
this.updateValidity({onlySelf: true});
}
addControl(name: string, c: AbstractControl) {
this.controls[name] = c;
c.setParent(this);
}
removeControl(name: string) { StringMapWrapper.delete(this.controls, name); }
include(controlName: string): void {
StringMapWrapper.set(this._optionals, controlName, true);
this.updateValueAndValidity();
}
exclude(controlName: string): void {
StringMapWrapper.set(this._optionals, controlName, false);
this.updateValueAndValidity();
}
contains(controlName: string): boolean {
var c = StringMapWrapper.contains(this.controls, controlName);
return c && this._included(controlName);
}
_setParentForControls() {
StringMapWrapper.forEach(this.controls, (control, name) => { control.setParent(this); });
}
_updateValue() { this._value = this._reduceValue(); }
_reduceValue() {
return this._reduceChildren({}, (acc, control, name) => {
acc[name] = control.value;
return acc;
});
}
_reduceChildren(initValue: any, fn: Function) {
var res = initValue;
StringMapWrapper.forEach(this.controls, (control, name) => {
if (this._included(name)) {
res = fn(res, control, name);
}
});
return res;
}
_included(controlName: string): boolean {
var isOptional = StringMapWrapper.contains(this._optionals, controlName);
return !isOptional || StringMapWrapper.get(this._optionals, controlName);
}
}
/**
* Defines a part of a form, of variable length, that can contain other controls.
*
* A `ControlArray` aggregates the values and errors of each {@link Control} in the group. Thus, if
* one of the controls
* in a group is invalid, the entire group is invalid. Similarly, if a control changes its value,
* the entire group
* changes as well.
*
* `ControlArray` is one of the three fundamental building blocks used to define forms in Angular,
* along with {@link Control} and {@link ControlGroup}. {@link ControlGroup} can also contain
* other controls, but is of fixed length.
*/
export class ControlArray extends AbstractControl {
controls: List<AbstractControl>;
constructor(controls: List<AbstractControl>, validator: Function = Validators.array) {
super(validator);
this.controls = controls;
this._valueChanges = new EventEmitter();
this._setParentForControls();
this._updateValue();
this.updateValidity({onlySelf: true});
}
at(index: number): AbstractControl { return this.controls[index]; }
push(control: AbstractControl): void {
this.controls.push(control);
control.setParent(this);
this.updateValueAndValidity();
}
insert(index: number, control: AbstractControl): void {
ListWrapper.insert(this.controls, index, control);
control.setParent(this);
this.updateValueAndValidity();
}
removeAt(index: number): void {
ListWrapper.removeAt(this.controls, index);
this.updateValueAndValidity();
}
get length(): number { return this.controls.length; }
_updateValue() { this._value = ListWrapper.map(this.controls, (c) => c.value); }
_setParentForControls() {
ListWrapper.forEach(this.controls, (control) => { control.setParent(this); });
}
}
| modules/angular2/src/forms/model.ts | 1 | https://github.com/angular/angular/commit/5b597de18cb4a29f78dc3a576b9c6e45bff18ecf | [
0.9950662851333618,
0.15539391338825226,
0.0001675368839642033,
0.0016191917238757014,
0.3272918164730072
] |
{
"id": 2,
"code_window": [
" */\n",
"export class Control extends AbstractControl {\n",
" _onChange: Function;\n",
"\n",
" constructor(value: any, validator: Function = Validators.nullValidator) {\n",
" super(validator);\n",
" this._value = value;\n",
" this.updateValidity({onlySelf: true});\n",
" this._valueChanges = new EventEmitter();\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" constructor(value: any = null, validator: Function = Validators.nullValidator) {\n"
],
"file_path": "modules/angular2/src/forms/model.ts",
"type": "replace",
"edit_start_line_idx": 146
} | import {
UIMessageBus,
UIMessageBusSink,
UIMessageBusSource
} from "angular2/src/web-workers/ui/application";
var worker = new Worker("loader.js");
var bus = new UIMessageBus(new UIMessageBusSink(worker), new UIMessageBusSource(worker));
var VALUE = 5;
document.getElementById("send_echo")
.addEventListener("click", (e) => {
var val = (<HTMLInputElement>document.getElementById("echo_input")).value;
bus.sink.send({type: "echo", value: val});
});
bus.source.listen((message) => {
if (message.data.type === "echo_response") {
document.getElementById("echo_result").innerHTML =
`<span class='response'>${message.data.value}</span>`;
} else if (message.data.type === "test") {
bus.sink.send({type: "result", value: {id: message.data.id, value: VALUE}});
} else if (message.data.type == "result") {
document.getElementById("ui_result").innerHTML =
`<span class='result'>${message.data.value}</span>`;
} else if (message.data.type == "ready") {
bus.sink.send({type: "init"});
}
});
| modules/examples/src/message_broker/index.ts | 0 | https://github.com/angular/angular/commit/5b597de18cb4a29f78dc3a576b9c6e45bff18ecf | [
0.000176401503267698,
0.00017506482254248112,
0.00017342602950520813,
0.00017536693485453725,
0.0000012333733820923953
] |
{
"id": 2,
"code_window": [
" */\n",
"export class Control extends AbstractControl {\n",
" _onChange: Function;\n",
"\n",
" constructor(value: any, validator: Function = Validators.nullValidator) {\n",
" super(validator);\n",
" this._value = value;\n",
" this.updateValidity({onlySelf: true});\n",
" this._valueChanges = new EventEmitter();\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" constructor(value: any = null, validator: Function = Validators.nullValidator) {\n"
],
"file_path": "modules/angular2/src/forms/model.ts",
"type": "replace",
"edit_start_line_idx": 146
} | library bar;
import 'package:angular2/src/core/annotations_impl/annotations.dart';
@Component(selector: '[soup]')
class MyComponent {}
| modules/angular2/test/transform/integration/synthetic_ctor_files/bar.dart | 0 | https://github.com/angular/angular/commit/5b597de18cb4a29f78dc3a576b9c6e45bff18ecf | [
0.00017348524124827236,
0.00017348524124827236,
0.00017348524124827236,
0.00017348524124827236,
0
] |
{
"id": 2,
"code_window": [
" */\n",
"export class Control extends AbstractControl {\n",
" _onChange: Function;\n",
"\n",
" constructor(value: any, validator: Function = Validators.nullValidator) {\n",
" super(validator);\n",
" this._value = value;\n",
" this.updateValidity({onlySelf: true});\n",
" this._valueChanges = new EventEmitter();\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" constructor(value: any = null, validator: Function = Validators.nullValidator) {\n"
],
"file_path": "modules/angular2/src/forms/model.ts",
"type": "replace",
"edit_start_line_idx": 146
} | {
"HelloCmp":
{
"id":"HelloCmp",
"selector":"hello-app",
"compileChildren":true,
"host":{},
"properties":[],
"readAttributes":[],
"type":1,
"version":1
}
} | modules/angular2/test/transform/template_compiler/inline_method_files/hello.ng_meta.json | 0 | https://github.com/angular/angular/commit/5b597de18cb4a29f78dc3a576b9c6e45bff18ecf | [
0.00017709231178741902,
0.00017681834287941456,
0.0001765443739714101,
0.00017681834287941456,
2.739689080044627e-7
] |
{
"id": 3,
"code_window": [
"\n",
"export function main() {\n",
" describe(\"Form Model\", () => {\n",
" describe(\"Control\", () => {\n",
" describe(\"validator\", () => {\n",
" it(\"should run validator with the initial value\", () => {\n",
" var c = new Control(\"value\", Validators.required);\n",
" expect(c.valid).toEqual(true);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it(\"should default the value to null\", () => {\n",
" var c = new Control();\n",
" expect(c.value).toBe(null);\n",
" expect(c.validator).toBe(Validators.nullValidator);\n",
" });\n",
"\n"
],
"file_path": "modules/angular2/test/forms/model_spec.ts",
"type": "add",
"edit_start_line_idx": 21
} | import {PromiseWrapper, ObservableWrapper, EventEmitter} from 'angular2/src/facade/async';
import {StringMapWrapper, List, ListWrapper} from 'angular2/src/facade/collection';
import {isPresent, isBlank, CONST_EXPR} from 'angular2/src/facade/lang';
import {Directive} from 'angular2/annotations';
import {forwardRef, Binding} from 'angular2/di';
import {NgControl} from './ng_control';
import {Form} from './form_interface';
import {NgControlGroup} from './ng_control_group';
import {ControlContainer} from './control_container';
import {AbstractControl, ControlGroup, Control} from '../model';
import {setUpControl} from './shared';
const formDirectiveBinding =
CONST_EXPR(new Binding(ControlContainer, {toAlias: forwardRef(() => NgForm)}));
/**
* Creates and binds a form object to a DOM element.
*
* # Example
*
* ```
* @Component({selector: "signup-comp"})
* @View({
* directives: [formDirectives],
* template: `
* <form #f="form" (submit)='onSignUp(f.value)'>
* <div ng-control-group='credentials' #credentials="form">
* Login <input type='text' ng-control='login'>
* Password <input type='password' ng-control='password'>
* </div>
* <div *ng-if="!credentials.valid">Credentials are invalid</div>
*
* <div ng-control-group='personal'>
* Name <input type='text' ng-control='name'>
* </div>
* <button type='submit'>Sign Up!</button>
* </form>
* `})
* class SignupComp {
* onSignUp(value) {
* // value === {personal: {name: 'some name'},
* // credentials: {login: 'some login', password: 'some password'}}
* }
* }
*
* ```
*/
@Directive({
selector: 'form:not([ng-no-form]):not([ng-form-model]),ng-form,[ng-form]',
hostInjector: [formDirectiveBinding],
host: {
'(submit)': 'onSubmit()',
},
events: ['ngSubmit'],
exportAs: 'form'
})
export class NgForm extends ControlContainer implements Form {
form: ControlGroup;
ngSubmit = new EventEmitter();
constructor() {
super();
this.form = new ControlGroup({});
}
get formDirective(): Form { return this; }
get control(): ControlGroup { return this.form; }
get path(): List<string> { return []; }
get controls(): StringMap<string, AbstractControl> { return this.form.controls; }
addControl(dir: NgControl): void {
this._later(_ => {
var container = this._findContainer(dir.path);
var c = new Control("");
setUpControl(c, dir);
container.addControl(dir.name, c);
c.updateValidity();
});
}
getControl(dir: NgControl): Control { return <Control>this.form.find(dir.path); }
removeControl(dir: NgControl): void {
this._later(_ => {
var container = this._findContainer(dir.path);
if (isPresent(container)) {
container.removeControl(dir.name);
container.updateValidity();
}
});
}
addControlGroup(dir: NgControlGroup): void {
this._later(_ => {
var container = this._findContainer(dir.path);
var c = new ControlGroup({});
container.addControl(dir.name, c);
c.updateValidity();
});
}
removeControlGroup(dir: NgControlGroup): void {
this._later(_ => {
var container = this._findContainer(dir.path);
if (isPresent(container)) {
container.removeControl(dir.name);
container.updateValidity();
}
});
}
getControlGroup(dir: NgControlGroup): ControlGroup {
return <ControlGroup>this.form.find(dir.path);
}
updateModel(dir: NgControl, value: any): void {
this._later(_ => {
var c = <Control>this.form.find(dir.path);
c.updateValue(value);
});
}
onSubmit(): boolean {
ObservableWrapper.callNext(this.ngSubmit, null);
return false;
}
_findContainer(path: List<string>): ControlGroup {
ListWrapper.removeLast(path);
return ListWrapper.isEmpty(path) ? this.form : <ControlGroup>this.form.find(path);
}
_later(fn) {
var c = PromiseWrapper.completer();
PromiseWrapper.then(c.promise, fn, (_) => {});
c.resolve(null);
}
}
| modules/angular2/src/forms/directives/ng_form.ts | 1 | https://github.com/angular/angular/commit/5b597de18cb4a29f78dc3a576b9c6e45bff18ecf | [
0.971729576587677,
0.06582614034414291,
0.00017306146037299186,
0.00020272063557058573,
0.24212241172790527
] |
{
"id": 3,
"code_window": [
"\n",
"export function main() {\n",
" describe(\"Form Model\", () => {\n",
" describe(\"Control\", () => {\n",
" describe(\"validator\", () => {\n",
" it(\"should run validator with the initial value\", () => {\n",
" var c = new Control(\"value\", Validators.required);\n",
" expect(c.valid).toEqual(true);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it(\"should default the value to null\", () => {\n",
" var c = new Control();\n",
" expect(c.value).toBe(null);\n",
" expect(c.validator).toBe(Validators.nullValidator);\n",
" });\n",
"\n"
],
"file_path": "modules/angular2/test/forms/model_spec.ts",
"type": "add",
"edit_start_line_idx": 21
} | import {bind, Binding} from 'angular2/di';
import {Compiler, CompilerCache} from 'angular2/src/core/compiler/compiler';
import {Reflector, reflector} from 'angular2/src/reflection/reflection';
import {
Parser,
Lexer,
ChangeDetection,
DynamicChangeDetection,
Pipes,
defaultPipes
} from 'angular2/change_detection';
import {ExceptionHandler} from 'angular2/src/core/exception_handler';
import {ViewLoader} from 'angular2/src/render/dom/compiler/view_loader';
import {ViewResolver} from 'angular2/src/core/compiler/view_resolver';
import {DirectiveResolver} from 'angular2/src/core/compiler/directive_resolver';
import {DynamicComponentLoader} from 'angular2/src/core/compiler/dynamic_component_loader';
import {ShadowDomStrategy} from 'angular2/src/render/dom/shadow_dom/shadow_dom_strategy';
import {
EmulatedUnscopedShadowDomStrategy
} from 'angular2/src/render/dom/shadow_dom/emulated_unscoped_shadow_dom_strategy';
import {XHR} from 'angular2/src/render/xhr';
import {ComponentUrlMapper} from 'angular2/src/core/compiler/component_url_mapper';
import {UrlResolver} from 'angular2/src/services/url_resolver';
import {AppRootUrl} from 'angular2/src/services/app_root_url';
import {StyleUrlResolver} from 'angular2/src/render/dom/compiler/style_url_resolver';
import {StyleInliner} from 'angular2/src/render/dom/compiler/style_inliner';
import {NgZone} from 'angular2/src/core/zone/ng_zone';
import {DOM} from 'angular2/src/dom/dom_adapter';
import {EventManager, DomEventsPlugin} from 'angular2/src/render/dom/events/event_manager';
import {MockViewResolver} from 'angular2/src/mock/view_resolver_mock';
import {MockXHR} from 'angular2/src/render/xhr_mock';
import {MockLocationStrategy} from 'angular2/src/mock/mock_location_strategy';
import {LocationStrategy} from 'angular2/src/router/location_strategy';
import {MockNgZone} from 'angular2/src/mock/ng_zone_mock';
import {TestComponentBuilder} from './test_component_builder';
import {Injector} from 'angular2/di';
import {List, ListWrapper} from 'angular2/src/facade/collection';
import {FunctionWrapper, Type} from 'angular2/src/facade/lang';
import {AppViewPool, APP_VIEW_POOL_CAPACITY} from 'angular2/src/core/compiler/view_pool';
import {AppViewManager} from 'angular2/src/core/compiler/view_manager';
import {AppViewManagerUtils} from 'angular2/src/core/compiler/view_manager_utils';
import {ELEMENT_PROBE_CONFIG} from 'angular2/debug';
import {ProtoViewFactory} from 'angular2/src/core/compiler/proto_view_factory';
import {RenderCompiler, Renderer} from 'angular2/src/render/api';
import {
DomRenderer,
DOCUMENT_TOKEN,
DOM_REFLECT_PROPERTIES_AS_ATTRIBUTES
} from 'angular2/src/render/dom/dom_renderer';
import {DefaultDomCompiler} from 'angular2/src/render/dom/compiler/compiler';
import {Log} from './utils';
/**
* Returns the root injector bindings.
*
* This must be kept in sync with the _rootBindings in application.js
*
* @returns {any[]}
*/
function _getRootBindings() {
return [
bind(Reflector)
.toValue(reflector),
];
}
/**
* Returns the application injector bindings.
*
* This must be kept in sync with _injectorBindings() in application.js
*
* @returns {any[]}
*/
function _getAppBindings() {
var appDoc;
// The document is only available in browser environment
try {
appDoc = DOM.defaultDoc();
} catch (e) {
appDoc = null;
}
return [
bind(DOCUMENT_TOKEN)
.toValue(appDoc),
bind(ShadowDomStrategy)
.toFactory((doc) => new EmulatedUnscopedShadowDomStrategy(doc.head), [DOCUMENT_TOKEN]),
DomRenderer,
DefaultDomCompiler,
bind(DOM_REFLECT_PROPERTIES_AS_ATTRIBUTES).toValue(false),
bind(Renderer).toAlias(DomRenderer),
bind(RenderCompiler).toAlias(DefaultDomCompiler),
ProtoViewFactory,
AppViewPool,
AppViewManager,
AppViewManagerUtils,
ELEMENT_PROBE_CONFIG,
bind(APP_VIEW_POOL_CAPACITY).toValue(500),
Compiler,
CompilerCache,
bind(ViewResolver).toClass(MockViewResolver),
bind(Pipes).toValue(defaultPipes),
Log,
bind(ChangeDetection).toClass(DynamicChangeDetection),
ViewLoader,
DynamicComponentLoader,
DirectiveResolver,
Parser,
Lexer,
ExceptionHandler,
bind(LocationStrategy).toClass(MockLocationStrategy),
bind(XHR).toClass(MockXHR),
ComponentUrlMapper,
UrlResolver,
AppRootUrl,
StyleUrlResolver,
StyleInliner,
TestComponentBuilder,
bind(NgZone).toClass(MockNgZone),
bind(EventManager)
.toFactory(
(zone) => {
var plugins = [
new DomEventsPlugin(),
];
return new EventManager(plugins, zone);
},
[NgZone]),
];
}
export function createTestInjector(bindings: List<Type | Binding | List<any>>): Injector {
var rootInjector = Injector.resolveAndCreate(_getRootBindings());
return rootInjector.resolveAndCreateChild(ListWrapper.concat(_getAppBindings(), bindings));
}
/**
* Allows injecting dependencies in `beforeEach()` and `it()`.
*
* Example:
*
* ```
* beforeEach(inject([Dependency, AClass], (dep, object) => {
* // some code that uses `dep` and `object`
* // ...
* }));
*
* it('...', inject([AClass, AsyncTestCompleter], (object, async) => {
* object.doSomething().then(() => {
* expect(...);
* async.done();
* });
* })
* ```
*
* Notes:
* - injecting an `AsyncTestCompleter` allow completing async tests - this is the equivalent of
* adding a `done` parameter in Jasmine,
* - inject is currently a function because of some Traceur limitation the syntax should eventually
* becomes `it('...', @Inject (object: AClass, async: AsyncTestCompleter) => { ... });`
*
* @param {Array} tokens
* @param {Function} fn
* @return {FunctionWithParamTokens}
*/
export function inject(tokens: List<any>, fn: Function): FunctionWithParamTokens {
return new FunctionWithParamTokens(tokens, fn);
}
export class FunctionWithParamTokens {
_tokens: List<any>;
_fn: Function;
constructor(tokens: List<any>, fn: Function) {
this._tokens = tokens;
this._fn = fn;
}
execute(injector: Injector): void {
var params = ListWrapper.map(this._tokens, (t) => injector.get(t));
FunctionWrapper.apply(this._fn, params);
}
}
| modules/angular2/src/test_lib/test_injector.ts | 0 | https://github.com/angular/angular/commit/5b597de18cb4a29f78dc3a576b9c6e45bff18ecf | [
0.00018081211601383984,
0.00017311451665591449,
0.00016219312965404242,
0.00017545395530760288,
0.000005511463768925751
] |
{
"id": 3,
"code_window": [
"\n",
"export function main() {\n",
" describe(\"Form Model\", () => {\n",
" describe(\"Control\", () => {\n",
" describe(\"validator\", () => {\n",
" it(\"should run validator with the initial value\", () => {\n",
" var c = new Control(\"value\", Validators.required);\n",
" expect(c.valid).toEqual(true);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it(\"should default the value to null\", () => {\n",
" var c = new Control();\n",
" expect(c.value).toBe(null);\n",
" expect(c.validator).toBe(Validators.nullValidator);\n",
" });\n",
"\n"
],
"file_path": "modules/angular2/test/forms/model_spec.ts",
"type": "add",
"edit_start_line_idx": 21
} | library angular2.test.transform.reflection_remover.verbose_files.expected;
// This file is intentionally formatted as a string to avoid having the
// automatic transformer prettify it.
//
// This file represents transformed user code. Because this code will be
// linked to output by a source map, we cannot change line numbers from the
// original code and we therefore add our generated code on the same line as
// those we are removing.
var code = """
library web_foo;
import 'package:angular2/src/core/application.dart';
import 'package:angular2/src/reflection/reflection.dart';
import 'package:angular2/src/reflection/debug_reflection_capabilities.dart';import 'index.ng_deps.dart' as ngStaticInit0;
void main() {
reflector.reflectionCapabilities = new ReflectionCapabilities(verbose: true);ngStaticInit0.initReflector();
bootstrap(MyComponent);
}
""";
| modules/angular2/test/transform/reflection_remover/verbose_files/expected/index.dart | 0 | https://github.com/angular/angular/commit/5b597de18cb4a29f78dc3a576b9c6e45bff18ecf | [
0.0001740485749905929,
0.00017265723727177829,
0.0001712183584459126,
0.00017270473472308367,
0.0000011559193353605224
] |
{
"id": 3,
"code_window": [
"\n",
"export function main() {\n",
" describe(\"Form Model\", () => {\n",
" describe(\"Control\", () => {\n",
" describe(\"validator\", () => {\n",
" it(\"should run validator with the initial value\", () => {\n",
" var c = new Control(\"value\", Validators.required);\n",
" expect(c.valid).toEqual(true);\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" it(\"should default the value to null\", () => {\n",
" var c = new Control();\n",
" expect(c.value).toBe(null);\n",
" expect(c.validator).toBe(Validators.nullValidator);\n",
" });\n",
"\n"
],
"file_path": "modules/angular2/test/forms/model_spec.ts",
"type": "add",
"edit_start_line_idx": 21
} | // This can only be requested once due to constant method name :(
__ng_jsonp__.__req0.finished([{"name":"caitp"}])
| modules/examples/src/jsonp/people.json | 0 | https://github.com/angular/angular/commit/5b597de18cb4a29f78dc3a576b9c6e45bff18ecf | [
0.00017122997087426484,
0.00017122997087426484,
0.00017122997087426484,
0.00017122997087426484,
0
] |
{
"id": 0,
"code_window": [
" preserveWhitespace?: boolean;\n",
" isFromDOM?: boolean;\n",
" shouldDecodeTags?: boolean;\n",
" shouldDecodeNewlines?: boolean;\n",
"\n",
" // for ssr optimization compiler\n",
" scopeId?: string;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" shouldDecodeNewlines?: boolean;\n",
" shouldDecodeNewlinesForHref?: boolean;\n"
],
"file_path": "flow/compiler.js",
"type": "replace",
"edit_start_line_idx": 16
} | /* @flow */
import config from 'core/config'
import { warn, cached } from 'core/util/index'
import { mark, measure } from 'core/util/perf'
import Vue from './runtime/index'
import { query } from './util/index'
import { shouldDecodeNewlines } from './util/compat'
import { compileToFunctions } from './compiler/index'
const idToTemplate = cached(id => {
const el = query(id)
return el && el.innerHTML
})
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && query(el)
/* istanbul ignore if */
if (el === document.body || el === document.documentElement) {
process.env.NODE_ENV !== 'production' && warn(
`Do not mount Vue to <html> or <body> - mount to normal elements instead.`
)
return this
}
const options = this.$options
// resolve template/el and convert to render function
if (!options.render) {
let template = options.template
if (template) {
if (typeof template === 'string') {
if (template.charAt(0) === '#') {
template = idToTemplate(template)
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && !template) {
warn(
`Template element not found or is empty: ${options.template}`,
this
)
}
}
} else if (template.nodeType) {
template = template.innerHTML
} else {
if (process.env.NODE_ENV !== 'production') {
warn('invalid template option:' + template, this)
}
return this
}
} else if (el) {
template = getOuterHTML(el)
}
if (template) {
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile')
}
const { render, staticRenderFns } = compileToFunctions(template, {
shouldDecodeNewlines,
delimiters: options.delimiters,
comments: options.comments
}, this)
options.render = render
options.staticRenderFns = staticRenderFns
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile end')
measure(`vue ${this._name} compile`, 'compile', 'compile end')
}
}
}
return mount.call(this, el, hydrating)
}
/**
* Get outerHTML of elements, taking care
* of SVG elements in IE as well.
*/
function getOuterHTML (el: Element): string {
if (el.outerHTML) {
return el.outerHTML
} else {
const container = document.createElement('div')
container.appendChild(el.cloneNode(true))
return container.innerHTML
}
}
Vue.compile = compileToFunctions
export default Vue
| src/platforms/web/entry-runtime-with-compiler.js | 1 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.998857855796814,
0.19982218742370605,
0.00016653061902616173,
0.00017250567907467484,
0.39930102229118347
] |
{
"id": 0,
"code_window": [
" preserveWhitespace?: boolean;\n",
" isFromDOM?: boolean;\n",
" shouldDecodeTags?: boolean;\n",
" shouldDecodeNewlines?: boolean;\n",
"\n",
" // for ssr optimization compiler\n",
" scopeId?: string;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" shouldDecodeNewlines?: boolean;\n",
" shouldDecodeNewlinesForHref?: boolean;\n"
],
"file_path": "flow/compiler.js",
"type": "replace",
"edit_start_line_idx": 16
} | /* @flow */
import RenderStream from './render-stream'
import { createWriteFunction } from './write'
import { createRenderFunction } from './render'
import { createPromiseCallback } from './util'
import TemplateRenderer from './template-renderer/index'
import type { ClientManifest } from './template-renderer/index'
export type Renderer = {
renderToString: (component: Component, context: any, cb: any) => ?Promise<string>;
renderToStream: (component: Component, context?: Object) => stream$Readable;
};
type RenderCache = {
get: (key: string, cb?: Function) => string | void;
set: (key: string, val: string) => void;
has?: (key: string, cb?: Function) => boolean | void;
};
export type RenderOptions = {
modules?: Array<(vnode: VNode) => ?string>;
directives?: Object;
isUnaryTag?: Function;
cache?: RenderCache;
template?: string;
inject?: boolean;
basedir?: string;
shouldPreload?: Function;
shouldPrefetch?: Function;
clientManifest?: ClientManifest;
runInNewContext?: boolean | 'once';
};
export function createRenderer ({
modules = [],
directives = {},
isUnaryTag = (() => false),
template,
inject,
cache,
shouldPreload,
shouldPrefetch,
clientManifest
}: RenderOptions = {}): Renderer {
const render = createRenderFunction(modules, directives, isUnaryTag, cache)
const templateRenderer = new TemplateRenderer({
template,
inject,
shouldPreload,
shouldPrefetch,
clientManifest
})
return {
renderToString (
component: Component,
context: any,
cb: any
): ?Promise<string> {
if (typeof context === 'function') {
cb = context
context = {}
}
if (context) {
templateRenderer.bindRenderFns(context)
}
// no callback, return Promise
let promise
if (!cb) {
({ promise, cb } = createPromiseCallback())
}
let result = ''
const write = createWriteFunction(text => {
result += text
return false
}, cb)
try {
render(component, write, context, () => {
if (template) {
result = templateRenderer.renderSync(result, context)
}
cb(null, result)
})
} catch (e) {
cb(e)
}
return promise
},
renderToStream (
component: Component,
context?: Object
): stream$Readable {
if (context) {
templateRenderer.bindRenderFns(context)
}
const renderStream = new RenderStream((write, done) => {
render(component, write, context, done)
})
if (!template) {
return renderStream
} else {
const templateStream = templateRenderer.createStream(context)
renderStream.on('error', err => {
templateStream.emit('error', err)
})
renderStream.pipe(templateStream)
return templateStream
}
}
}
}
| src/server/create-renderer.js | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00022322768927551806,
0.00017614873650018126,
0.0001672784419497475,
0.00017281351028941572,
0.000014345667295856401
] |
{
"id": 0,
"code_window": [
" preserveWhitespace?: boolean;\n",
" isFromDOM?: boolean;\n",
" shouldDecodeTags?: boolean;\n",
" shouldDecodeNewlines?: boolean;\n",
"\n",
" // for ssr optimization compiler\n",
" scopeId?: string;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" shouldDecodeNewlines?: boolean;\n",
" shouldDecodeNewlinesForHref?: boolean;\n"
],
"file_path": "flow/compiler.js",
"type": "replace",
"edit_start_line_idx": 16
} | import VNode from 'core/vdom/vnode'
window.createTextVNode = function (text) {
return new VNode(undefined, undefined, undefined, text)
}
| test/helpers/vdom.js | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00016988113929983228,
0.00016988113929983228,
0.00016988113929983228,
0.00016988113929983228,
0
] |
{
"id": 0,
"code_window": [
" preserveWhitespace?: boolean;\n",
" isFromDOM?: boolean;\n",
" shouldDecodeTags?: boolean;\n",
" shouldDecodeNewlines?: boolean;\n",
"\n",
" // for ssr optimization compiler\n",
" scopeId?: string;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" shouldDecodeNewlines?: boolean;\n",
" shouldDecodeNewlinesForHref?: boolean;\n"
],
"file_path": "flow/compiler.js",
"type": "replace",
"edit_start_line_idx": 16
} | import Vue from 'vue'
import injectStyles from '../transition/inject-styles'
import { isIE9 } from 'core/util/env'
import { nextFrame } from 'web/runtime/transition-util'
describe('Component keep-alive', () => {
const { duration, buffer } = injectStyles()
let components, one, two, el
beforeEach(() => {
one = {
template: '<div>one</div>',
created: jasmine.createSpy('one created'),
mounted: jasmine.createSpy('one mounted'),
activated: jasmine.createSpy('one activated'),
deactivated: jasmine.createSpy('one deactivated'),
destroyed: jasmine.createSpy('one destroyed')
}
two = {
template: '<div>two</div>',
created: jasmine.createSpy('two created'),
mounted: jasmine.createSpy('two mounted'),
activated: jasmine.createSpy('two activated'),
deactivated: jasmine.createSpy('two deactivated'),
destroyed: jasmine.createSpy('two destroyed')
}
components = {
one,
two
}
el = document.createElement('div')
document.body.appendChild(el)
})
function assertHookCalls (component, callCounts) {
expect([
component.created.calls.count(),
component.mounted.calls.count(),
component.activated.calls.count(),
component.deactivated.calls.count(),
component.destroyed.calls.count()
]).toEqual(callCounts)
}
it('should work', done => {
const vm = new Vue({
template: `
<div v-if="ok">
<keep-alive>
<component :is="view"></component>
</keep-alive>
</div>
`,
data: {
view: 'one',
ok: true
},
components
}).$mount()
expect(vm.$el.textContent).toBe('one')
assertHookCalls(one, [1, 1, 1, 0, 0])
assertHookCalls(two, [0, 0, 0, 0, 0])
vm.view = 'two'
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('two')
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 1, 0, 0])
vm.view = 'one'
}).then(() => {
expect(vm.$el.textContent).toBe('one')
assertHookCalls(one, [1, 1, 2, 1, 0])
assertHookCalls(two, [1, 1, 1, 1, 0])
vm.view = 'two'
}).then(() => {
expect(vm.$el.textContent).toBe('two')
assertHookCalls(one, [1, 1, 2, 2, 0])
assertHookCalls(two, [1, 1, 2, 1, 0])
vm.ok = false // teardown
}).then(() => {
expect(vm.$el.textContent).toBe('')
assertHookCalls(one, [1, 1, 2, 2, 1])
assertHookCalls(two, [1, 1, 2, 2, 1])
}).then(done)
})
it('should invoke hooks on the entire sub tree', done => {
one.template = '<two/>'
one.components = { two }
const vm = new Vue({
template: `
<div>
<keep-alive>
<one v-if="ok"/>
</keep-alive>
</div>
`,
data: {
ok: true
},
components
}).$mount()
expect(vm.$el.textContent).toBe('two')
assertHookCalls(one, [1, 1, 1, 0, 0])
assertHookCalls(two, [1, 1, 1, 0, 0])
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('')
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 1, 1, 0])
vm.ok = true
}).then(() => {
expect(vm.$el.textContent).toBe('two')
assertHookCalls(one, [1, 1, 2, 1, 0])
assertHookCalls(two, [1, 1, 2, 1, 0])
vm.ok = false
}).then(() => {
expect(vm.$el.textContent).toBe('')
assertHookCalls(one, [1, 1, 2, 2, 0])
assertHookCalls(two, [1, 1, 2, 2, 0])
}).then(done)
})
it('should handle nested keep-alive hooks properly', done => {
one.template = '<keep-alive><two v-if="ok" /></keep-alive>'
one.data = () => ({ ok: true })
one.components = { two }
const vm = new Vue({
template: `
<div>
<keep-alive>
<one v-if="ok" ref="one" />
</keep-alive>
</div>
`,
data: {
ok: true
},
components
}).$mount()
var oneInstance = vm.$refs.one
expect(vm.$el.textContent).toBe('two')
assertHookCalls(one, [1, 1, 1, 0, 0])
assertHookCalls(two, [1, 1, 1, 0, 0])
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('')
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 1, 1, 0])
}).then(() => {
vm.ok = true
}).then(() => {
expect(vm.$el.textContent).toBe('two')
assertHookCalls(one, [1, 1, 2, 1, 0])
assertHookCalls(two, [1, 1, 2, 1, 0])
}).then(() => {
// toggle sub component when activated
oneInstance.ok = false
}).then(() => {
expect(vm.$el.textContent).toBe('')
assertHookCalls(one, [1, 1, 2, 1, 0])
assertHookCalls(two, [1, 1, 2, 2, 0])
}).then(() => {
oneInstance.ok = true
}).then(() => {
expect(vm.$el.textContent).toBe('two')
assertHookCalls(one, [1, 1, 2, 1, 0])
assertHookCalls(two, [1, 1, 3, 2, 0])
}).then(() => {
vm.ok = false
}).then(() => {
expect(vm.$el.textContent).toBe('')
assertHookCalls(one, [1, 1, 2, 2, 0])
assertHookCalls(two, [1, 1, 3, 3, 0])
}).then(() => {
// toggle sub component when parent is deactivated
oneInstance.ok = false
}).then(() => {
expect(vm.$el.textContent).toBe('')
assertHookCalls(one, [1, 1, 2, 2, 0])
assertHookCalls(two, [1, 1, 3, 3, 0]) // should not be affected
}).then(() => {
oneInstance.ok = true
}).then(() => {
expect(vm.$el.textContent).toBe('')
assertHookCalls(one, [1, 1, 2, 2, 0])
assertHookCalls(two, [1, 1, 3, 3, 0]) // should not be affected
}).then(() => {
vm.ok = true
}).then(() => {
expect(vm.$el.textContent).toBe('two')
assertHookCalls(one, [1, 1, 3, 2, 0])
assertHookCalls(two, [1, 1, 4, 3, 0])
}).then(() => {
oneInstance.ok = false
vm.ok = false
}).then(() => {
expect(vm.$el.textContent).toBe('')
assertHookCalls(one, [1, 1, 3, 3, 0])
assertHookCalls(two, [1, 1, 4, 4, 0])
}).then(() => {
vm.ok = true
}).then(() => {
expect(vm.$el.textContent).toBe('')
assertHookCalls(one, [1, 1, 4, 3, 0])
assertHookCalls(two, [1, 1, 4, 4, 0]) // should remain inactive
}).then(done)
})
function sharedAssertions (vm, done) {
expect(vm.$el.textContent).toBe('one')
assertHookCalls(one, [1, 1, 1, 0, 0])
assertHookCalls(two, [0, 0, 0, 0, 0])
vm.view = 'two'
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('two')
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 0, 0, 0])
vm.view = 'one'
}).then(() => {
expect(vm.$el.textContent).toBe('one')
assertHookCalls(one, [1, 1, 2, 1, 0])
assertHookCalls(two, [1, 1, 0, 0, 1])
vm.view = 'two'
}).then(() => {
expect(vm.$el.textContent).toBe('two')
assertHookCalls(one, [1, 1, 2, 2, 0])
assertHookCalls(two, [2, 2, 0, 0, 1])
vm.ok = false // teardown
}).then(() => {
expect(vm.$el.textContent).toBe('')
assertHookCalls(one, [1, 1, 2, 2, 1])
assertHookCalls(two, [2, 2, 0, 0, 2])
}).then(done)
}
it('include (string)', done => {
const vm = new Vue({
template: `
<div v-if="ok">
<keep-alive include="one">
<component :is="view"></component>
</keep-alive>
</div>
`,
data: {
view: 'one',
ok: true
},
components
}).$mount()
sharedAssertions(vm, done)
})
it('include (regex)', done => {
const vm = new Vue({
template: `
<div v-if="ok">
<keep-alive :include="/^one$/">
<component :is="view"></component>
</keep-alive>
</div>
`,
data: {
view: 'one',
ok: true
},
components
}).$mount()
sharedAssertions(vm, done)
})
it('include (array)', done => {
const vm = new Vue({
template: `
<div v-if="ok">
<keep-alive :include="['one']">
<component :is="view"></component>
</keep-alive>
</div>
`,
data: {
view: 'one',
ok: true
},
components
}).$mount()
sharedAssertions(vm, done)
})
it('exclude (string)', done => {
const vm = new Vue({
template: `
<div v-if="ok">
<keep-alive exclude="two">
<component :is="view"></component>
</keep-alive>
</div>
`,
data: {
view: 'one',
ok: true
},
components
}).$mount()
sharedAssertions(vm, done)
})
it('exclude (regex)', done => {
const vm = new Vue({
template: `
<div v-if="ok">
<keep-alive :exclude="/^two$/">
<component :is="view"></component>
</keep-alive>
</div>
`,
data: {
view: 'one',
ok: true
},
components
}).$mount()
sharedAssertions(vm, done)
})
it('exclude (array)', done => {
const vm = new Vue({
template: `
<div v-if="ok">
<keep-alive :exclude="['two']">
<component :is="view"></component>
</keep-alive>
</div>
`,
data: {
view: 'one',
ok: true
},
components
}).$mount()
sharedAssertions(vm, done)
})
it('include + exclude', done => {
const vm = new Vue({
template: `
<div v-if="ok">
<keep-alive include="one,two" exclude="two">
<component :is="view"></component>
</keep-alive>
</div>
`,
data: {
view: 'one',
ok: true
},
components
}).$mount()
sharedAssertions(vm, done)
})
it('prune cache on include/exclude change', done => {
const vm = new Vue({
template: `
<div>
<keep-alive :include="include">
<component :is="view"></component>
</keep-alive>
</div>
`,
data: {
view: 'one',
include: 'one,two'
},
components
}).$mount()
vm.view = 'two'
waitForUpdate(() => {
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 1, 0, 0])
vm.include = 'two'
}).then(() => {
assertHookCalls(one, [1, 1, 1, 1, 1])
assertHookCalls(two, [1, 1, 1, 0, 0])
vm.view = 'one'
}).then(() => {
assertHookCalls(one, [2, 2, 1, 1, 1])
assertHookCalls(two, [1, 1, 1, 1, 0])
}).then(done)
})
it('should not prune currently active instance', done => {
const vm = new Vue({
template: `
<div>
<keep-alive :include="include">
<component :is="view"></component>
</keep-alive>
</div>
`,
data: {
view: 'one',
include: 'one,two'
},
components
}).$mount()
vm.include = 'two'
waitForUpdate(() => {
assertHookCalls(one, [1, 1, 1, 0, 0])
assertHookCalls(two, [0, 0, 0, 0, 0])
vm.view = 'two'
}).then(() => {
assertHookCalls(one, [1, 1, 1, 0, 1])
assertHookCalls(two, [1, 1, 1, 0, 0])
}).then(done)
})
// #3882
it('deeply nested keep-alive should be destroyed properly', done => {
one.template = `<div><keep-alive><two></two></keep-alive></div>`
one.components = { two }
const vm = new Vue({
template: `<div><parent v-if="ok"></parent></div>`,
data: { ok: true },
components: {
parent: {
template: `<div><keep-alive><one></one></keep-alive></div>`,
components: { one }
}
}
}).$mount()
assertHookCalls(one, [1, 1, 1, 0, 0])
assertHookCalls(two, [1, 1, 1, 0, 0])
vm.ok = false
waitForUpdate(() => {
assertHookCalls(one, [1, 1, 1, 1, 1])
assertHookCalls(two, [1, 1, 1, 1, 1])
}).then(done)
})
// #4237
it('should update latest props/listeners for a re-activated component', done => {
const one = {
props: ['prop'],
template: `<div>one {{ prop }}</div>`
}
const two = {
props: ['prop'],
template: `<div>two {{ prop }}</div>`
}
const vm = new Vue({
data: { view: 'one', n: 1 },
template: `
<div>
<keep-alive>
<component :is="view" :prop="n"></component>
</keep-alive>
</div>
`,
components: { one, two }
}).$mount()
expect(vm.$el.textContent).toBe('one 1')
vm.n++
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('one 2')
vm.view = 'two'
}).then(() => {
expect(vm.$el.textContent).toBe('two 2')
}).then(done)
})
if (!isIE9) {
it('with transition-mode out-in', done => {
let next
const vm = new Vue({
template: `<div>
<transition name="test" mode="out-in" @after-leave="afterLeave">
<keep-alive>
<component :is="view" class="test"></component>
</keep-alive>
</transition>
</div>`,
data: {
view: 'one'
},
components,
methods: {
afterLeave () {
next()
}
}
}).$mount(el)
expect(vm.$el.textContent).toBe('one')
assertHookCalls(one, [1, 1, 1, 0, 0])
assertHookCalls(two, [0, 0, 0, 0, 0])
vm.view = 'two'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-leave test-leave-active">one</div><!---->'
)
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [0, 0, 0, 0, 0])
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-leave-active test-leave-to">one</div><!---->'
)
}).thenWaitFor(_next => { next = _next }).then(() => {
expect(vm.$el.innerHTML).toBe('<!---->')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-enter test-enter-active">two</div>'
)
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 1, 0, 0])
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-enter-active test-enter-to">two</div>'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test">two</div>'
)
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 1, 0, 0])
}).then(() => {
vm.view = 'one'
}).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-leave test-leave-active">two</div><!---->'
)
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 1, 1, 0])
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-leave-active test-leave-to">two</div><!---->'
)
}).thenWaitFor(_next => { next = _next }).then(() => {
expect(vm.$el.innerHTML).toBe('<!---->')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-enter test-enter-active">one</div>'
)
assertHookCalls(one, [1, 1, 2, 1, 0])
assertHookCalls(two, [1, 1, 1, 1, 0])
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-enter-active test-enter-to">one</div>'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test">one</div>'
)
assertHookCalls(one, [1, 1, 2, 1, 0])
assertHookCalls(two, [1, 1, 1, 1, 0])
}).then(done)
})
it('with transition-mode out-in + include', done => {
let next
const vm = new Vue({
template: `<div>
<transition name="test" mode="out-in" @after-leave="afterLeave">
<keep-alive include="one">
<component :is="view" class="test"></component>
</keep-alive>
</transition>
</div>`,
data: {
view: 'one'
},
components,
methods: {
afterLeave () {
next()
}
}
}).$mount(el)
expect(vm.$el.textContent).toBe('one')
assertHookCalls(one, [1, 1, 1, 0, 0])
assertHookCalls(two, [0, 0, 0, 0, 0])
vm.view = 'two'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-leave test-leave-active">one</div><!---->'
)
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [0, 0, 0, 0, 0])
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-leave-active test-leave-to">one</div><!---->'
)
}).thenWaitFor(_next => { next = _next }).then(() => {
expect(vm.$el.innerHTML).toBe('<!---->')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-enter test-enter-active">two</div>'
)
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 0, 0, 0])
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-enter-active test-enter-to">two</div>'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test">two</div>'
)
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 0, 0, 0])
}).then(() => {
vm.view = 'one'
}).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-leave test-leave-active">two</div><!---->'
)
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 0, 0, 1])
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-leave-active test-leave-to">two</div><!---->'
)
}).thenWaitFor(_next => { next = _next }).then(() => {
expect(vm.$el.innerHTML).toBe('<!---->')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-enter test-enter-active">one</div>'
)
assertHookCalls(one, [1, 1, 2, 1, 0])
assertHookCalls(two, [1, 1, 0, 0, 1])
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-enter-active test-enter-to">one</div>'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test">one</div>'
)
assertHookCalls(one, [1, 1, 2, 1, 0])
assertHookCalls(two, [1, 1, 0, 0, 1])
}).then(done)
})
it('with transition-mode in-out', done => {
let next
const vm = new Vue({
template: `<div>
<transition name="test" mode="in-out" @after-enter="afterEnter">
<keep-alive>
<component :is="view" class="test"></component>
</keep-alive>
</transition>
</div>`,
data: {
view: 'one'
},
components,
methods: {
afterEnter () {
next()
}
}
}).$mount(el)
expect(vm.$el.textContent).toBe('one')
assertHookCalls(one, [1, 1, 1, 0, 0])
assertHookCalls(two, [0, 0, 0, 0, 0])
vm.view = 'two'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test">one</div>' +
'<div class="test test-enter test-enter-active">two</div>'
)
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 1, 0, 0])
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test">one</div>' +
'<div class="test test-enter-active test-enter-to">two</div>'
)
}).thenWaitFor(_next => { next = _next }).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test">one</div>' +
'<div class="test">two</div>'
)
}).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-leave test-leave-active">one</div>' +
'<div class="test">two</div>'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-leave-active test-leave-to">one</div>' +
'<div class="test">two</div>'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test">two</div>'
)
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 1, 0, 0])
}).then(() => {
vm.view = 'one'
}).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test">two</div>' +
'<div class="test test-enter test-enter-active">one</div>'
)
assertHookCalls(one, [1, 1, 2, 1, 0])
assertHookCalls(two, [1, 1, 1, 1, 0])
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test">two</div>' +
'<div class="test test-enter-active test-enter-to">one</div>'
)
}).thenWaitFor(_next => { next = _next }).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test">two</div>' +
'<div class="test">one</div>'
)
}).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-leave test-leave-active">two</div>' +
'<div class="test">one</div>'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-leave-active test-leave-to">two</div>' +
'<div class="test">one</div>'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test">one</div>'
)
assertHookCalls(one, [1, 1, 2, 1, 0])
assertHookCalls(two, [1, 1, 1, 1, 0])
}).then(done)
})
it('dynamic components, in-out with early cancel', done => {
let next
const vm = new Vue({
template: `<div>
<transition name="test" mode="in-out" @after-enter="afterEnter">
<keep-alive>
<component :is="view" class="test"></component>
</keep-alive>
</transition>
</div>`,
data: { view: 'one' },
components,
methods: {
afterEnter () {
next()
}
}
}).$mount(el)
expect(vm.$el.textContent).toBe('one')
vm.view = 'two'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test">one</div>' +
'<div class="test test-enter test-enter-active">two</div>'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test">one</div>' +
'<div class="test test-enter-active test-enter-to">two</div>'
)
// switch again before enter finishes,
// this cancels both enter and leave.
vm.view = 'one'
}).then(() => {
// 1. the pending leaving "one" should be removed instantly.
// 2. the entering "two" should be placed into its final state instantly.
// 3. a new "one" is created and entering
expect(vm.$el.innerHTML).toBe(
'<div class="test">two</div>' +
'<div class="test test-enter test-enter-active">one</div>'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test">two</div>' +
'<div class="test test-enter-active test-enter-to">one</div>'
)
}).thenWaitFor(_next => { next = _next }).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test">two</div>' +
'<div class="test">one</div>'
)
}).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-leave test-leave-active">two</div>' +
'<div class="test">one</div>'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-leave-active test-leave-to">two</div>' +
'<div class="test">one</div>'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test">one</div>'
)
}).then(done).then(done)
})
// #4339
it('component with inner transition', done => {
const vm = new Vue({
template: `
<div>
<keep-alive>
<component ref="test" :is="view"></component>
</keep-alive>
</div>
`,
data: { view: 'foo' },
components: {
foo: { template: '<transition><div class="test">foo</div></transition>' },
bar: { template: '<transition name="test"><div class="test">bar</div></transition>' }
}
}).$mount(el)
// should not apply transition on initial render by default
expect(vm.$el.innerHTML).toBe('<div class="test">foo</div>')
vm.view = 'bar'
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test v-leave v-leave-active">foo</div>' +
'<div class="test test-enter test-enter-active">bar</div>'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test v-leave-active v-leave-to">foo</div>' +
'<div class="test test-enter-active test-enter-to">bar</div>'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test">bar</div>'
)
vm.view = 'foo'
}).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-leave test-leave-active">bar</div>' +
'<div class="test v-enter v-enter-active">foo</div>'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-leave-active test-leave-to">bar</div>' +
'<div class="test v-enter-active v-enter-to">foo</div>'
)
}).thenWaitFor(duration + buffer).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test">foo</div>'
)
}).then(done)
})
it('async components with transition-mode out-in', done => {
const barResolve = jasmine.createSpy('bar resolved')
let next
const foo = (resolve) => {
setTimeout(() => {
resolve(one)
Vue.nextTick(next)
}, duration / 2)
}
const bar = (resolve) => {
setTimeout(() => {
resolve(two)
barResolve()
}, duration / 2)
}
components = {
foo,
bar
}
const vm = new Vue({
template: `<div>
<transition name="test" mode="out-in" @after-enter="afterEnter" @after-leave="afterLeave">
<keep-alive>
<component :is="view" class="test"></component>
</keep-alive>
</transition>
</div>`,
data: {
view: 'foo'
},
components,
methods: {
afterEnter () {
next()
},
afterLeave () {
next()
}
}
}).$mount(el)
expect(vm.$el.textContent).toBe('')
next = () => {
assertHookCalls(one, [1, 1, 1, 0, 0])
assertHookCalls(two, [0, 0, 0, 0, 0])
waitForUpdate(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-enter test-enter-active">one</div>'
)
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-enter-active test-enter-to">one</div>'
)
}).thenWaitFor(_next => { next = _next }).then(() => {
// foo afterEnter get called
expect(vm.$el.innerHTML).toBe('<div class="test">one</div>')
vm.view = 'bar'
}).thenWaitFor(nextFrame).then(() => {
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [0, 0, 0, 0, 0])
expect(vm.$el.innerHTML).toBe(
'<div class="test test-leave-active test-leave-to">one</div><!---->'
)
}).thenWaitFor(_next => { next = _next }).then(() => {
// foo afterLeave get called
// and bar has already been resolved before afterLeave get called
expect(barResolve.calls.count()).toBe(1)
expect(vm.$el.innerHTML).toBe('<!---->')
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-enter test-enter-active">two</div>'
)
assertHookCalls(one, [1, 1, 1, 1, 0])
assertHookCalls(two, [1, 1, 1, 0, 0])
}).thenWaitFor(nextFrame).then(() => {
expect(vm.$el.innerHTML).toBe(
'<div class="test test-enter-active test-enter-to">two</div>'
)
}).thenWaitFor(_next => { next = _next }).then(() => {
// bar afterEnter get called
expect(vm.$el.innerHTML).toBe('<div class="test">two</div>')
}).then(done)
}
})
it('max', done => {
const spyA = jasmine.createSpy()
const spyB = jasmine.createSpy()
const spyC = jasmine.createSpy()
const spyAD = jasmine.createSpy()
const spyBD = jasmine.createSpy()
const spyCD = jasmine.createSpy()
function assertCount (calls) {
expect([
spyA.calls.count(),
spyAD.calls.count(),
spyB.calls.count(),
spyBD.calls.count(),
spyC.calls.count(),
spyCD.calls.count()
]).toEqual(calls)
}
const vm = new Vue({
template: `
<keep-alive max="2">
<component :is="n"></component>
</keep-alive>
`,
data: {
n: 'aa'
},
components: {
aa: {
template: '<div>a</div>',
created: spyA,
destroyed: spyAD
},
bb: {
template: '<div>bbb</div>',
created: spyB,
destroyed: spyBD
},
cc: {
template: '<div>ccc</div>',
created: spyC,
destroyed: spyCD
}
}
}).$mount()
assertCount([1, 0, 0, 0, 0, 0])
vm.n = 'bb'
waitForUpdate(() => {
assertCount([1, 0, 1, 0, 0, 0])
vm.n = 'cc'
}).then(() => {
// should prune A because max cache reached
assertCount([1, 1, 1, 0, 1, 0])
vm.n = 'bb'
}).then(() => {
// B should be reused, and made latest
assertCount([1, 1, 1, 0, 1, 0])
vm.n = 'aa'
}).then(() => {
// C should be pruned because B was used last so C is the oldest cached
assertCount([2, 1, 1, 0, 1, 1])
}).then(done)
})
}
})
| test/unit/features/component/component-keep-alive.spec.js | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.0001781854807632044,
0.00017333436699118465,
0.0001676564133958891,
0.0001732281962176785,
0.0000020586312530213036
] |
{
"id": 1,
"code_window": [
" '>': '>',\n",
" '"': '\"',\n",
" '&': '&',\n",
" ' ': '\\n'\n",
"}\n",
"const encodedAttr = /&(?:lt|gt|quot|amp);/g\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" ' ': '\\n',\n",
" '	': '\\t'\n"
],
"file_path": "src/compiler/parser/html-parser.js",
"type": "replace",
"edit_start_line_idx": 41
} | /* @flow */
import config from 'core/config'
import { warn, cached } from 'core/util/index'
import { mark, measure } from 'core/util/perf'
import Vue from './runtime/index'
import { query } from './util/index'
import { shouldDecodeNewlines } from './util/compat'
import { compileToFunctions } from './compiler/index'
const idToTemplate = cached(id => {
const el = query(id)
return el && el.innerHTML
})
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && query(el)
/* istanbul ignore if */
if (el === document.body || el === document.documentElement) {
process.env.NODE_ENV !== 'production' && warn(
`Do not mount Vue to <html> or <body> - mount to normal elements instead.`
)
return this
}
const options = this.$options
// resolve template/el and convert to render function
if (!options.render) {
let template = options.template
if (template) {
if (typeof template === 'string') {
if (template.charAt(0) === '#') {
template = idToTemplate(template)
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && !template) {
warn(
`Template element not found or is empty: ${options.template}`,
this
)
}
}
} else if (template.nodeType) {
template = template.innerHTML
} else {
if (process.env.NODE_ENV !== 'production') {
warn('invalid template option:' + template, this)
}
return this
}
} else if (el) {
template = getOuterHTML(el)
}
if (template) {
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile')
}
const { render, staticRenderFns } = compileToFunctions(template, {
shouldDecodeNewlines,
delimiters: options.delimiters,
comments: options.comments
}, this)
options.render = render
options.staticRenderFns = staticRenderFns
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile end')
measure(`vue ${this._name} compile`, 'compile', 'compile end')
}
}
}
return mount.call(this, el, hydrating)
}
/**
* Get outerHTML of elements, taking care
* of SVG elements in IE as well.
*/
function getOuterHTML (el: Element): string {
if (el.outerHTML) {
return el.outerHTML
} else {
const container = document.createElement('div')
container.appendChild(el.cloneNode(true))
return container.innerHTML
}
}
Vue.compile = compileToFunctions
export default Vue
| src/platforms/web/entry-runtime-with-compiler.js | 1 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00017627842316869646,
0.00017156398098450154,
0.00016650061297696084,
0.00017189056961797178,
0.0000032479510991834104
] |
{
"id": 1,
"code_window": [
" '>': '>',\n",
" '"': '\"',\n",
" '&': '&',\n",
" ' ': '\\n'\n",
"}\n",
"const encodedAttr = /&(?:lt|gt|quot|amp);/g\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" ' ': '\\n',\n",
" '	': '\\t'\n"
],
"file_path": "src/compiler/parser/html-parser.js",
"type": "replace",
"edit_start_line_idx": 41
} | <!DOCTYPE html>
<html lang="en">
<head>
<title>vue.js version</title>
<script src="https://cdn.jsdelivr.net/stats.js/r11/stats.min.js"></script>
<script src="../../dist/vue.min.js"></script>
<style>
html, body {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
}
svg {
width: 800px;
height: 600px;
}
</style>
</head>
<body>
<h1>Animating 1000 SVG dots</h1>
<div id="app">
<p>
<button @click="toggleOptimization">
{{ optimized ? 'disable' : 'enable' }} optimization (Object.freeze)
</button>
</p>
<svg>
<circle v-for='point in model.points' :cx='point.x' :cy='point.y' r='2px' fill='#FC309D'></circle>
</svg>
</div>
<script type="text/javascript" charset="utf-8">
var stats = new Stats()
stats.setMode(0)
stats.domElement.style.position = 'absolute'
stats.domElement.style.right = '0px'
stats.domElement.style.top = '0px'
document.body.appendChild(stats.domElement)
var WIDTH = 800
var HEIGHT = 600
new Vue({
el: '#app',
data: {
model: createModel(1000),
optimized: false
},
created: function () {
var self = this
requestAnimationFrame(render)
stats.begin()
function render () {
stats.end()
stats.begin()
requestAnimationFrame(render)
self.model.step()
if (self.optimized) {
self.$forceUpdate()
}
}
},
methods: {
toggleOptimization: function () {
this.model = this.optimized
? createModel(1000)
: Object.freeze(createModel(1000))
this.optimized = !this.optimized
}
}
});
function createModel (count) {
var points = []
for (var i = 0; i < count; ++i) {
points.push({
x: Math.random() * WIDTH,
y: Math.random() * HEIGHT,
vx: Math.random() * 4 - 2,
vy: Math.random() * 4 - 2
})
}
return {
points: points,
step: step
}
function step () {
points.forEach(move)
}
function move (p) {
if (p.x > WIDTH || p.x < 0) p.vx *= -1
if (p.y > HEIGHT || p.y < 0) p.vy *= -1
p.y += p.vy
p.x += p.vx
}
}
</script>
</body>
</html>
| benchmarks/svg/index.html | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00017602262960281223,
0.00017308793030679226,
0.0001702182344160974,
0.00017361233767587692,
0.0000020378679437271785
] |
{
"id": 1,
"code_window": [
" '>': '>',\n",
" '"': '\"',\n",
" '&': '&',\n",
" ' ': '\\n'\n",
"}\n",
"const encodedAttr = /&(?:lt|gt|quot|amp);/g\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" ' ': '\\n',\n",
" '	': '\\t'\n"
],
"file_path": "src/compiler/parser/html-parser.js",
"type": "replace",
"edit_start_line_idx": 41
} | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Vue.js SVG graph example</title>
<link rel="stylesheet" href="style.css">
<!-- Delete ".min" for console warnings in development -->
<script src="../../dist/vue.min.js"></script>
<script src="https://unpkg.com/marky/dist/marky.min.js"></script>
</head>
<body>
<!-- template for the polygraph component. -->
<script type="text/x-template" id="polygraph-template">
<g>
<polygon :points="points"></polygon>
<circle cx="100" cy="100" r="80"></circle>
<axis-label
v-for="(stat, index) in stats"
:stat="stat"
:index="index"
:total="stats.length">
</axis-label>
</g>
</script>
<!-- template for the axis label component. -->
<script type="text/x-template" id="axis-label-template">
<text :x="point.x" :y="point.y">{{stat.label}}</text>
</script>
<!-- demo root element -->
<div id="demo">
<!-- Use the component -->
<svg width="200" height="200">
<polygraph :stats="stats"></polygraph>
</svg>
<!-- controls -->
<div v-for="stat in stats">
<label>{{stat.label}}</label>
<input type="range" v-model="stat.value" min="0" max="100">
<span>{{stat.value}}</span>
<button @click="remove(stat)" class="remove">X</button>
</div>
<form id="add">
<input name="newlabel" v-model="newLabel">
<button @click="add">Add a Stat</button>
</form>
<pre id="raw">{{ stats }}</pre>
</div>
<p style="font-size:12px">* input[type="range"] requires IE10 or above.</p>
<script src="svg.js"></script>
</body>
</html>
| examples/svg/index.html | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00017209076031576842,
0.0001694627571851015,
0.0001653740619076416,
0.00016989093273878098,
0.0000022122158043202944
] |
{
"id": 1,
"code_window": [
" '>': '>',\n",
" '"': '\"',\n",
" '&': '&',\n",
" ' ': '\\n'\n",
"}\n",
"const encodedAttr = /&(?:lt|gt|quot|amp);/g\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" ' ': '\\n',\n",
" '	': '\\t'\n"
],
"file_path": "src/compiler/parser/html-parser.js",
"type": "replace",
"edit_start_line_idx": 41
} | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
<title>Vue.js elastic header example</title>
<!-- Delete ".min" for console warnings in development -->
<script src="../../dist/vue.min.js"></script>
<script src="http://dynamicsjs.com/lib/dynamics.js"></script>
<link rel="stylesheet" href="style.css">
<!-- template for the component -->
<script type="text/x-template" id="header-view-template">
<div class="draggable-header-view"
@mousedown="startDrag" @touchstart="startDrag"
@mousemove="onDrag" @touchmove="onDrag"
@mouseup="stopDrag" @touchend="stopDrag" @mouseleave="stopDrag">
<svg class="bg" width="320" height="560">
<path :d="headerPath" fill="#3F51B5"></path>
</svg>
<div class="header">
<slot name="header"></slot>
</div>
<div class="content" :style="contentPosition">
<slot name="content"></slot>
</div>
</div>
</script>
</head>
<body>
<div id="app" @touchmove.prevent>
<draggable-header-view>
<template slot="header">
<h1>Elastic Draggable SVG Header</h1>
<p>with <a href="https://vuejs.org">Vue.js</a> + <a href="http://dynamicsjs.com">dynamics.js</a></p>
</template>
<template slot="content">
<p>Note this is just an effect demo - there are of course many additional details if you want to use this in production, e.g. handling responsive sizes, reload threshold and content scrolling. Those are out of scope for this quick little hack. However, the idea is that you can hide them as internal details of a Vue.js component and expose a simple Web-Component-like interface.</p>
</template>
</draggable-header-view>
</div>
<script>
Vue.component('draggable-header-view', {
template: '#header-view-template',
data: function () {
return {
dragging: false,
// quadratic bezier control point
c: { x: 160, y: 160 },
// record drag start point
start: { x: 0, y: 0 }
}
},
computed: {
headerPath: function () {
return 'M0,0 L320,0 320,160' +
'Q' + this.c.x + ',' + this.c.y +
' 0,160'
},
contentPosition: function () {
var dy = this.c.y - 160
var dampen = dy > 0 ? 2 : 4
return {
transform: 'translate3d(0,' + dy / dampen + 'px,0)'
}
}
},
methods: {
startDrag: function (e) {
e = e.changedTouches ? e.changedTouches[0] : e
this.dragging = true
this.start.x = e.pageX
this.start.y = e.pageY
},
onDrag: function (e) {
e = e.changedTouches ? e.changedTouches[0] : e
if (this.dragging) {
this.c.x = 160 + (e.pageX - this.start.x)
// dampen vertical drag by a factor
var dy = e.pageY - this.start.y
var dampen = dy > 0 ? 1.5 : 4
this.c.y = 160 + dy / dampen
}
},
stopDrag: function () {
if (this.dragging) {
this.dragging = false
dynamics.animate(this.c, {
x: 160,
y: 160
}, {
type: dynamics.spring,
duration: 700,
friction: 280
})
}
}
}
})
new Vue({ el: '#app' })
</script>
</body>
</html>
| examples/elastic-header/index.html | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00017520949768368155,
0.00016989420691970736,
0.00016493785369675606,
0.00016941461944952607,
0.0000032505438412044896
] |
{
"id": 2,
"code_window": [
"}\n",
"const encodedAttr = /&(?:lt|gt|quot|amp);/g\n",
"const encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10);/g\n",
"\n",
"// #5992\n",
"const isIgnoreNewlineTag = makeMap('pre,textarea', true)\n",
"const shouldIgnoreFirstNewline = (tag, html) => tag && isIgnoreNewlineTag(tag) && html[0] === '\\n'\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10|#9);/g\n"
],
"file_path": "src/compiler/parser/html-parser.js",
"type": "replace",
"edit_start_line_idx": 44
} | /* @flow */
import config from 'core/config'
import { warn, cached } from 'core/util/index'
import { mark, measure } from 'core/util/perf'
import Vue from './runtime/index'
import { query } from './util/index'
import { shouldDecodeNewlines } from './util/compat'
import { compileToFunctions } from './compiler/index'
const idToTemplate = cached(id => {
const el = query(id)
return el && el.innerHTML
})
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && query(el)
/* istanbul ignore if */
if (el === document.body || el === document.documentElement) {
process.env.NODE_ENV !== 'production' && warn(
`Do not mount Vue to <html> or <body> - mount to normal elements instead.`
)
return this
}
const options = this.$options
// resolve template/el and convert to render function
if (!options.render) {
let template = options.template
if (template) {
if (typeof template === 'string') {
if (template.charAt(0) === '#') {
template = idToTemplate(template)
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && !template) {
warn(
`Template element not found or is empty: ${options.template}`,
this
)
}
}
} else if (template.nodeType) {
template = template.innerHTML
} else {
if (process.env.NODE_ENV !== 'production') {
warn('invalid template option:' + template, this)
}
return this
}
} else if (el) {
template = getOuterHTML(el)
}
if (template) {
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile')
}
const { render, staticRenderFns } = compileToFunctions(template, {
shouldDecodeNewlines,
delimiters: options.delimiters,
comments: options.comments
}, this)
options.render = render
options.staticRenderFns = staticRenderFns
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile end')
measure(`vue ${this._name} compile`, 'compile', 'compile end')
}
}
}
return mount.call(this, el, hydrating)
}
/**
* Get outerHTML of elements, taking care
* of SVG elements in IE as well.
*/
function getOuterHTML (el: Element): string {
if (el.outerHTML) {
return el.outerHTML
} else {
const container = document.createElement('div')
container.appendChild(el.cloneNode(true))
return container.innerHTML
}
}
Vue.compile = compileToFunctions
export default Vue
| src/platforms/web/entry-runtime-with-compiler.js | 1 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.005907169543206692,
0.0007443967624567449,
0.00016819313168525696,
0.00017132519860751927,
0.0017209249781444669
] |
{
"id": 2,
"code_window": [
"}\n",
"const encodedAttr = /&(?:lt|gt|quot|amp);/g\n",
"const encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10);/g\n",
"\n",
"// #5992\n",
"const isIgnoreNewlineTag = makeMap('pre,textarea', true)\n",
"const shouldIgnoreFirstNewline = (tag, html) => tag && isIgnoreNewlineTag(tag) && html[0] === '\\n'\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10|#9);/g\n"
],
"file_path": "src/compiler/parser/html-parser.js",
"type": "replace",
"edit_start_line_idx": 44
} | import Vue from 'vue'
describe('Global API: mixin', () => {
let options
beforeEach(() => { options = Vue.options })
afterEach(() => { Vue.options = options })
it('should work', () => {
const spy = jasmine.createSpy('global mixin')
Vue.mixin({
created () {
spy(this.$options.myOption)
}
})
new Vue({
myOption: 'hello'
})
expect(spy).toHaveBeenCalledWith('hello')
})
it('should work for constructors created before mixin is applied', () => {
const calls = []
const Test = Vue.extend({
name: 'test',
beforeCreate () {
calls.push(this.$options.myOption + ' local')
}
})
Vue.mixin({
beforeCreate () {
calls.push(this.$options.myOption + ' global')
}
})
expect(Test.options.name).toBe('test')
new Test({
myOption: 'hello'
})
expect(calls).toEqual(['hello global', 'hello local'])
})
// #3957
it('should work for global props', () => {
const Test = Vue.extend({
template: `<div>{{ prop }}</div>`
})
Vue.mixin({
props: ['prop']
})
// test child component
const vm = new Vue({
template: '<test prop="hi"></test>',
components: { Test }
}).$mount()
expect(vm.$el.textContent).toBe('hi')
})
// vue-loader#433
it('should not drop late-set render functions', () => {
const Test = Vue.extend({})
Test.options.render = h => h('div', 'hello')
Vue.mixin({})
const vm = new Vue({
render: h => h(Test)
}).$mount()
expect(vm.$el.textContent).toBe('hello')
})
// #4266
it('should not drop scopedId', () => {
const Test = Vue.extend({})
Test.options._scopeId = 'foo'
Vue.mixin({})
const vm = new Test({
template: '<div><p>hi</p></div>'
}).$mount()
expect(vm.$el.children[0].hasAttribute('foo')).toBe(true)
})
// #4976
it('should not drop late-attached custom options on existing constructors', () => {
const baseSpy = jasmine.createSpy('base')
const Base = Vue.extend({
beforeCreate: baseSpy
})
const Test = Base.extend({})
// Inject options later
// vue-loader and vue-hot-reload-api are doing like this
Test.options.computed = {
$style: () => 123
}
const spy = jasmine.createSpy('late attached')
Test.options.beforeCreate = Test.options.beforeCreate.concat(spy)
// Update super constructor's options
const mixinSpy = jasmine.createSpy('mixin')
Vue.mixin({
beforeCreate: mixinSpy
})
// mount the component
const vm = new Test({
template: '<div>{{ $style }}</div>'
}).$mount()
expect(spy.calls.count()).toBe(1)
expect(baseSpy.calls.count()).toBe(1)
expect(mixinSpy.calls.count()).toBe(1)
expect(vm.$el.textContent).toBe('123')
expect(vm.$style).toBe(123)
// Should not be dropped
expect(Test.options.computed.$style()).toBe(123)
expect(Test.options.beforeCreate).toEqual([mixinSpy, baseSpy, spy])
})
// vue-class-component#83
it('should work for a constructor mixin', () => {
const spy = jasmine.createSpy('global mixin')
const Mixin = Vue.extend({
created () {
spy(this.$options.myOption)
}
})
Vue.mixin(Mixin)
new Vue({
myOption: 'hello'
})
expect(spy).toHaveBeenCalledWith('hello')
})
// vue-class-component#87
it('should not drop original lifecycle hooks', () => {
const base = jasmine.createSpy('base')
const Base = Vue.extend({
beforeCreate: base
})
const injected = jasmine.createSpy('injected')
// inject a function
Base.options.beforeCreate = Base.options.beforeCreate.concat(injected)
Vue.mixin({})
new Base({})
expect(base).toHaveBeenCalled()
expect(injected).toHaveBeenCalled()
})
})
| test/unit/features/global-api/mixin.spec.js | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00017722473421599716,
0.00017346952517982572,
0.0001702399895293638,
0.00017362242215313017,
0.0000017426854128643754
] |
{
"id": 2,
"code_window": [
"}\n",
"const encodedAttr = /&(?:lt|gt|quot|amp);/g\n",
"const encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10);/g\n",
"\n",
"// #5992\n",
"const isIgnoreNewlineTag = makeMap('pre,textarea', true)\n",
"const shouldIgnoreFirstNewline = (tag, html) => tag && isIgnoreNewlineTag(tag) && html[0] === '\\n'\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10|#9);/g\n"
],
"file_path": "src/compiler/parser/html-parser.js",
"type": "replace",
"edit_start_line_idx": 44
} | module.exports = {
'grid': function (browser) {
var columns = ['name', 'power']
browser
.url('http://localhost:8080/examples/grid/')
.waitForElementVisible('table', 1000)
.assert.count('th', 2)
.assert.count('th.active', 0)
.assert.containsText('th:nth-child(1)', 'Name')
.assert.containsText('th:nth-child(2)', 'Power')
assertTable([
{ name: 'Chuck Norris', power: Infinity },
{ name: 'Bruce Lee', power: 9000 },
{ name: 'Jackie Chan', power: 7000 },
{ name: 'Jet Li', power: 8000 }
])
browser
.click('th:nth-child(1)')
.assert.count('th.active:nth-child(1)', 1)
.assert.count('th.active:nth-child(2)', 0)
.assert.count('th:nth-child(1) .arrow.dsc', 1)
.assert.count('th:nth-child(2) .arrow.dsc', 0)
assertTable([
{ name: 'Jet Li', power: 8000 },
{ name: 'Jackie Chan', power: 7000 },
{ name: 'Chuck Norris', power: Infinity },
{ name: 'Bruce Lee', power: 9000 }
])
browser
.click('th:nth-child(2)')
.assert.count('th.active:nth-child(1)', 0)
.assert.count('th.active:nth-child(2)', 1)
.assert.count('th:nth-child(1) .arrow.dsc', 1)
.assert.count('th:nth-child(2) .arrow.dsc', 1)
assertTable([
{ name: 'Chuck Norris', power: Infinity },
{ name: 'Bruce Lee', power: 9000 },
{ name: 'Jet Li', power: 8000 },
{ name: 'Jackie Chan', power: 7000 }
])
browser
.click('th:nth-child(2)')
.assert.count('th.active:nth-child(1)', 0)
.assert.count('th.active:nth-child(2)', 1)
.assert.count('th:nth-child(1) .arrow.dsc', 1)
.assert.count('th:nth-child(2) .arrow.asc', 1)
assertTable([
{ name: 'Jackie Chan', power: 7000 },
{ name: 'Jet Li', power: 8000 },
{ name: 'Bruce Lee', power: 9000 },
{ name: 'Chuck Norris', power: Infinity }
])
browser
.click('th:nth-child(1)')
.assert.count('th.active:nth-child(1)', 1)
.assert.count('th.active:nth-child(2)', 0)
.assert.count('th:nth-child(1) .arrow.asc', 1)
.assert.count('th:nth-child(2) .arrow.asc', 1)
assertTable([
{ name: 'Bruce Lee', power: 9000 },
{ name: 'Chuck Norris', power: Infinity },
{ name: 'Jackie Chan', power: 7000 },
{ name: 'Jet Li', power: 8000 }
])
browser
.setValue('input[name="query"]', 'j')
assertTable([
{ name: 'Jackie Chan', power: 7000 },
{ name: 'Jet Li', power: 8000 }
])
browser
.clearValue('input[name="query"]')
.setValue('input[name="query"]', 'infinity')
assertTable([
{ name: 'Chuck Norris', power: Infinity }
])
browser
.clearValue('input[name="query"]')
.assert.count('p', 0)
.setValue('input[name="query"]', 'stringthatdoesnotexistanywhere')
.assert.count('p', 1)
browser.end()
function assertTable (data) {
browser.assert.count('td', data.length * columns.length)
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < columns.length; j++) {
browser.assert.containsText(
'tr:nth-child(' + (i + 1) + ') td:nth-child(' + (j + 1) + ')',
data[i][columns[j]]
)
}
}
}
}
}
| test/e2e/specs/grid.js | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00017567705071996897,
0.00017362793732900172,
0.0001700783905107528,
0.00017424968245904893,
0.0000016986549553621444
] |
{
"id": 2,
"code_window": [
"}\n",
"const encodedAttr = /&(?:lt|gt|quot|amp);/g\n",
"const encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10);/g\n",
"\n",
"// #5992\n",
"const isIgnoreNewlineTag = makeMap('pre,textarea', true)\n",
"const shouldIgnoreFirstNewline = (tag, html) => tag && isIgnoreNewlineTag(tag) && html[0] === '\\n'\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10|#9);/g\n"
],
"file_path": "src/compiler/parser/html-parser.js",
"type": "replace",
"edit_start_line_idx": 44
} | /* @flow */
const SourceMapConsumer = require('source-map').SourceMapConsumer
const filenameRE = /\(([^)]+\.js):(\d+):(\d+)\)$/
export function createSourceMapConsumers (rawMaps: Object) {
const maps = {}
Object.keys(rawMaps).forEach(file => {
maps[file] = new SourceMapConsumer(rawMaps[file])
})
return maps
}
export function rewriteErrorTrace (e: any, mapConsumers: {
[key: string]: SourceMapConsumer
}) {
if (e && typeof e.stack === 'string') {
e.stack = e.stack.split('\n').map(line => {
return rewriteTraceLine(line, mapConsumers)
}).join('\n')
}
}
function rewriteTraceLine (trace: string, mapConsumers: {
[key: string]: SourceMapConsumer
}) {
const m = trace.match(filenameRE)
const map = m && mapConsumers[m[1]]
if (m != null && map) {
const originalPosition = map.originalPositionFor({
line: Number(m[2]),
column: Number(m[3])
})
if (originalPosition.source != null) {
const { source, line, column } = originalPosition
const mappedPosition = `(${source.replace(/^webpack:\/\/\//, '')}:${String(line)}:${String(column)})`
return trace.replace(filenameRE, mappedPosition)
} else {
return trace
}
} else {
return trace
}
}
| src/server/bundle-renderer/source-map-support.js | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00017677278083283454,
0.00017274993297178298,
0.00016988211427815259,
0.00017279860912822187,
0.0000024823857529554516
] |
{
"id": 3,
"code_window": [
" if (args[4] === '') { delete args[4] }\n",
" if (args[5] === '') { delete args[5] }\n",
" }\n",
" const value = args[3] || args[4] || args[5] || ''\n",
" attrs[i] = {\n",
" name: args[1],\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" const shouldDecodeNewlines = tagName === 'a' && args[1] === 'href'\n",
" ? options.shouldDecodeNewlinesForHref\n",
" : options.shouldDecodeNewlines\n"
],
"file_path": "src/compiler/parser/html-parser.js",
"type": "add",
"edit_start_line_idx": 235
} | /**
* Not type-checking this file because it's mostly vendor code.
*/
/*!
* HTML Parser By John Resig (ejohn.org)
* Modified by Juriy "kangax" Zaytsev
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*/
import { makeMap, no } from 'shared/util'
import { isNonPhrasingTag } from 'web/compiler/util'
// Regular Expressions for parsing tags and attributes
const attribute = /^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/
// could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName
// but for Vue templates we can enforce a simple charset
const ncname = '[a-zA-Z_][\\w\\-\\.]*'
const qnameCapture = `((?:${ncname}\\:)?${ncname})`
const startTagOpen = new RegExp(`^<${qnameCapture}`)
const startTagClose = /^\s*(\/?)>/
const endTag = new RegExp(`^<\\/${qnameCapture}[^>]*>`)
const doctype = /^<!DOCTYPE [^>]+>/i
const comment = /^<!--/
const conditionalComment = /^<!\[/
let IS_REGEX_CAPTURING_BROKEN = false
'x'.replace(/x(.)?/g, function (m, g) {
IS_REGEX_CAPTURING_BROKEN = g === ''
})
// Special Elements (can contain anything)
export const isPlainTextElement = makeMap('script,style,textarea', true)
const reCache = {}
const decodingMap = {
'<': '<',
'>': '>',
'"': '"',
'&': '&',
' ': '\n'
}
const encodedAttr = /&(?:lt|gt|quot|amp);/g
const encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10);/g
// #5992
const isIgnoreNewlineTag = makeMap('pre,textarea', true)
const shouldIgnoreFirstNewline = (tag, html) => tag && isIgnoreNewlineTag(tag) && html[0] === '\n'
function decodeAttr (value, shouldDecodeNewlines) {
const re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr
return value.replace(re, match => decodingMap[match])
}
export function parseHTML (html, options) {
const stack = []
const expectHTML = options.expectHTML
const isUnaryTag = options.isUnaryTag || no
const canBeLeftOpenTag = options.canBeLeftOpenTag || no
let index = 0
let last, lastTag
while (html) {
last = html
// Make sure we're not in a plaintext content element like script/style
if (!lastTag || !isPlainTextElement(lastTag)) {
let textEnd = html.indexOf('<')
if (textEnd === 0) {
// Comment:
if (comment.test(html)) {
const commentEnd = html.indexOf('-->')
if (commentEnd >= 0) {
if (options.shouldKeepComment) {
options.comment(html.substring(4, commentEnd))
}
advance(commentEnd + 3)
continue
}
}
// http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment
if (conditionalComment.test(html)) {
const conditionalEnd = html.indexOf(']>')
if (conditionalEnd >= 0) {
advance(conditionalEnd + 2)
continue
}
}
// Doctype:
const doctypeMatch = html.match(doctype)
if (doctypeMatch) {
advance(doctypeMatch[0].length)
continue
}
// End tag:
const endTagMatch = html.match(endTag)
if (endTagMatch) {
const curIndex = index
advance(endTagMatch[0].length)
parseEndTag(endTagMatch[1], curIndex, index)
continue
}
// Start tag:
const startTagMatch = parseStartTag()
if (startTagMatch) {
handleStartTag(startTagMatch)
if (shouldIgnoreFirstNewline(lastTag, html)) {
advance(1)
}
continue
}
}
let text, rest, next
if (textEnd >= 0) {
rest = html.slice(textEnd)
while (
!endTag.test(rest) &&
!startTagOpen.test(rest) &&
!comment.test(rest) &&
!conditionalComment.test(rest)
) {
// < in plain text, be forgiving and treat it as text
next = rest.indexOf('<', 1)
if (next < 0) break
textEnd += next
rest = html.slice(textEnd)
}
text = html.substring(0, textEnd)
advance(textEnd)
}
if (textEnd < 0) {
text = html
html = ''
}
if (options.chars && text) {
options.chars(text)
}
} else {
let endTagLength = 0
const stackedTag = lastTag.toLowerCase()
const reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i'))
const rest = html.replace(reStackedTag, function (all, text, endTag) {
endTagLength = endTag.length
if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') {
text = text
.replace(/<!--([\s\S]*?)-->/g, '$1')
.replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1')
}
if (shouldIgnoreFirstNewline(stackedTag, text)) {
text = text.slice(1)
}
if (options.chars) {
options.chars(text)
}
return ''
})
index += html.length - rest.length
html = rest
parseEndTag(stackedTag, index - endTagLength, index)
}
if (html === last) {
options.chars && options.chars(html)
if (process.env.NODE_ENV !== 'production' && !stack.length && options.warn) {
options.warn(`Mal-formatted tag at end of template: "${html}"`)
}
break
}
}
// Clean up any remaining tags
parseEndTag()
function advance (n) {
index += n
html = html.substring(n)
}
function parseStartTag () {
const start = html.match(startTagOpen)
if (start) {
const match = {
tagName: start[1],
attrs: [],
start: index
}
advance(start[0].length)
let end, attr
while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) {
advance(attr[0].length)
match.attrs.push(attr)
}
if (end) {
match.unarySlash = end[1]
advance(end[0].length)
match.end = index
return match
}
}
}
function handleStartTag (match) {
const tagName = match.tagName
const unarySlash = match.unarySlash
if (expectHTML) {
if (lastTag === 'p' && isNonPhrasingTag(tagName)) {
parseEndTag(lastTag)
}
if (canBeLeftOpenTag(tagName) && lastTag === tagName) {
parseEndTag(tagName)
}
}
const unary = isUnaryTag(tagName) || !!unarySlash
const l = match.attrs.length
const attrs = new Array(l)
for (let i = 0; i < l; i++) {
const args = match.attrs[i]
// hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778
if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) {
if (args[3] === '') { delete args[3] }
if (args[4] === '') { delete args[4] }
if (args[5] === '') { delete args[5] }
}
const value = args[3] || args[4] || args[5] || ''
attrs[i] = {
name: args[1],
value: decodeAttr(
value,
options.shouldDecodeNewlines
)
}
}
if (!unary) {
stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs })
lastTag = tagName
}
if (options.start) {
options.start(tagName, attrs, unary, match.start, match.end)
}
}
function parseEndTag (tagName, start, end) {
let pos, lowerCasedTagName
if (start == null) start = index
if (end == null) end = index
if (tagName) {
lowerCasedTagName = tagName.toLowerCase()
}
// Find the closest opened tag of the same type
if (tagName) {
for (pos = stack.length - 1; pos >= 0; pos--) {
if (stack[pos].lowerCasedTag === lowerCasedTagName) {
break
}
}
} else {
// If no tag name is provided, clean shop
pos = 0
}
if (pos >= 0) {
// Close all the open elements, up the stack
for (let i = stack.length - 1; i >= pos; i--) {
if (process.env.NODE_ENV !== 'production' &&
(i > pos || !tagName) &&
options.warn
) {
options.warn(
`tag <${stack[i].tag}> has no matching end tag.`
)
}
if (options.end) {
options.end(stack[i].tag, start, end)
}
}
// Remove the open elements from the stack
stack.length = pos
lastTag = pos && stack[pos - 1].tag
} else if (lowerCasedTagName === 'br') {
if (options.start) {
options.start(tagName, [], true, start, end)
}
} else if (lowerCasedTagName === 'p') {
if (options.start) {
options.start(tagName, [], false, start, end)
}
if (options.end) {
options.end(tagName, start, end)
}
}
}
}
| src/compiler/parser/html-parser.js | 1 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.998479425907135,
0.032794393599033356,
0.00016652235353831202,
0.00017153113731183112,
0.1763126701116562
] |
{
"id": 3,
"code_window": [
" if (args[4] === '') { delete args[4] }\n",
" if (args[5] === '') { delete args[5] }\n",
" }\n",
" const value = args[3] || args[4] || args[5] || ''\n",
" attrs[i] = {\n",
" name: args[1],\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" const shouldDecodeNewlines = tagName === 'a' && args[1] === 'href'\n",
" ? options.shouldDecodeNewlinesForHref\n",
" : options.shouldDecodeNewlines\n"
],
"file_path": "src/compiler/parser/html-parser.js",
"type": "add",
"edit_start_line_idx": 235
} | export default {
}
| src/platforms/weex/runtime/directives/index.js | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00016496237367391586,
0.00016496237367391586,
0.00016496237367391586,
0.00016496237367391586,
0
] |
{
"id": 3,
"code_window": [
" if (args[4] === '') { delete args[4] }\n",
" if (args[5] === '') { delete args[5] }\n",
" }\n",
" const value = args[3] || args[4] || args[5] || ''\n",
" attrs[i] = {\n",
" name: args[1],\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" const shouldDecodeNewlines = tagName === 'a' && args[1] === 'href'\n",
" ? options.shouldDecodeNewlinesForHref\n",
" : options.shouldDecodeNewlines\n"
],
"file_path": "src/compiler/parser/html-parser.js",
"type": "add",
"edit_start_line_idx": 235
} | /* @flow */
import {
isDef,
isUndef
} from 'shared/util'
import {
concat,
stringifyClass,
genClassForVnode
} from 'web/util/index'
function updateClass (oldVnode: any, vnode: any) {
const el = vnode.elm
const data: VNodeData = vnode.data
const oldData: VNodeData = oldVnode.data
if (
isUndef(data.staticClass) &&
isUndef(data.class) && (
isUndef(oldData) || (
isUndef(oldData.staticClass) &&
isUndef(oldData.class)
)
)
) {
return
}
let cls = genClassForVnode(vnode)
// handle transition classes
const transitionClass = el._transitionClasses
if (isDef(transitionClass)) {
cls = concat(cls, stringifyClass(transitionClass))
}
// set the class
if (cls !== el._prevClass) {
el.setAttribute('class', cls)
el._prevClass = cls
}
}
export default {
create: updateClass,
update: updateClass
}
| src/platforms/web/runtime/modules/class.js | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.0001722115557640791,
0.00017072816262952983,
0.00016912973660510033,
0.0001706855109659955,
0.000001120197566706338
] |
{
"id": 3,
"code_window": [
" if (args[4] === '') { delete args[4] }\n",
" if (args[5] === '') { delete args[5] }\n",
" }\n",
" const value = args[3] || args[4] || args[5] || ''\n",
" attrs[i] = {\n",
" name: args[1],\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" const shouldDecodeNewlines = tagName === 'a' && args[1] === 'href'\n",
" ? options.shouldDecodeNewlinesForHref\n",
" : options.shouldDecodeNewlines\n"
],
"file_path": "src/compiler/parser/html-parser.js",
"type": "add",
"edit_start_line_idx": 235
} | import {
Component,
AsyncComponent,
ComponentOptions,
FunctionalComponentOptions,
WatchOptionsWithHandler,
WatchHandler,
DirectiveOptions,
DirectiveFunction,
RecordPropsDefinition,
ThisTypedComponentOptionsWithArrayProps,
ThisTypedComponentOptionsWithRecordProps,
WatchOptions,
} from "./options";
import { VNode, VNodeData, VNodeChildren, ScopedSlot } from "./vnode";
import { PluginFunction, PluginObject } from "./plugin";
export interface CreateElement {
(tag?: string | Component<any, any, any, any> | AsyncComponent<any, any, any, any>, children?: VNodeChildren): VNode;
(tag?: string | Component<any, any, any, any> | AsyncComponent<any, any, any, any>, data?: VNodeData, children?: VNodeChildren): VNode;
}
export interface Vue {
readonly $el: HTMLElement;
readonly $options: ComponentOptions<Vue>;
readonly $parent: Vue;
readonly $root: Vue;
readonly $children: Vue[];
readonly $refs: { [key: string]: Vue | Element | Vue[] | Element[] };
readonly $slots: { [key: string]: VNode[] };
readonly $scopedSlots: { [key: string]: ScopedSlot };
readonly $isServer: boolean;
readonly $data: Record<string, any>;
readonly $props: Record<string, any>;
readonly $ssrContext: any;
readonly $vnode: VNode;
readonly $attrs: Record<string, string>;
readonly $listeners: Record<string, Function | Function[]>;
$mount(elementOrSelector?: Element | String, hydrating?: boolean): this;
$forceUpdate(): void;
$destroy(): void;
$set: typeof Vue.set;
$delete: typeof Vue.delete;
$watch(
expOrFn: string,
callback: (this: this, n: any, o: any) => void,
options?: WatchOptions
): (() => void);
$watch<T>(
expOrFn: (this: this) => T,
callback: (this: this, n: T, o: T) => void,
options?: WatchOptions
): (() => void);
$on(event: string | string[], callback: Function): this;
$once(event: string, callback: Function): this;
$off(event?: string | string[], callback?: Function): this;
$emit(event: string, ...args: any[]): this;
$nextTick(callback: (this: this) => void): void;
$nextTick(): Promise<void>;
$createElement: CreateElement;
}
export type CombinedVueInstance<Instance extends Vue, Data, Methods, Computed, Props> = Data & Methods & Computed & Props & Instance;
export type ExtendedVue<Instance extends Vue, Data, Methods, Computed, Props> = VueConstructor<CombinedVueInstance<Instance, Data, Methods, Computed, Props> & Vue>;
export interface VueConstructor<V extends Vue = Vue> {
new <Data = object, Methods = object, Computed = object, PropNames extends string = never>(options?: ThisTypedComponentOptionsWithArrayProps<V, Data, Methods, Computed, PropNames>): CombinedVueInstance<V, Data, Methods, Computed, Record<PropNames, any>>;
// ideally, the return type should just contains Props, not Record<keyof Props, any>. But TS requires Base constructors must all have the same return type.
new <Data = object, Methods = object, Computed = object, Props = object>(options?: ThisTypedComponentOptionsWithRecordProps<V, Data, Methods, Computed, Props>): CombinedVueInstance<V, Data, Methods, Computed, Record<keyof Props, any>>;
new (options?: ComponentOptions<V>): CombinedVueInstance<V, object, object, object, Record<keyof object, any>>;
extend<PropNames extends string = never>(definition: FunctionalComponentOptions<Record<PropNames, any>, PropNames[]>): ExtendedVue<V, {}, {}, {}, Record<PropNames, any>>;
extend<Props>(definition: FunctionalComponentOptions<Props, RecordPropsDefinition<Props>>): ExtendedVue<V, {}, {}, {}, Props>;
extend<Data, Methods, Computed, PropNames extends string>(options?: ThisTypedComponentOptionsWithArrayProps<V, Data, Methods, Computed, PropNames>): ExtendedVue<V, Data, Methods, Computed, Record<PropNames, any>>;
extend<Data, Methods, Computed, Props>(options?: ThisTypedComponentOptionsWithRecordProps<V, Data, Methods, Computed, Props>): ExtendedVue<V, Data, Methods, Computed, Props>;
extend(options?: ComponentOptions<V>): ExtendedVue<V, {}, {}, {}, {}>;
nextTick(callback: () => void, context?: any[]): void;
nextTick(): Promise<void>
set<T>(object: Object, key: string, value: T): T;
set<T>(array: T[], key: number, value: T): T;
delete(object: Object, key: string): void;
delete<T>(array: T[], key: number): void;
directive(
id: string,
definition?: DirectiveOptions | DirectiveFunction
): DirectiveOptions;
filter(id: string, definition?: Function): Function;
component(id: string): VueConstructor;
component<VC extends VueConstructor>(id: string, constructor: VC): VC;
component<Data, Methods, Computed, Props>(id: string, definition: AsyncComponent<Data, Methods, Computed, Props>): ExtendedVue<V, Data, Methods, Computed, Props>;
component<PropNames extends string>(id: string, definition: FunctionalComponentOptions<Record<PropNames, any>, PropNames[]>): ExtendedVue<V, {}, {}, {}, Record<PropNames, any>>;
component<Props>(id: string, definition: FunctionalComponentOptions<Props, RecordPropsDefinition<Props>>): ExtendedVue<V, {}, {}, {}, Props>;
component<Data, Methods, Computed, PropNames extends string>(id: string, definition?: ThisTypedComponentOptionsWithArrayProps<V, Data, Methods, Computed, PropNames>): ExtendedVue<V, Data, Methods, Computed, Record<PropNames, any>>;
component<Data, Methods, Computed, Props>(id: string, definition?: ThisTypedComponentOptionsWithRecordProps<V, Data, Methods, Computed, Props>): ExtendedVue<V, Data, Methods, Computed, Props>;
component(id: string, definition?: ComponentOptions<V>): ExtendedVue<V, {}, {}, {}, {}>;
use<T>(plugin: PluginObject<T> | PluginFunction<T>, options?: T): void;
use(plugin: PluginObject<any> | PluginFunction<any>, ...options: any[]): void;
mixin(mixin: VueConstructor | ComponentOptions<Vue>): void;
compile(template: string): {
render(createElement: typeof Vue.prototype.$createElement): VNode;
staticRenderFns: (() => VNode)[];
};
config: {
silent: boolean;
optionMergeStrategies: any;
devtools: boolean;
productionTip: boolean;
performance: boolean;
errorHandler(err: Error, vm: Vue, info: string): void;
warnHandler(msg: string, vm: Vue, trace: string): void;
ignoredElements: (string | RegExp)[];
keyCodes: { [key: string]: number | number[] };
}
}
export const Vue: VueConstructor;
| types/vue.d.ts | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00017718672461342067,
0.00017085943545680493,
0.00016589161532465369,
0.00017145952733699232,
0.0000032066154744825326
] |
{
"id": 4,
"code_window": [
" attrs[i] = {\n",
" name: args[1],\n",
" value: decodeAttr(\n",
" value,\n",
" options.shouldDecodeNewlines\n",
" )\n",
" }\n",
" }\n",
"\n",
" if (!unary) {\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" value: decodeAttr(value, shouldDecodeNewlines)\n"
],
"file_path": "src/compiler/parser/html-parser.js",
"type": "replace",
"edit_start_line_idx": 237
} | /**
* Not type-checking this file because it's mostly vendor code.
*/
/*!
* HTML Parser By John Resig (ejohn.org)
* Modified by Juriy "kangax" Zaytsev
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*/
import { makeMap, no } from 'shared/util'
import { isNonPhrasingTag } from 'web/compiler/util'
// Regular Expressions for parsing tags and attributes
const attribute = /^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/
// could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName
// but for Vue templates we can enforce a simple charset
const ncname = '[a-zA-Z_][\\w\\-\\.]*'
const qnameCapture = `((?:${ncname}\\:)?${ncname})`
const startTagOpen = new RegExp(`^<${qnameCapture}`)
const startTagClose = /^\s*(\/?)>/
const endTag = new RegExp(`^<\\/${qnameCapture}[^>]*>`)
const doctype = /^<!DOCTYPE [^>]+>/i
const comment = /^<!--/
const conditionalComment = /^<!\[/
let IS_REGEX_CAPTURING_BROKEN = false
'x'.replace(/x(.)?/g, function (m, g) {
IS_REGEX_CAPTURING_BROKEN = g === ''
})
// Special Elements (can contain anything)
export const isPlainTextElement = makeMap('script,style,textarea', true)
const reCache = {}
const decodingMap = {
'<': '<',
'>': '>',
'"': '"',
'&': '&',
' ': '\n'
}
const encodedAttr = /&(?:lt|gt|quot|amp);/g
const encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10);/g
// #5992
const isIgnoreNewlineTag = makeMap('pre,textarea', true)
const shouldIgnoreFirstNewline = (tag, html) => tag && isIgnoreNewlineTag(tag) && html[0] === '\n'
function decodeAttr (value, shouldDecodeNewlines) {
const re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr
return value.replace(re, match => decodingMap[match])
}
export function parseHTML (html, options) {
const stack = []
const expectHTML = options.expectHTML
const isUnaryTag = options.isUnaryTag || no
const canBeLeftOpenTag = options.canBeLeftOpenTag || no
let index = 0
let last, lastTag
while (html) {
last = html
// Make sure we're not in a plaintext content element like script/style
if (!lastTag || !isPlainTextElement(lastTag)) {
let textEnd = html.indexOf('<')
if (textEnd === 0) {
// Comment:
if (comment.test(html)) {
const commentEnd = html.indexOf('-->')
if (commentEnd >= 0) {
if (options.shouldKeepComment) {
options.comment(html.substring(4, commentEnd))
}
advance(commentEnd + 3)
continue
}
}
// http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment
if (conditionalComment.test(html)) {
const conditionalEnd = html.indexOf(']>')
if (conditionalEnd >= 0) {
advance(conditionalEnd + 2)
continue
}
}
// Doctype:
const doctypeMatch = html.match(doctype)
if (doctypeMatch) {
advance(doctypeMatch[0].length)
continue
}
// End tag:
const endTagMatch = html.match(endTag)
if (endTagMatch) {
const curIndex = index
advance(endTagMatch[0].length)
parseEndTag(endTagMatch[1], curIndex, index)
continue
}
// Start tag:
const startTagMatch = parseStartTag()
if (startTagMatch) {
handleStartTag(startTagMatch)
if (shouldIgnoreFirstNewline(lastTag, html)) {
advance(1)
}
continue
}
}
let text, rest, next
if (textEnd >= 0) {
rest = html.slice(textEnd)
while (
!endTag.test(rest) &&
!startTagOpen.test(rest) &&
!comment.test(rest) &&
!conditionalComment.test(rest)
) {
// < in plain text, be forgiving and treat it as text
next = rest.indexOf('<', 1)
if (next < 0) break
textEnd += next
rest = html.slice(textEnd)
}
text = html.substring(0, textEnd)
advance(textEnd)
}
if (textEnd < 0) {
text = html
html = ''
}
if (options.chars && text) {
options.chars(text)
}
} else {
let endTagLength = 0
const stackedTag = lastTag.toLowerCase()
const reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i'))
const rest = html.replace(reStackedTag, function (all, text, endTag) {
endTagLength = endTag.length
if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') {
text = text
.replace(/<!--([\s\S]*?)-->/g, '$1')
.replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1')
}
if (shouldIgnoreFirstNewline(stackedTag, text)) {
text = text.slice(1)
}
if (options.chars) {
options.chars(text)
}
return ''
})
index += html.length - rest.length
html = rest
parseEndTag(stackedTag, index - endTagLength, index)
}
if (html === last) {
options.chars && options.chars(html)
if (process.env.NODE_ENV !== 'production' && !stack.length && options.warn) {
options.warn(`Mal-formatted tag at end of template: "${html}"`)
}
break
}
}
// Clean up any remaining tags
parseEndTag()
function advance (n) {
index += n
html = html.substring(n)
}
function parseStartTag () {
const start = html.match(startTagOpen)
if (start) {
const match = {
tagName: start[1],
attrs: [],
start: index
}
advance(start[0].length)
let end, attr
while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) {
advance(attr[0].length)
match.attrs.push(attr)
}
if (end) {
match.unarySlash = end[1]
advance(end[0].length)
match.end = index
return match
}
}
}
function handleStartTag (match) {
const tagName = match.tagName
const unarySlash = match.unarySlash
if (expectHTML) {
if (lastTag === 'p' && isNonPhrasingTag(tagName)) {
parseEndTag(lastTag)
}
if (canBeLeftOpenTag(tagName) && lastTag === tagName) {
parseEndTag(tagName)
}
}
const unary = isUnaryTag(tagName) || !!unarySlash
const l = match.attrs.length
const attrs = new Array(l)
for (let i = 0; i < l; i++) {
const args = match.attrs[i]
// hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778
if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) {
if (args[3] === '') { delete args[3] }
if (args[4] === '') { delete args[4] }
if (args[5] === '') { delete args[5] }
}
const value = args[3] || args[4] || args[5] || ''
attrs[i] = {
name: args[1],
value: decodeAttr(
value,
options.shouldDecodeNewlines
)
}
}
if (!unary) {
stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs })
lastTag = tagName
}
if (options.start) {
options.start(tagName, attrs, unary, match.start, match.end)
}
}
function parseEndTag (tagName, start, end) {
let pos, lowerCasedTagName
if (start == null) start = index
if (end == null) end = index
if (tagName) {
lowerCasedTagName = tagName.toLowerCase()
}
// Find the closest opened tag of the same type
if (tagName) {
for (pos = stack.length - 1; pos >= 0; pos--) {
if (stack[pos].lowerCasedTag === lowerCasedTagName) {
break
}
}
} else {
// If no tag name is provided, clean shop
pos = 0
}
if (pos >= 0) {
// Close all the open elements, up the stack
for (let i = stack.length - 1; i >= pos; i--) {
if (process.env.NODE_ENV !== 'production' &&
(i > pos || !tagName) &&
options.warn
) {
options.warn(
`tag <${stack[i].tag}> has no matching end tag.`
)
}
if (options.end) {
options.end(stack[i].tag, start, end)
}
}
// Remove the open elements from the stack
stack.length = pos
lastTag = pos && stack[pos - 1].tag
} else if (lowerCasedTagName === 'br') {
if (options.start) {
options.start(tagName, [], true, start, end)
}
} else if (lowerCasedTagName === 'p') {
if (options.start) {
options.start(tagName, [], false, start, end)
}
if (options.end) {
options.end(tagName, start, end)
}
}
}
}
| src/compiler/parser/html-parser.js | 1 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.9970206618309021,
0.03398499637842178,
0.000165477380505763,
0.0001739812141750008,
0.17588748037815094
] |
{
"id": 4,
"code_window": [
" attrs[i] = {\n",
" name: args[1],\n",
" value: decodeAttr(\n",
" value,\n",
" options.shouldDecodeNewlines\n",
" )\n",
" }\n",
" }\n",
"\n",
" if (!unary) {\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" value: decodeAttr(value, shouldDecodeNewlines)\n"
],
"file_path": "src/compiler/parser/html-parser.js",
"type": "replace",
"edit_start_line_idx": 237
} | import Vue from 'vue'
describe('ref', () => {
const components = {
test: {
id: 'test',
template: '<div>test</div>'
},
test2: {
id: 'test2',
template: '<div>test2</div>'
}
}
it('should work', () => {
const vm = new Vue({
data: {
value: 'bar'
},
template: `<div>
<test ref="foo"></test>
<test2 :ref="value"></test2>
</div>`,
components
})
vm.$mount()
expect(vm.$refs.foo).toBeTruthy()
expect(vm.$refs.foo.$options.id).toBe('test')
expect(vm.$refs.bar).toBeTruthy()
expect(vm.$refs.bar.$options.id).toBe('test2')
})
it('should dynamically update refs', done => {
const vm = new Vue({
data: {
value: 'foo'
},
template: '<div :ref="value"></div>'
}).$mount()
expect(vm.$refs.foo).toBe(vm.$el)
vm.value = 'bar'
waitForUpdate(() => {
expect(vm.$refs.foo).toBeUndefined()
expect(vm.$refs.bar).toBe(vm.$el)
}).then(done)
})
it('should work as a hyperscript prop', () => {
const vm = new Vue({
components,
render (h) {
return h('div', null, [
h('test', { ref: 'test' })
])
}
})
vm.$mount()
expect(vm.$refs.test).toBeTruthy()
expect(vm.$refs.test.$options.id).toBe('test')
})
it('should accept HOC component', () => {
const vm = new Vue({
template: '<test ref="test"></test>',
components
})
vm.$mount()
expect(vm.$refs.test).toBeTruthy()
expect(vm.$refs.test.$options.id).toBe('test')
})
it('should accept dynamic component', done => {
const vm = new Vue({
template: `<div>
<component :is="test" ref="test"></component>
</div>`,
components,
data: { test: 'test' }
})
vm.$mount()
expect(vm.$refs.test.$options.id).toBe('test')
vm.test = 'test2'
waitForUpdate(() => {
expect(vm.$refs.test.$options.id).toBe('test2')
vm.test = ''
}).then(() => {
expect(vm.$refs.test).toBeUndefined()
}).then(done)
})
it('should register as Array when used with v-for', done => {
const vm = new Vue({
data: {
items: [1, 2, 3]
},
template: `
<div>
<div v-for="n in items" ref="list">{{n}}</div>
</div>
`
}).$mount()
assertRefs()
// updating
vm.items.push(4)
waitForUpdate(assertRefs)
.then(() => { vm.items = [] })
.then(assertRefs)
.then(done)
function assertRefs () {
expect(Array.isArray(vm.$refs.list)).toBe(true)
expect(vm.$refs.list.length).toBe(vm.items.length)
expect(vm.$refs.list.every((item, i) => item.textContent === String(i + 1))).toBe(true)
}
})
it('should register as Array when used with v-for (components)', done => {
const vm = new Vue({
data: {
items: [1, 2, 3]
},
template: `
<div>
<test v-for="n in items" ref="list" :key="n" :n="n"></test>
</div>
`,
components: {
test: {
props: ['n'],
template: '<div>{{ n }}</div>'
}
}
}).$mount()
assertRefs()
// updating
vm.items.push(4)
waitForUpdate(assertRefs)
.then(() => { vm.items = [] })
.then(assertRefs)
.then(done)
function assertRefs () {
expect(Array.isArray(vm.$refs.list)).toBe(true)
expect(vm.$refs.list.length).toBe(vm.items.length)
expect(vm.$refs.list.every((comp, i) => comp.$el.textContent === String(i + 1))).toBe(true)
}
})
it('should work with v-for on dynamic component', done => {
components.test3 = {
id: 'test3',
template: `<test1 v-if="!normal"></test1><div v-else>test3</div>`,
data () {
return { normal: false }
},
components: { test1: components.test }
}
// a flag that representing whether to test component content or not
let testContent = false
const vm = new Vue({
template: `
<div>
<component
v-for="(item, index) in items"
:key="index"
:is="item"
ref="children">
</component>
</div>
`,
data: {
items: ['test2', 'test3']
},
components
}).$mount()
assertRefs()
expect(vm.$refs.children[0].$el.textContent).toBe('test2')
expect(vm.$refs.children[1].$el.textContent).toBe('test')
// updating
vm.$refs.children[1].normal = true
testContent = true
waitForUpdate(assertRefs)
.then(() => { vm.items.push('test') })
.then(assertRefs)
.then(done)
function assertRefs () {
expect(Array.isArray(vm.$refs.children)).toBe(true)
expect(vm.$refs.children.length).toBe(vm.items.length)
if (testContent) {
expect(
vm.$refs.children.every((comp, i) => comp.$el.textContent === vm.items[i])
).toBe(true)
}
}
})
it('should register on component with empty roots', done => {
const vm = new Vue({
template: '<child ref="test"></child>',
components: {
child: {
template: '<div v-if="show"></div>',
data () {
return { show: false }
}
}
}
}).$mount()
expect(vm.$refs.test).toBe(vm.$children[0])
vm.$refs.test.show = true
waitForUpdate(() => {
expect(vm.$refs.test).toBe(vm.$children[0])
vm.$refs.test.show = false
}).then(() => {
expect(vm.$refs.test).toBe(vm.$children[0])
}).then(done)
})
})
| test/unit/features/ref.spec.js | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00017987734463531524,
0.0001744104374665767,
0.00016687903553247452,
0.00017509509052615613,
0.000002816655978676863
] |
{
"id": 4,
"code_window": [
" attrs[i] = {\n",
" name: args[1],\n",
" value: decodeAttr(\n",
" value,\n",
" options.shouldDecodeNewlines\n",
" )\n",
" }\n",
" }\n",
"\n",
" if (!unary) {\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" value: decodeAttr(value, shouldDecodeNewlines)\n"
],
"file_path": "src/compiler/parser/html-parser.js",
"type": "replace",
"edit_start_line_idx": 237
} | var base = require('./karma.base.config.js')
module.exports = function (config) {
config.set(Object.assign(base, {
browsers: ['PhantomJS'],
reporters: ['progress'],
plugins: base.plugins.concat([
'karma-phantomjs-launcher'
])
}))
}
| test/unit/karma.dev.config.js | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00017650060181040317,
0.00017522001871839166,
0.00017393942107446492,
0.00017522001871839166,
0.0000012805903679691255
] |
{
"id": 4,
"code_window": [
" attrs[i] = {\n",
" name: args[1],\n",
" value: decodeAttr(\n",
" value,\n",
" options.shouldDecodeNewlines\n",
" )\n",
" }\n",
" }\n",
"\n",
" if (!unary) {\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" value: decodeAttr(value, shouldDecodeNewlines)\n"
],
"file_path": "src/compiler/parser/html-parser.js",
"type": "replace",
"edit_start_line_idx": 237
} | /* @flow */
import { namespaceMap } from 'web/util/index'
export function createElement (tagName: string, vnode: VNode): Element {
const elm = document.createElement(tagName)
if (tagName !== 'select') {
return elm
}
// false or null will remove the attribute but undefined will not
if (vnode.data && vnode.data.attrs && vnode.data.attrs.multiple !== undefined) {
elm.setAttribute('multiple', 'multiple')
}
return elm
}
export function createElementNS (namespace: string, tagName: string): Element {
return document.createElementNS(namespaceMap[namespace], tagName)
}
export function createTextNode (text: string): Text {
return document.createTextNode(text)
}
export function createComment (text: string): Comment {
return document.createComment(text)
}
export function insertBefore (parentNode: Node, newNode: Node, referenceNode: Node) {
parentNode.insertBefore(newNode, referenceNode)
}
export function removeChild (node: Node, child: Node) {
node.removeChild(child)
}
export function appendChild (node: Node, child: Node) {
node.appendChild(child)
}
export function parentNode (node: Node): ?Node {
return node.parentNode
}
export function nextSibling (node: Node): ?Node {
return node.nextSibling
}
export function tagName (node: Element): string {
return node.tagName
}
export function setTextContent (node: Node, text: string) {
node.textContent = text
}
export function setAttribute (node: Element, key: string, val: string) {
node.setAttribute(key, val)
}
| src/platforms/web/runtime/node-ops.js | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00017249307711608708,
0.00017052418843377382,
0.00016555329784750938,
0.0001715371327009052,
0.000002421919816697482
] |
{
"id": 5,
"code_window": [
" expectHTML: options.expectHTML,\n",
" isUnaryTag: options.isUnaryTag,\n",
" canBeLeftOpenTag: options.canBeLeftOpenTag,\n",
" shouldDecodeNewlines: options.shouldDecodeNewlines,\n",
" shouldKeepComment: options.comments,\n",
" start (tag, attrs, unary) {\n",
" // check namespace.\n",
" // inherit parent ns if there is one\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" shouldDecodeNewlinesForHref: options.shouldDecodeNewlinesForHref,\n"
],
"file_path": "src/compiler/parser/index.js",
"type": "add",
"edit_start_line_idx": 109
} | /**
* Not type-checking this file because it's mostly vendor code.
*/
/*!
* HTML Parser By John Resig (ejohn.org)
* Modified by Juriy "kangax" Zaytsev
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*/
import { makeMap, no } from 'shared/util'
import { isNonPhrasingTag } from 'web/compiler/util'
// Regular Expressions for parsing tags and attributes
const attribute = /^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/
// could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName
// but for Vue templates we can enforce a simple charset
const ncname = '[a-zA-Z_][\\w\\-\\.]*'
const qnameCapture = `((?:${ncname}\\:)?${ncname})`
const startTagOpen = new RegExp(`^<${qnameCapture}`)
const startTagClose = /^\s*(\/?)>/
const endTag = new RegExp(`^<\\/${qnameCapture}[^>]*>`)
const doctype = /^<!DOCTYPE [^>]+>/i
const comment = /^<!--/
const conditionalComment = /^<!\[/
let IS_REGEX_CAPTURING_BROKEN = false
'x'.replace(/x(.)?/g, function (m, g) {
IS_REGEX_CAPTURING_BROKEN = g === ''
})
// Special Elements (can contain anything)
export const isPlainTextElement = makeMap('script,style,textarea', true)
const reCache = {}
const decodingMap = {
'<': '<',
'>': '>',
'"': '"',
'&': '&',
' ': '\n'
}
const encodedAttr = /&(?:lt|gt|quot|amp);/g
const encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10);/g
// #5992
const isIgnoreNewlineTag = makeMap('pre,textarea', true)
const shouldIgnoreFirstNewline = (tag, html) => tag && isIgnoreNewlineTag(tag) && html[0] === '\n'
function decodeAttr (value, shouldDecodeNewlines) {
const re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr
return value.replace(re, match => decodingMap[match])
}
export function parseHTML (html, options) {
const stack = []
const expectHTML = options.expectHTML
const isUnaryTag = options.isUnaryTag || no
const canBeLeftOpenTag = options.canBeLeftOpenTag || no
let index = 0
let last, lastTag
while (html) {
last = html
// Make sure we're not in a plaintext content element like script/style
if (!lastTag || !isPlainTextElement(lastTag)) {
let textEnd = html.indexOf('<')
if (textEnd === 0) {
// Comment:
if (comment.test(html)) {
const commentEnd = html.indexOf('-->')
if (commentEnd >= 0) {
if (options.shouldKeepComment) {
options.comment(html.substring(4, commentEnd))
}
advance(commentEnd + 3)
continue
}
}
// http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment
if (conditionalComment.test(html)) {
const conditionalEnd = html.indexOf(']>')
if (conditionalEnd >= 0) {
advance(conditionalEnd + 2)
continue
}
}
// Doctype:
const doctypeMatch = html.match(doctype)
if (doctypeMatch) {
advance(doctypeMatch[0].length)
continue
}
// End tag:
const endTagMatch = html.match(endTag)
if (endTagMatch) {
const curIndex = index
advance(endTagMatch[0].length)
parseEndTag(endTagMatch[1], curIndex, index)
continue
}
// Start tag:
const startTagMatch = parseStartTag()
if (startTagMatch) {
handleStartTag(startTagMatch)
if (shouldIgnoreFirstNewline(lastTag, html)) {
advance(1)
}
continue
}
}
let text, rest, next
if (textEnd >= 0) {
rest = html.slice(textEnd)
while (
!endTag.test(rest) &&
!startTagOpen.test(rest) &&
!comment.test(rest) &&
!conditionalComment.test(rest)
) {
// < in plain text, be forgiving and treat it as text
next = rest.indexOf('<', 1)
if (next < 0) break
textEnd += next
rest = html.slice(textEnd)
}
text = html.substring(0, textEnd)
advance(textEnd)
}
if (textEnd < 0) {
text = html
html = ''
}
if (options.chars && text) {
options.chars(text)
}
} else {
let endTagLength = 0
const stackedTag = lastTag.toLowerCase()
const reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i'))
const rest = html.replace(reStackedTag, function (all, text, endTag) {
endTagLength = endTag.length
if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') {
text = text
.replace(/<!--([\s\S]*?)-->/g, '$1')
.replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1')
}
if (shouldIgnoreFirstNewline(stackedTag, text)) {
text = text.slice(1)
}
if (options.chars) {
options.chars(text)
}
return ''
})
index += html.length - rest.length
html = rest
parseEndTag(stackedTag, index - endTagLength, index)
}
if (html === last) {
options.chars && options.chars(html)
if (process.env.NODE_ENV !== 'production' && !stack.length && options.warn) {
options.warn(`Mal-formatted tag at end of template: "${html}"`)
}
break
}
}
// Clean up any remaining tags
parseEndTag()
function advance (n) {
index += n
html = html.substring(n)
}
function parseStartTag () {
const start = html.match(startTagOpen)
if (start) {
const match = {
tagName: start[1],
attrs: [],
start: index
}
advance(start[0].length)
let end, attr
while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) {
advance(attr[0].length)
match.attrs.push(attr)
}
if (end) {
match.unarySlash = end[1]
advance(end[0].length)
match.end = index
return match
}
}
}
function handleStartTag (match) {
const tagName = match.tagName
const unarySlash = match.unarySlash
if (expectHTML) {
if (lastTag === 'p' && isNonPhrasingTag(tagName)) {
parseEndTag(lastTag)
}
if (canBeLeftOpenTag(tagName) && lastTag === tagName) {
parseEndTag(tagName)
}
}
const unary = isUnaryTag(tagName) || !!unarySlash
const l = match.attrs.length
const attrs = new Array(l)
for (let i = 0; i < l; i++) {
const args = match.attrs[i]
// hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778
if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) {
if (args[3] === '') { delete args[3] }
if (args[4] === '') { delete args[4] }
if (args[5] === '') { delete args[5] }
}
const value = args[3] || args[4] || args[5] || ''
attrs[i] = {
name: args[1],
value: decodeAttr(
value,
options.shouldDecodeNewlines
)
}
}
if (!unary) {
stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs })
lastTag = tagName
}
if (options.start) {
options.start(tagName, attrs, unary, match.start, match.end)
}
}
function parseEndTag (tagName, start, end) {
let pos, lowerCasedTagName
if (start == null) start = index
if (end == null) end = index
if (tagName) {
lowerCasedTagName = tagName.toLowerCase()
}
// Find the closest opened tag of the same type
if (tagName) {
for (pos = stack.length - 1; pos >= 0; pos--) {
if (stack[pos].lowerCasedTag === lowerCasedTagName) {
break
}
}
} else {
// If no tag name is provided, clean shop
pos = 0
}
if (pos >= 0) {
// Close all the open elements, up the stack
for (let i = stack.length - 1; i >= pos; i--) {
if (process.env.NODE_ENV !== 'production' &&
(i > pos || !tagName) &&
options.warn
) {
options.warn(
`tag <${stack[i].tag}> has no matching end tag.`
)
}
if (options.end) {
options.end(stack[i].tag, start, end)
}
}
// Remove the open elements from the stack
stack.length = pos
lastTag = pos && stack[pos - 1].tag
} else if (lowerCasedTagName === 'br') {
if (options.start) {
options.start(tagName, [], true, start, end)
}
} else if (lowerCasedTagName === 'p') {
if (options.start) {
options.start(tagName, [], false, start, end)
}
if (options.end) {
options.end(tagName, start, end)
}
}
}
}
| src/compiler/parser/html-parser.js | 1 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.9691503643989563,
0.038067273795604706,
0.0001657164393691346,
0.0006510231178253889,
0.17081806063652039
] |
{
"id": 5,
"code_window": [
" expectHTML: options.expectHTML,\n",
" isUnaryTag: options.isUnaryTag,\n",
" canBeLeftOpenTag: options.canBeLeftOpenTag,\n",
" shouldDecodeNewlines: options.shouldDecodeNewlines,\n",
" shouldKeepComment: options.comments,\n",
" start (tag, attrs, unary) {\n",
" // check namespace.\n",
" // inherit parent ns if there is one\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" shouldDecodeNewlinesForHref: options.shouldDecodeNewlinesForHref,\n"
],
"file_path": "src/compiler/parser/index.js",
"type": "add",
"edit_start_line_idx": 109
} | import Vue from '../../dist/vue.runtime.common.js'
import VM from 'vm'
import { createRenderer } from '../../packages/vue-server-renderer'
const { renderToString } = createRenderer()
describe('SSR: renderToString', () => {
it('static attributes', done => {
renderVmWithOptions({
template: '<div id="foo" bar="123"></div>'
}, result => {
expect(result).toContain('<div id="foo" bar="123" data-server-rendered="true"></div>')
done()
})
})
it('unary tags', done => {
renderVmWithOptions({
template: '<input value="123">'
}, result => {
expect(result).toContain('<input value="123" data-server-rendered="true">')
done()
})
})
it('dynamic attributes', done => {
renderVmWithOptions({
template: '<div qux="quux" :id="foo" :bar="baz"></div>',
data: {
foo: 'hi',
baz: 123
}
}, result => {
expect(result).toContain('<div qux="quux" id="hi" bar="123" data-server-rendered="true"></div>')
done()
})
})
it('static class', done => {
renderVmWithOptions({
template: '<div class="foo bar"></div>'
}, result => {
expect(result).toContain('<div data-server-rendered="true" class="foo bar"></div>')
done()
})
})
it('dynamic class', done => {
renderVmWithOptions({
template: '<div class="foo bar" :class="[a, { qux: hasQux, quux: hasQuux }]"></div>',
data: {
a: 'baz',
hasQux: true,
hasQuux: false
}
}, result => {
expect(result).toContain('<div data-server-rendered="true" class="foo bar baz qux"></div>')
done()
})
})
it('custom component class', done => {
renderVmWithOptions({
template: '<div><cmp class="cmp"></cmp></div>',
components: {
cmp: {
render: h => h('div', 'test')
}
}
}, result => {
expect(result).toContain('<div data-server-rendered="true"><div class="cmp">test</div></div>')
done()
})
})
it('nested component class', done => {
renderVmWithOptions({
template: '<cmp class="outer" :class="cls"></cmp>',
data: { cls: { 'success': 1 }},
components: {
cmp: {
render: h => h('div', [h('nested', { staticClass: 'nested', 'class': { 'error': 1 }})]),
components: {
nested: {
render: h => h('div', { staticClass: 'inner' }, 'test')
}
}
}
}
}, result => {
expect(result).toContain('<div data-server-rendered="true" class="outer success">' +
'<div class="inner nested error">test</div>' +
'</div>')
done()
})
})
it('dynamic style', done => {
renderVmWithOptions({
template: '<div style="background-color:black" :style="{ fontSize: fontSize + \'px\', color: color }"></div>',
data: {
fontSize: 14,
color: 'red'
}
}, result => {
expect(result).toContain(
'<div data-server-rendered="true" style="background-color:black;font-size:14px;color:red;"></div>'
)
done()
})
})
it('dynamic string style', done => {
renderVmWithOptions({
template: '<div :style="style"></div>',
data: {
style: 'color:red'
}
}, result => {
expect(result).toContain(
'<div data-server-rendered="true" style="color:red;"></div>'
)
done()
})
})
it('auto-prefixed style value as array', done => {
renderVmWithOptions({
template: '<div :style="style"></div>',
data: {
style: {
display: ['-webkit-box', '-ms-flexbox', 'flex']
}
}
}, result => {
expect(result).toContain(
'<div data-server-rendered="true" style="display:-webkit-box;display:-ms-flexbox;display:flex;"></div>'
)
done()
})
})
it('custom component style', done => {
renderVmWithOptions({
template: '<section><comp :style="style"></comp></section>',
data: {
style: 'color:red'
},
components: {
comp: {
template: '<div></div>'
}
}
}, result => {
expect(result).toContain(
'<section data-server-rendered="true"><div style="color:red;"></div></section>'
)
done()
})
})
it('nested custom component style', done => {
renderVmWithOptions({
template: '<comp style="color: blue" :style="style"></comp>',
data: {
style: 'color:red'
},
components: {
comp: {
template: '<nested style="text-align: left;" :style="{fontSize:\'520rem\'}"></nested>',
components: {
nested: {
template: '<div></div>'
}
}
}
}
}, result => {
expect(result).toContain(
'<div data-server-rendered="true" style="text-align:left;font-size:520rem;color:red;"></div>'
)
done()
})
})
it('component style not passed to child', done => {
renderVmWithOptions({
template: '<comp :style="style"></comp>',
data: {
style: 'color:red'
},
components: {
comp: {
template: '<div><div></div></div>'
}
}
}, result => {
expect(result).toContain(
'<div data-server-rendered="true" style="color:red;"><div></div></div>'
)
done()
})
})
it('component style not passed to slot', done => {
renderVmWithOptions({
template: '<comp :style="style"><span style="color:black"></span></comp>',
data: {
style: 'color:red'
},
components: {
comp: {
template: '<div><slot></slot></div>'
}
}
}, result => {
expect(result).toContain(
'<div data-server-rendered="true" style="color:red;"><span style="color:black;"></span></div>'
)
done()
})
})
it('attrs merging on components', done => {
const Test = {
render: h => h('div', {
attrs: { id: 'a' }
})
}
renderVmWithOptions({
render: h => h(Test, {
attrs: { id: 'b', name: 'c' }
})
}, res => {
expect(res).toContain(
'<div id="b" data-server-rendered="true" name="c"></div>'
)
done()
})
})
it('domProps merging on components', done => {
const Test = {
render: h => h('div', {
domProps: { innerHTML: 'a' }
})
}
renderVmWithOptions({
render: h => h(Test, {
domProps: { innerHTML: 'b', value: 'c' }
})
}, res => {
expect(res).toContain(
'<div data-server-rendered="true" value="c">b</div>'
)
done()
})
})
it('v-show directive render', done => {
renderVmWithOptions({
template: '<div v-show="false"><span>inner</span></div>'
}, res => {
expect(res).toContain(
'<div data-server-rendered="true" style="display:none;"><span>inner</span></div>'
)
done()
})
})
it('v-show directive not passed to child', done => {
renderVmWithOptions({
template: '<foo v-show="false"></foo>',
components: {
foo: {
template: '<div><span>inner</span></div>'
}
}
}, res => {
expect(res).toContain(
'<div data-server-rendered="true" style="display:none;"><span>inner</span></div>'
)
done()
})
})
it('v-show directive not passed to slot', done => {
renderVmWithOptions({
template: '<foo v-show="false"><span>inner</span></foo>',
components: {
foo: {
template: '<div><slot></slot></div>'
}
}
}, res => {
expect(res).toContain(
'<div data-server-rendered="true" style="display:none;"><span>inner</span></div>'
)
done()
})
})
it('v-show directive merging on components', done => {
renderVmWithOptions({
template: '<foo v-show="false"></foo>',
components: {
foo: {
render: h => h('bar', {
directives: [{
name: 'show',
value: true
}]
}),
components: {
bar: {
render: h => h('div', 'inner')
}
}
}
}
}, res => {
expect(res).toContain(
'<div data-server-rendered="true" style="display:none;">inner</div>'
)
done()
})
})
it('text interpolation', done => {
renderVmWithOptions({
template: '<div>{{ foo }} side {{ bar }}</div>',
data: {
foo: 'server',
bar: '<span>rendering</span>'
}
}, result => {
expect(result).toContain('<div data-server-rendered="true">server side <span>rendering</span></div>')
done()
})
})
it('v-html on root', done => {
renderVmWithOptions({
template: '<div v-html="text"></div>',
data: {
text: '<span>foo</span>'
}
}, result => {
expect(result).toContain('<div data-server-rendered="true"><span>foo</span></div>')
done()
})
})
it('v-text on root', done => {
renderVmWithOptions({
template: '<div v-text="text"></div>',
data: {
text: '<span>foo</span>'
}
}, result => {
expect(result).toContain('<div data-server-rendered="true"><span>foo</span></div>')
done()
})
})
it('v-html', done => {
renderVmWithOptions({
template: '<div><div v-html="text"></div></div>',
data: {
text: '<span>foo</span>'
}
}, result => {
expect(result).toContain('<div data-server-rendered="true"><div><span>foo</span></div></div>')
done()
})
})
it('v-html with null value', done => {
renderVmWithOptions({
template: '<div><div v-html="text"></div></div>',
data: {
text: null
}
}, result => {
expect(result).toContain('<div data-server-rendered="true"><div></div></div>')
done()
})
})
it('v-text', done => {
renderVmWithOptions({
template: '<div><div v-text="text"></div></div>',
data: {
text: '<span>foo</span>'
}
}, result => {
expect(result).toContain('<div data-server-rendered="true"><div><span>foo</span></div></div>')
done()
})
})
it('v-text with null value', done => {
renderVmWithOptions({
template: '<div><div v-text="text"></div></div>',
data: {
text: null
}
}, result => {
expect(result).toContain('<div data-server-rendered="true"><div></div></div>')
done()
})
})
it('child component (hoc)', done => {
renderVmWithOptions({
template: '<child class="foo" :msg="msg"></child>',
data: {
msg: 'hello'
},
components: {
child: {
props: ['msg'],
data () {
return { name: 'bar' }
},
render () {
const h = this.$createElement
return h('div', { class: ['bar'] }, [`${this.msg} ${this.name}`])
}
}
}
}, result => {
expect(result).toContain('<div data-server-rendered="true" class="foo bar">hello bar</div>')
done()
})
})
it('has correct lifecycle during render', done => {
let lifecycleCount = 1
renderVmWithOptions({
template: '<div><span>{{ val }}</span><test></test></div>',
data: {
val: 'hi'
},
beforeCreate () {
expect(lifecycleCount++).toBe(1)
},
created () {
this.val = 'hello'
expect(this.val).toBe('hello')
expect(lifecycleCount++).toBe(2)
},
components: {
test: {
beforeCreate () {
expect(lifecycleCount++).toBe(3)
},
created () {
expect(lifecycleCount++).toBe(4)
},
render () {
expect(lifecycleCount++).toBeGreaterThan(4)
return this.$createElement('span', { class: ['b'] }, 'testAsync')
}
}
}
}, result => {
expect(result).toContain(
'<div data-server-rendered="true">' +
'<span>hello</span>' +
'<span class="b">testAsync</span>' +
'</div>'
)
done()
})
})
it('computed properties', done => {
renderVmWithOptions({
template: '<div>{{ b }}</div>',
data: {
a: {
b: 1
}
},
computed: {
b () {
return this.a.b + 1
}
},
created () {
this.a.b = 2
expect(this.b).toBe(3)
}
}, result => {
expect(result).toContain('<div data-server-rendered="true">3</div>')
done()
})
})
it('renders async component', done => {
renderVmWithOptions({
template: `
<div>
<test-async></test-async>
</div>
`,
components: {
testAsync (resolve) {
setTimeout(() => resolve({
render () {
return this.$createElement('span', { class: ['b'] }, 'testAsync')
}
}), 1)
}
}
}, result => {
expect(result).toContain('<div data-server-rendered="true"><span class="b">testAsync</span></div>')
done()
})
})
it('renders async component (Promise, nested)', done => {
const Foo = () => Promise.resolve({
render: h => h('div', [h('span', 'foo'), h(Bar)])
})
const Bar = () => ({
component: Promise.resolve({
render: h => h('span', 'bar')
})
})
renderVmWithOptions({
render: h => h(Foo)
}, res => {
expect(res).toContain(`<div data-server-rendered="true"><span>foo</span><span>bar</span></div>`)
done()
})
})
it('renders async component (ES module)', done => {
const Foo = () => Promise.resolve({
__esModule: true,
default: {
render: h => h('div', [h('span', 'foo'), h(Bar)])
}
})
const Bar = () => ({
component: Promise.resolve({
__esModule: true,
default: {
render: h => h('span', 'bar')
}
})
})
renderVmWithOptions({
render: h => h(Foo)
}, res => {
expect(res).toContain(`<div data-server-rendered="true"><span>foo</span><span>bar</span></div>`)
done()
})
})
it('renders async component (hoc)', done => {
renderVmWithOptions({
template: '<test-async></test-async>',
components: {
testAsync: () => Promise.resolve({
render () {
return this.$createElement('span', { class: ['b'] }, 'testAsync')
}
})
}
}, result => {
expect(result).toContain('<span data-server-rendered="true" class="b">testAsync</span>')
done()
})
})
it('everything together', done => {
renderVmWithOptions({
template: `
<div>
<p class="hi">yoyo</p>
<div id="ho" :class="{ red: isRed }"></div>
<span>{{ test }}</span>
<input :value="test">
<img :src="imageUrl">
<test></test>
<test-async></test-async>
</div>
`,
data: {
test: 'hi',
isRed: true,
imageUrl: 'https://vuejs.org/images/logo.png'
},
components: {
test: {
render () {
return this.$createElement('div', { class: ['a'] }, 'test')
}
},
testAsync (resolve) {
resolve({
render () {
return this.$createElement('span', { class: ['b'] }, 'testAsync')
}
})
}
}
}, result => {
expect(result).toContain(
'<div data-server-rendered="true">' +
'<p class="hi">yoyo</p> ' +
'<div id="ho" class="red"></div> ' +
'<span>hi</span> ' +
'<input value="hi"> ' +
'<img src="https://vuejs.org/images/logo.png"> ' +
'<div class="a">test</div> ' +
'<span class="b">testAsync</span>' +
'</div>'
)
done()
})
})
it('normal attr', done => {
renderVmWithOptions({
template: `
<div>
<span :test="'ok'">hello</span>
<span :test="null">hello</span>
<span :test="false">hello</span>
<span :test="true">hello</span>
<span :test="0">hello</span>
</div>
`
}, result => {
expect(result).toContain(
'<div data-server-rendered="true">' +
'<span test="ok">hello</span> ' +
'<span>hello</span> ' +
'<span>hello</span> ' +
'<span test="true">hello</span> ' +
'<span test="0">hello</span>' +
'</div>'
)
done()
})
})
it('enumerated attr', done => {
renderVmWithOptions({
template: `
<div>
<span :draggable="true">hello</span>
<span :draggable="'ok'">hello</span>
<span :draggable="null">hello</span>
<span :draggable="false">hello</span>
<span :draggable="''">hello</span>
<span :draggable="'false'">hello</span>
</div>
`
}, result => {
expect(result).toContain(
'<div data-server-rendered="true">' +
'<span draggable="true">hello</span> ' +
'<span draggable="true">hello</span> ' +
'<span draggable="false">hello</span> ' +
'<span draggable="false">hello</span> ' +
'<span draggable="true">hello</span> ' +
'<span draggable="false">hello</span>' +
'</div>'
)
done()
})
})
it('boolean attr', done => {
renderVmWithOptions({
template: `
<div>
<span :disabled="true">hello</span>
<span :disabled="'ok'">hello</span>
<span :disabled="null">hello</span>
<span :disabled="''">hello</span>
</div>
`
}, result => {
expect(result).toContain(
'<div data-server-rendered="true">' +
'<span disabled="disabled">hello</span> ' +
'<span disabled="disabled">hello</span> ' +
'<span>hello</span> ' +
'<span disabled="disabled">hello</span>' +
'</div>'
)
done()
})
})
it('v-bind object', done => {
renderVmWithOptions({
data: {
test: { id: 'a', class: ['a', 'b'], value: 'c' }
},
template: '<input v-bind="test">'
}, result => {
expect(result).toContain('<input id="a" data-server-rendered="true" value="c" class="a b">')
done()
})
})
it('custom directives', done => {
const renderer = createRenderer({
directives: {
'class-prefixer': (node, dir) => {
if (node.data.class) {
node.data.class = `${dir.value}-${node.data.class}`
}
if (node.data.staticClass) {
node.data.staticClass = `${dir.value}-${node.data.staticClass}`
}
}
}
})
renderer.renderToString(new Vue({
render () {
const h = this.$createElement
return h('p', {
class: 'class1',
staticClass: 'class2',
directives: [{
name: 'class-prefixer',
value: 'my'
}]
}, ['hello world'])
}
}), (err, result) => {
expect(err).toBeNull()
expect(result).toContain('<p data-server-rendered="true" class="my-class2 my-class1">hello world</p>')
done()
})
})
it('_scopeId', done => {
renderVmWithOptions({
_scopeId: '_v-parent',
template: '<div id="foo"><p><child></child></p></div>',
components: {
child: {
_scopeId: '_v-child',
render () {
const h = this.$createElement
return h('div', null, [h('span', null, ['foo'])])
}
}
}
}, result => {
expect(result).toContain(
'<div id="foo" data-server-rendered="true" _v-parent>' +
'<p _v-parent>' +
'<div _v-child _v-parent><span _v-child>foo</span></div>' +
'</p>' +
'</div>'
)
done()
})
})
it('_scopeId on slot content', done => {
renderVmWithOptions({
_scopeId: '_v-parent',
template: '<div><child><p>foo</p></child></div>',
components: {
child: {
_scopeId: '_v-child',
render () {
const h = this.$createElement
return h('div', null, this.$slots.default)
}
}
}
}, result => {
expect(result).toContain(
'<div data-server-rendered="true" _v-parent>' +
'<div _v-child _v-parent><p _v-child _v-parent>foo</p></div>' +
'</div>'
)
done()
})
})
it('comment nodes', done => {
renderVmWithOptions({
template: '<div><transition><div v-if="false"></div></transition></div>'
}, result => {
expect(result).toContain(`<div data-server-rendered="true"><!----></div>`)
done()
})
})
it('should catch error', done => {
Vue.config.silent = true
renderToString(new Vue({
render () {
throw new Error('oops')
}
}), err => {
expect(err instanceof Error).toBe(true)
Vue.config.silent = false
done()
})
})
it('default value Foreign Function', () => {
const FunctionConstructor = VM.runInNewContext('Function')
const func = () => 123
const vm = new Vue({
props: {
a: {
type: FunctionConstructor,
default: func
}
},
propsData: {
a: undefined
}
})
expect(vm.a).toBe(func)
})
it('should prevent xss in attributes', done => {
renderVmWithOptions({
data: {
xss: '"><script>alert(1)</script>'
},
template: `
<div>
<a :title="xss" :style="{ color: xss }" :class="[xss]">foo</a>
</div>
`
}, res => {
expect(res).not.toContain(`<script>alert(1)</script>`)
done()
})
})
it('should prevent script xss with v-bind object syntax + array value', done => {
renderVmWithOptions({
data: {
test: ['"><script>alert(1)</script><!--"']
},
template: `<div v-bind="{ test }"></div>`
}, res => {
expect(res).not.toContain(`<script>alert(1)</script>`)
done()
})
})
it('v-if', done => {
renderVmWithOptions({
template: `
<div>
<span v-if="true">foo</span>
<span v-if="false">bar</span>
</div>
`
}, res => {
expect(res).toContain(`<div data-server-rendered="true"><span>foo</span> <!----></div>`)
done()
})
})
it('v-for', done => {
renderVmWithOptions({
template: `
<div>
<span>foo</span>
<span v-for="i in 2">{{ i }}</span>
</div>
`
}, res => {
expect(res).toContain(`<div data-server-rendered="true"><span>foo</span> <span>1</span><span>2</span></div>`)
done()
})
})
it('template v-if', done => {
renderVmWithOptions({
template: `
<div>
<span>foo</span>
<template v-if="true">
<span>foo</span> bar <span>baz</span>
</template>
</div>
`
}, res => {
expect(res).toContain(`<div data-server-rendered="true"><span>foo</span> <span>foo</span> bar <span>baz</span></div>`)
done()
})
})
it('template v-for', done => {
renderVmWithOptions({
template: `
<div>
<span>foo</span>
<template v-for="i in 2">
<span>{{ i }}</span><span>bar</span>
</template>
</div>
`
}, res => {
expect(res).toContain(`<div data-server-rendered="true"><span>foo</span> <span>1</span><span>bar</span><span>2</span><span>bar</span></div>`)
done()
})
})
it('with inheritAttrs: false + $attrs', done => {
renderVmWithOptions({
template: `<foo id="a"/>`,
components: {
foo: {
inheritAttrs: false,
template: `<div><div v-bind="$attrs"></div></div>`
}
}
}, res => {
expect(res).toBe(`<div data-server-rendered="true"><div id="a"></div></div>`)
done()
})
})
it('should escape static strings', done => {
renderVmWithOptions({
template: `<div><foo></div>`
}, res => {
expect(res).toBe(`<div data-server-rendered="true"><foo></div>`)
done()
})
})
it('should not cache computed properties', done => {
renderVmWithOptions({
template: `<div>{{ foo }}</div>`,
data: () => ({ bar: 1 }),
computed: {
foo () { return this.bar + 1 }
},
created () {
this.foo // access
this.bar++ // trigger change
}
}, res => {
expect(res).toBe(`<div data-server-rendered="true">3</div>`)
done()
})
})
it('return Promise', done => {
renderToString(new Vue({
template: `<div>{{ foo }}</div>`,
data: { foo: 'bar' }
})).then(res => {
expect(res).toBe(`<div data-server-rendered="true">bar</div>`)
done()
})
})
it('return Promise (error)', done => {
Vue.config.silent = true
renderToString(new Vue({
render () {
throw new Error('foobar')
}
})).catch(err => {
expect(err.toString()).toContain(`foobar`)
Vue.config.silent = false
done()
})
})
it('should catch template compilation error', done => {
renderToString(new Vue({
template: `<div></div><div></div>`
}), (err, res) => {
expect(err.toString()).toContain('Component template should contain exactly one root element')
done()
})
})
})
function renderVmWithOptions (options, cb) {
renderToString(new Vue(options), (err, res) => {
expect(err).toBeNull()
cb(res)
})
}
| test/ssr/ssr-string.spec.js | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.0005020952085033059,
0.00017660288722254336,
0.0001668184413574636,
0.00017333519645035267,
0.000032860309147508815
] |
{
"id": 5,
"code_window": [
" expectHTML: options.expectHTML,\n",
" isUnaryTag: options.isUnaryTag,\n",
" canBeLeftOpenTag: options.canBeLeftOpenTag,\n",
" shouldDecodeNewlines: options.shouldDecodeNewlines,\n",
" shouldKeepComment: options.comments,\n",
" start (tag, attrs, unary) {\n",
" // check namespace.\n",
" // inherit parent ns if there is one\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" shouldDecodeNewlinesForHref: options.shouldDecodeNewlinesForHref,\n"
],
"file_path": "src/compiler/parser/index.js",
"type": "add",
"edit_start_line_idx": 109
} | import Vue from 'vue'
function checkPrefixedProp (prop) {
var el = document.createElement('div')
var upper = prop.charAt(0).toUpperCase() + prop.slice(1)
if (!(prop in el.style)) {
var prefixes = ['Webkit', 'Moz', 'ms']
var i = prefixes.length
while (i--) {
if ((prefixes[i] + upper) in el.style) {
prop = prefixes[i] + upper
}
}
}
return prop
}
describe('Directive v-bind:style', () => {
let vm
beforeEach(() => {
vm = new Vue({
template: '<div :style="styles"></div>',
data () {
return {
styles: {},
fontSize: 16
}
}
}).$mount()
})
it('string', done => {
vm.styles = 'color:red;'
waitForUpdate(() => {
expect(vm.$el.style.cssText.replace(/\s/g, '')).toBe('color:red;')
}).then(done)
})
it('falsy number', done => {
vm.styles = { opacity: 0 }
waitForUpdate(() => {
expect(vm.$el.style.opacity).toBe('0')
}).then(done)
})
it('plain object', done => {
vm.styles = { color: 'red' }
waitForUpdate(() => {
expect(vm.$el.style.cssText.replace(/\s/g, '')).toBe('color:red;')
}).then(done)
})
it('camelCase', done => {
vm.styles = { marginRight: '10px' }
waitForUpdate(() => {
expect(vm.$el.style.marginRight).toBe('10px')
}).then(done)
})
it('remove if falsy value', done => {
vm.$el.style.color = 'red'
waitForUpdate(() => {
vm.styles = { color: null }
}).then(() => {
expect(vm.$el.style.color).toBe('')
}).then(done)
})
it('ignore unsupported property', done => {
vm.styles = { foo: 'bar' }
waitForUpdate(() => {
expect(vm.$el.style.foo).not.toBe('bar')
}).then(done)
})
it('auto prefix', done => {
const prop = checkPrefixedProp('transform')
const val = 'scale(0.5)'
vm.styles = { transform: val }
waitForUpdate(() => {
expect(vm.$el.style[prop]).toBe(val)
}).then(done)
})
it('auto-prefixed style value as array', done => {
vm.styles = { display: ['-webkit-box', '-ms-flexbox', 'flex'] }
const testEl = document.createElement('div')
vm.styles.display.forEach(value => {
testEl.style.display = value
})
waitForUpdate(() => {
expect(vm.$el.style.display).toBe(testEl.style.display)
}).then(done)
})
it('!important', done => {
vm.styles = { display: 'block !important' }
waitForUpdate(() => {
expect(vm.$el.style.getPropertyPriority('display')).toBe('important')
}).then(done)
})
it('object with multiple entries', done => {
vm.$el.style.color = 'red'
vm.styles = {
marginLeft: '10px',
marginRight: '15px'
}
waitForUpdate(() => {
expect(vm.$el.style.getPropertyValue('color')).toBe('red')
expect(vm.$el.style.getPropertyValue('margin-left')).toBe('10px')
expect(vm.$el.style.getPropertyValue('margin-right')).toBe('15px')
vm.styles = {
color: 'blue',
padding: null
}
}).then(() => {
expect(vm.$el.style.getPropertyValue('color')).toBe('blue')
expect(vm.$el.style.getPropertyValue('padding')).toBeFalsy()
expect(vm.$el.style.getPropertyValue('margin-left')).toBeFalsy()
expect(vm.$el.style.getPropertyValue('margin-right')).toBeFalsy()
// handle falsy value
vm.styles = null
}).then(() => {
expect(vm.$el.style.getPropertyValue('color')).toBeFalsy()
expect(vm.$el.style.getPropertyValue('padding')).toBeFalsy()
expect(vm.$el.style.getPropertyValue('margin-left')).toBeFalsy()
expect(vm.$el.style.getPropertyValue('margin-right')).toBeFalsy()
}).then(done)
})
it('array of objects', done => {
vm.$el.style.padding = '10px'
vm.styles = [{ color: 'red' }, { marginRight: '20px' }]
waitForUpdate(() => {
expect(vm.$el.style.getPropertyValue('color')).toBe('red')
expect(vm.$el.style.getPropertyValue('margin-right')).toBe('20px')
expect(vm.$el.style.getPropertyValue('padding')).toBe('10px')
vm.styles = [{ color: 'blue' }, { padding: null }]
}).then(() => {
expect(vm.$el.style.getPropertyValue('color')).toBe('blue')
expect(vm.$el.style.getPropertyValue('margin-right')).toBeFalsy()
expect(vm.$el.style.getPropertyValue('padding')).toBeFalsy()
}).then(done)
})
it('updates objects deeply', done => {
vm.styles = { display: 'none' }
waitForUpdate(() => {
expect(vm.$el.style.display).toBe('none')
vm.styles.display = 'block'
}).then(() => {
expect(vm.$el.style.display).toBe('block')
}).then(done)
})
it('background size with only one value', done => {
vm.styles = { backgroundSize: '100%' }
waitForUpdate(() => {
expect(vm.$el.style.cssText.replace(/\s/g, '')).toMatch(/background-size:100%(auto)?;/)
}).then(done)
})
it('should work with interpolation', done => {
vm.styles = { fontSize: `${vm.fontSize}px` }
waitForUpdate(() => {
expect(vm.$el.style.fontSize).toBe('16px')
}).then(done)
})
const supportCssVariable = () => {
const el = document.createElement('div')
el.style.setProperty('--color', 'red')
return el.style.getPropertyValue('--color') === 'red'
}
if (supportCssVariable()) {
it('CSS variables', done => {
vm.styles = { '--color': 'red' }
waitForUpdate(() => {
expect(vm.$el.style.getPropertyValue('--color')).toBe('red')
}).then(done)
})
}
it('should merge static style with binding style', () => {
const vm = new Vue({
template: '<div style="background: url(https://vuejs.org/images/logo.png);color: blue" :style="test"></div>',
data: {
test: { color: 'red', fontSize: '12px' }
}
}).$mount()
const style = vm.$el.style
expect(style.getPropertyValue('background-image')).toMatch('https://vuejs.org/images/logo.png')
expect(style.getPropertyValue('color')).toBe('red')
expect(style.getPropertyValue('font-size')).toBe('12px')
})
it('should merge between parent and child', done => {
const vm = new Vue({
template: '<child style="text-align: left;margin-right:20px" :style="test"></child>',
data: {
test: { color: 'red', fontSize: '12px' }
},
components: {
child: {
template: '<div style="margin-right:10px;" :style="{marginLeft: marginLeft}"></div>',
data: () => ({ marginLeft: '16px' })
}
}
}).$mount()
const style = vm.$el.style
const child = vm.$children[0]
const css = style.cssText.replace(/\s/g, '')
expect(css).toContain('margin-right:20px;')
expect(css).toContain('margin-left:16px;')
expect(css).toContain('text-align:left;')
expect(css).toContain('color:red;')
expect(css).toContain('font-size:12px;')
expect(style.color).toBe('red')
expect(style.marginRight).toBe('20px')
vm.test.color = 'blue'
waitForUpdate(() => {
expect(style.color).toBe('blue')
child.marginLeft = '30px'
}).then(() => {
expect(style.marginLeft).toBe('30px')
child.fontSize = '30px'
}).then(() => {
expect(style.fontSize).toBe('12px')
}).then(done)
})
it('should not pass to child root element', () => {
const vm = new Vue({
template: '<child :style="test"></child>',
data: {
test: { color: 'red', fontSize: '12px' }
},
components: {
child: {
template: '<div><nested ref="nested" style="color: blue;text-align:left"></nested></div>',
components: {
nested: {
template: '<div></div>'
}
}
}
}
}).$mount()
const style = vm.$el.style
expect(style.color).toBe('red')
expect(style.textAlign).toBe('')
expect(style.fontSize).toBe('12px')
expect(vm.$children[0].$refs.nested.$el.style.color).toBe('blue')
})
it('should merge between nested components', (done) => {
const vm = new Vue({
template: '<child :style="test"></child>',
data: {
test: { color: 'red', fontSize: '12px' }
},
components: {
child: {
template: '<nested style="color: blue;text-align:left"></nested>',
components: {
nested: {
template: '<div style="margin-left: 12px;" :style="nestedStyle"></div>',
data: () => ({ nestedStyle: { marginLeft: '30px' }})
}
}
}
}
}).$mount()
const style = vm.$el.style
const child = vm.$children[0].$children[0]
expect(style.color).toBe('red')
expect(style.marginLeft).toBe('30px')
expect(style.textAlign).toBe('left')
expect(style.fontSize).toBe('12px')
vm.test.color = 'yellow'
waitForUpdate(() => {
child.nestedStyle.marginLeft = '60px'
}).then(() => {
expect(style.marginLeft).toBe('60px')
child.nestedStyle = {
fontSize: '14px',
marginLeft: '40px'
}
}).then(() => {
expect(style.fontSize).toBe('12px')
expect(style.marginLeft).toBe('40px')
}).then(done)
})
it('should not merge for different adjacent elements', (done) => {
const vm = new Vue({
template:
'<div>' +
'<section style="color: blue" :style="style" v-if="!bool"></section>' +
'<div></div>' +
'<section style="margin-top: 12px" v-if="bool"></section>' +
'</div>',
data: {
bool: false,
style: {
fontSize: '12px'
}
}
}).$mount()
const style = vm.$el.children[0].style
expect(style.fontSize).toBe('12px')
expect(style.color).toBe('blue')
waitForUpdate(() => {
vm.bool = true
}).then(() => {
expect(style.color).toBe('')
expect(style.fontSize).toBe('')
expect(style.marginTop).toBe('12px')
}).then(done)
})
it('should not merge for v-if, v-else-if and v-else elements', (done) => {
const vm = new Vue({
template:
'<div>' +
'<section style="color: blue" :style="style" v-if="foo"></section>' +
'<section style="margin-top: 12px" v-else-if="bar"></section>' +
'<section style="margin-bottom: 24px" v-else></section>' +
'<div></div>' +
'</div>',
data: {
foo: true,
bar: false,
style: {
fontSize: '12px'
}
}
}).$mount()
const style = vm.$el.children[0].style
expect(style.fontSize).toBe('12px')
expect(style.color).toBe('blue')
waitForUpdate(() => {
vm.foo = false
}).then(() => {
expect(style.color).toBe('')
expect(style.fontSize).toBe('')
expect(style.marginBottom).toBe('24px')
vm.bar = true
}).then(() => {
expect(style.color).toBe('')
expect(style.fontSize).toBe('')
expect(style.marginBottom).toBe('')
expect(style.marginTop).toBe('12px')
}).then(done)
})
// #5318
it('should work for elements passed down as a slot', done => {
const vm = new Vue({
template: `<test><div :style="style"/></test>`,
data: {
style: { color: 'red' }
},
components: {
test: {
template: `<div><slot/></div>`
}
}
}).$mount()
expect(vm.$el.children[0].style.color).toBe('red')
vm.style.color = 'green'
waitForUpdate(() => {
expect(vm.$el.children[0].style.color).toBe('green')
}).then(done)
})
})
| test/unit/features/directives/style.spec.js | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00017802719958126545,
0.00017506179574411362,
0.00016771430091466755,
0.0001755466073518619,
0.000002282835794176208
] |
{
"id": 5,
"code_window": [
" expectHTML: options.expectHTML,\n",
" isUnaryTag: options.isUnaryTag,\n",
" canBeLeftOpenTag: options.canBeLeftOpenTag,\n",
" shouldDecodeNewlines: options.shouldDecodeNewlines,\n",
" shouldKeepComment: options.comments,\n",
" start (tag, attrs, unary) {\n",
" // check namespace.\n",
" // inherit parent ns if there is one\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" shouldDecodeNewlinesForHref: options.shouldDecodeNewlinesForHref,\n"
],
"file_path": "src/compiler/parser/index.js",
"type": "add",
"edit_start_line_idx": 109
} | try {
var vueVersion = require('vue').version
} catch (e) {}
var packageName = require('./package.json').name
var packageVersion = require('./package.json').version
if (vueVersion && vueVersion !== packageVersion) {
throw new Error(
'\n\nVue packages version mismatch:\n\n' +
'- vue@' + vueVersion + '\n' +
'- ' + packageName + '@' + packageVersion + '\n\n' +
'This may cause things to work incorrectly. Make sure to use the same version for both.\n'
)
}
module.exports = require('./build')
| packages/vue-server-renderer/index.js | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00017438246868550777,
0.00017369762645103037,
0.00017301278421655297,
0.00017369762645103037,
6.848422344774008e-7
] |
{
"id": 6,
"code_window": [
"import { mark, measure } from 'core/util/perf'\n",
"\n",
"import Vue from './runtime/index'\n",
"import { query } from './util/index'\n",
"import { shouldDecodeNewlines } from './util/compat'\n",
"import { compileToFunctions } from './compiler/index'\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "src/platforms/web/entry-runtime-with-compiler.js",
"type": "replace",
"edit_start_line_idx": 8
} | /**
* Not type-checking this file because it's mostly vendor code.
*/
/*!
* HTML Parser By John Resig (ejohn.org)
* Modified by Juriy "kangax" Zaytsev
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*/
import { makeMap, no } from 'shared/util'
import { isNonPhrasingTag } from 'web/compiler/util'
// Regular Expressions for parsing tags and attributes
const attribute = /^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/
// could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName
// but for Vue templates we can enforce a simple charset
const ncname = '[a-zA-Z_][\\w\\-\\.]*'
const qnameCapture = `((?:${ncname}\\:)?${ncname})`
const startTagOpen = new RegExp(`^<${qnameCapture}`)
const startTagClose = /^\s*(\/?)>/
const endTag = new RegExp(`^<\\/${qnameCapture}[^>]*>`)
const doctype = /^<!DOCTYPE [^>]+>/i
const comment = /^<!--/
const conditionalComment = /^<!\[/
let IS_REGEX_CAPTURING_BROKEN = false
'x'.replace(/x(.)?/g, function (m, g) {
IS_REGEX_CAPTURING_BROKEN = g === ''
})
// Special Elements (can contain anything)
export const isPlainTextElement = makeMap('script,style,textarea', true)
const reCache = {}
const decodingMap = {
'<': '<',
'>': '>',
'"': '"',
'&': '&',
' ': '\n'
}
const encodedAttr = /&(?:lt|gt|quot|amp);/g
const encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10);/g
// #5992
const isIgnoreNewlineTag = makeMap('pre,textarea', true)
const shouldIgnoreFirstNewline = (tag, html) => tag && isIgnoreNewlineTag(tag) && html[0] === '\n'
function decodeAttr (value, shouldDecodeNewlines) {
const re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr
return value.replace(re, match => decodingMap[match])
}
export function parseHTML (html, options) {
const stack = []
const expectHTML = options.expectHTML
const isUnaryTag = options.isUnaryTag || no
const canBeLeftOpenTag = options.canBeLeftOpenTag || no
let index = 0
let last, lastTag
while (html) {
last = html
// Make sure we're not in a plaintext content element like script/style
if (!lastTag || !isPlainTextElement(lastTag)) {
let textEnd = html.indexOf('<')
if (textEnd === 0) {
// Comment:
if (comment.test(html)) {
const commentEnd = html.indexOf('-->')
if (commentEnd >= 0) {
if (options.shouldKeepComment) {
options.comment(html.substring(4, commentEnd))
}
advance(commentEnd + 3)
continue
}
}
// http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment
if (conditionalComment.test(html)) {
const conditionalEnd = html.indexOf(']>')
if (conditionalEnd >= 0) {
advance(conditionalEnd + 2)
continue
}
}
// Doctype:
const doctypeMatch = html.match(doctype)
if (doctypeMatch) {
advance(doctypeMatch[0].length)
continue
}
// End tag:
const endTagMatch = html.match(endTag)
if (endTagMatch) {
const curIndex = index
advance(endTagMatch[0].length)
parseEndTag(endTagMatch[1], curIndex, index)
continue
}
// Start tag:
const startTagMatch = parseStartTag()
if (startTagMatch) {
handleStartTag(startTagMatch)
if (shouldIgnoreFirstNewline(lastTag, html)) {
advance(1)
}
continue
}
}
let text, rest, next
if (textEnd >= 0) {
rest = html.slice(textEnd)
while (
!endTag.test(rest) &&
!startTagOpen.test(rest) &&
!comment.test(rest) &&
!conditionalComment.test(rest)
) {
// < in plain text, be forgiving and treat it as text
next = rest.indexOf('<', 1)
if (next < 0) break
textEnd += next
rest = html.slice(textEnd)
}
text = html.substring(0, textEnd)
advance(textEnd)
}
if (textEnd < 0) {
text = html
html = ''
}
if (options.chars && text) {
options.chars(text)
}
} else {
let endTagLength = 0
const stackedTag = lastTag.toLowerCase()
const reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i'))
const rest = html.replace(reStackedTag, function (all, text, endTag) {
endTagLength = endTag.length
if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') {
text = text
.replace(/<!--([\s\S]*?)-->/g, '$1')
.replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1')
}
if (shouldIgnoreFirstNewline(stackedTag, text)) {
text = text.slice(1)
}
if (options.chars) {
options.chars(text)
}
return ''
})
index += html.length - rest.length
html = rest
parseEndTag(stackedTag, index - endTagLength, index)
}
if (html === last) {
options.chars && options.chars(html)
if (process.env.NODE_ENV !== 'production' && !stack.length && options.warn) {
options.warn(`Mal-formatted tag at end of template: "${html}"`)
}
break
}
}
// Clean up any remaining tags
parseEndTag()
function advance (n) {
index += n
html = html.substring(n)
}
function parseStartTag () {
const start = html.match(startTagOpen)
if (start) {
const match = {
tagName: start[1],
attrs: [],
start: index
}
advance(start[0].length)
let end, attr
while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) {
advance(attr[0].length)
match.attrs.push(attr)
}
if (end) {
match.unarySlash = end[1]
advance(end[0].length)
match.end = index
return match
}
}
}
function handleStartTag (match) {
const tagName = match.tagName
const unarySlash = match.unarySlash
if (expectHTML) {
if (lastTag === 'p' && isNonPhrasingTag(tagName)) {
parseEndTag(lastTag)
}
if (canBeLeftOpenTag(tagName) && lastTag === tagName) {
parseEndTag(tagName)
}
}
const unary = isUnaryTag(tagName) || !!unarySlash
const l = match.attrs.length
const attrs = new Array(l)
for (let i = 0; i < l; i++) {
const args = match.attrs[i]
// hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778
if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) {
if (args[3] === '') { delete args[3] }
if (args[4] === '') { delete args[4] }
if (args[5] === '') { delete args[5] }
}
const value = args[3] || args[4] || args[5] || ''
attrs[i] = {
name: args[1],
value: decodeAttr(
value,
options.shouldDecodeNewlines
)
}
}
if (!unary) {
stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs })
lastTag = tagName
}
if (options.start) {
options.start(tagName, attrs, unary, match.start, match.end)
}
}
function parseEndTag (tagName, start, end) {
let pos, lowerCasedTagName
if (start == null) start = index
if (end == null) end = index
if (tagName) {
lowerCasedTagName = tagName.toLowerCase()
}
// Find the closest opened tag of the same type
if (tagName) {
for (pos = stack.length - 1; pos >= 0; pos--) {
if (stack[pos].lowerCasedTag === lowerCasedTagName) {
break
}
}
} else {
// If no tag name is provided, clean shop
pos = 0
}
if (pos >= 0) {
// Close all the open elements, up the stack
for (let i = stack.length - 1; i >= pos; i--) {
if (process.env.NODE_ENV !== 'production' &&
(i > pos || !tagName) &&
options.warn
) {
options.warn(
`tag <${stack[i].tag}> has no matching end tag.`
)
}
if (options.end) {
options.end(stack[i].tag, start, end)
}
}
// Remove the open elements from the stack
stack.length = pos
lastTag = pos && stack[pos - 1].tag
} else if (lowerCasedTagName === 'br') {
if (options.start) {
options.start(tagName, [], true, start, end)
}
} else if (lowerCasedTagName === 'p') {
if (options.start) {
options.start(tagName, [], false, start, end)
}
if (options.end) {
options.end(tagName, start, end)
}
}
}
}
| src/compiler/parser/html-parser.js | 1 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.008654627948999405,
0.00045147715718485415,
0.0001651532802497968,
0.00017105256847571582,
0.001497906749136746
] |
{
"id": 6,
"code_window": [
"import { mark, measure } from 'core/util/perf'\n",
"\n",
"import Vue from './runtime/index'\n",
"import { query } from './util/index'\n",
"import { shouldDecodeNewlines } from './util/compat'\n",
"import { compileToFunctions } from './compiler/index'\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "src/platforms/web/entry-runtime-with-compiler.js",
"type": "replace",
"edit_start_line_idx": 8
} | body {
font-family: Helvetica Neue, Arial, sans-serif;
}
polygon {
fill: #42b983;
opacity: .75;
}
circle {
fill: transparent;
stroke: #999;
}
text {
font-family: Helvetica Neue, Arial, sans-serif;
font-size: 10px;
fill: #666;
}
label {
display: inline-block;
margin-left: 10px;
width: 20px;
}
#raw {
position: absolute;
top: 0;
left: 300px;
} | examples/svg/style.css | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00017987238243222237,
0.00017224196926690638,
0.00016629768651910126,
0.00017139890405815095,
0.000005444749604066601
] |
{
"id": 6,
"code_window": [
"import { mark, measure } from 'core/util/perf'\n",
"\n",
"import Vue from './runtime/index'\n",
"import { query } from './util/index'\n",
"import { shouldDecodeNewlines } from './util/compat'\n",
"import { compileToFunctions } from './compiler/index'\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "src/platforms/web/entry-runtime-with-compiler.js",
"type": "replace",
"edit_start_line_idx": 8
} | # vue-server-renderer
> This package is auto-generated. For pull requests please see [src/platforms/web/entry-server-renderer.js](https://github.com/vuejs/vue/blob/dev/src/platforms/web/entry-server-renderer.js).
This package offers Node.js server-side rendering for Vue 2.0.
- [API Reference](https://ssr.vuejs.org/en/api.html)
- [Vue.js Server-Side Rendering Guide](https://ssr.vuejs.org)
| packages/vue-server-renderer/README.md | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00016568419232498854,
0.00016568419232498854,
0.00016568419232498854,
0.00016568419232498854,
0
] |
{
"id": 6,
"code_window": [
"import { mark, measure } from 'core/util/perf'\n",
"\n",
"import Vue from './runtime/index'\n",
"import { query } from './util/index'\n",
"import { shouldDecodeNewlines } from './util/compat'\n",
"import { compileToFunctions } from './compiler/index'\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [],
"file_path": "src/platforms/web/entry-runtime-with-compiler.js",
"type": "replace",
"edit_start_line_idx": 8
} | /* @flow */
import { extend, warn, isObject } from 'core/util/index'
/**
* Runtime helper for rendering <slot>
*/
export function renderSlot (
name: string,
fallback: ?Array<VNode>,
props: ?Object,
bindObject: ?Object
): ?Array<VNode> {
const scopedSlotFn = this.$scopedSlots[name]
if (scopedSlotFn) { // scoped slot
props = props || {}
if (bindObject) {
if (process.env.NODE_ENV !== 'production' && !isObject(bindObject)) {
warn(
'slot v-bind without argument expects an Object',
this
)
}
props = extend(extend({}, bindObject), props)
}
return scopedSlotFn(props) || fallback
} else {
const slotNodes = this.$slots[name]
// warn duplicate slot usage
if (slotNodes && process.env.NODE_ENV !== 'production') {
slotNodes._rendered && warn(
`Duplicate presence of slot "${name}" found in the same render tree ` +
`- this will likely cause render errors.`,
this
)
slotNodes._rendered = true
}
return slotNodes || fallback
}
}
| src/core/instance/render-helpers/render-slot.js | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00017886229034047574,
0.00017262551409658045,
0.00016698076797183603,
0.00017243585898540914,
0.000004805547632713569
] |
{
"id": 7,
"code_window": [
"import { compileToFunctions } from './compiler/index'\n",
"\n",
"const idToTemplate = cached(id => {\n",
" const el = query(id)\n",
" return el && el.innerHTML\n",
"})\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { shouldDecodeNewlines, shouldDecodeNewlinesForHref } from './util/compat'\n"
],
"file_path": "src/platforms/web/entry-runtime-with-compiler.js",
"type": "add",
"edit_start_line_idx": 10
} | /**
* Not type-checking this file because it's mostly vendor code.
*/
/*!
* HTML Parser By John Resig (ejohn.org)
* Modified by Juriy "kangax" Zaytsev
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*/
import { makeMap, no } from 'shared/util'
import { isNonPhrasingTag } from 'web/compiler/util'
// Regular Expressions for parsing tags and attributes
const attribute = /^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/
// could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName
// but for Vue templates we can enforce a simple charset
const ncname = '[a-zA-Z_][\\w\\-\\.]*'
const qnameCapture = `((?:${ncname}\\:)?${ncname})`
const startTagOpen = new RegExp(`^<${qnameCapture}`)
const startTagClose = /^\s*(\/?)>/
const endTag = new RegExp(`^<\\/${qnameCapture}[^>]*>`)
const doctype = /^<!DOCTYPE [^>]+>/i
const comment = /^<!--/
const conditionalComment = /^<!\[/
let IS_REGEX_CAPTURING_BROKEN = false
'x'.replace(/x(.)?/g, function (m, g) {
IS_REGEX_CAPTURING_BROKEN = g === ''
})
// Special Elements (can contain anything)
export const isPlainTextElement = makeMap('script,style,textarea', true)
const reCache = {}
const decodingMap = {
'<': '<',
'>': '>',
'"': '"',
'&': '&',
' ': '\n'
}
const encodedAttr = /&(?:lt|gt|quot|amp);/g
const encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10);/g
// #5992
const isIgnoreNewlineTag = makeMap('pre,textarea', true)
const shouldIgnoreFirstNewline = (tag, html) => tag && isIgnoreNewlineTag(tag) && html[0] === '\n'
function decodeAttr (value, shouldDecodeNewlines) {
const re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr
return value.replace(re, match => decodingMap[match])
}
export function parseHTML (html, options) {
const stack = []
const expectHTML = options.expectHTML
const isUnaryTag = options.isUnaryTag || no
const canBeLeftOpenTag = options.canBeLeftOpenTag || no
let index = 0
let last, lastTag
while (html) {
last = html
// Make sure we're not in a plaintext content element like script/style
if (!lastTag || !isPlainTextElement(lastTag)) {
let textEnd = html.indexOf('<')
if (textEnd === 0) {
// Comment:
if (comment.test(html)) {
const commentEnd = html.indexOf('-->')
if (commentEnd >= 0) {
if (options.shouldKeepComment) {
options.comment(html.substring(4, commentEnd))
}
advance(commentEnd + 3)
continue
}
}
// http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment
if (conditionalComment.test(html)) {
const conditionalEnd = html.indexOf(']>')
if (conditionalEnd >= 0) {
advance(conditionalEnd + 2)
continue
}
}
// Doctype:
const doctypeMatch = html.match(doctype)
if (doctypeMatch) {
advance(doctypeMatch[0].length)
continue
}
// End tag:
const endTagMatch = html.match(endTag)
if (endTagMatch) {
const curIndex = index
advance(endTagMatch[0].length)
parseEndTag(endTagMatch[1], curIndex, index)
continue
}
// Start tag:
const startTagMatch = parseStartTag()
if (startTagMatch) {
handleStartTag(startTagMatch)
if (shouldIgnoreFirstNewline(lastTag, html)) {
advance(1)
}
continue
}
}
let text, rest, next
if (textEnd >= 0) {
rest = html.slice(textEnd)
while (
!endTag.test(rest) &&
!startTagOpen.test(rest) &&
!comment.test(rest) &&
!conditionalComment.test(rest)
) {
// < in plain text, be forgiving and treat it as text
next = rest.indexOf('<', 1)
if (next < 0) break
textEnd += next
rest = html.slice(textEnd)
}
text = html.substring(0, textEnd)
advance(textEnd)
}
if (textEnd < 0) {
text = html
html = ''
}
if (options.chars && text) {
options.chars(text)
}
} else {
let endTagLength = 0
const stackedTag = lastTag.toLowerCase()
const reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i'))
const rest = html.replace(reStackedTag, function (all, text, endTag) {
endTagLength = endTag.length
if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') {
text = text
.replace(/<!--([\s\S]*?)-->/g, '$1')
.replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1')
}
if (shouldIgnoreFirstNewline(stackedTag, text)) {
text = text.slice(1)
}
if (options.chars) {
options.chars(text)
}
return ''
})
index += html.length - rest.length
html = rest
parseEndTag(stackedTag, index - endTagLength, index)
}
if (html === last) {
options.chars && options.chars(html)
if (process.env.NODE_ENV !== 'production' && !stack.length && options.warn) {
options.warn(`Mal-formatted tag at end of template: "${html}"`)
}
break
}
}
// Clean up any remaining tags
parseEndTag()
function advance (n) {
index += n
html = html.substring(n)
}
function parseStartTag () {
const start = html.match(startTagOpen)
if (start) {
const match = {
tagName: start[1],
attrs: [],
start: index
}
advance(start[0].length)
let end, attr
while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) {
advance(attr[0].length)
match.attrs.push(attr)
}
if (end) {
match.unarySlash = end[1]
advance(end[0].length)
match.end = index
return match
}
}
}
function handleStartTag (match) {
const tagName = match.tagName
const unarySlash = match.unarySlash
if (expectHTML) {
if (lastTag === 'p' && isNonPhrasingTag(tagName)) {
parseEndTag(lastTag)
}
if (canBeLeftOpenTag(tagName) && lastTag === tagName) {
parseEndTag(tagName)
}
}
const unary = isUnaryTag(tagName) || !!unarySlash
const l = match.attrs.length
const attrs = new Array(l)
for (let i = 0; i < l; i++) {
const args = match.attrs[i]
// hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778
if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) {
if (args[3] === '') { delete args[3] }
if (args[4] === '') { delete args[4] }
if (args[5] === '') { delete args[5] }
}
const value = args[3] || args[4] || args[5] || ''
attrs[i] = {
name: args[1],
value: decodeAttr(
value,
options.shouldDecodeNewlines
)
}
}
if (!unary) {
stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs })
lastTag = tagName
}
if (options.start) {
options.start(tagName, attrs, unary, match.start, match.end)
}
}
function parseEndTag (tagName, start, end) {
let pos, lowerCasedTagName
if (start == null) start = index
if (end == null) end = index
if (tagName) {
lowerCasedTagName = tagName.toLowerCase()
}
// Find the closest opened tag of the same type
if (tagName) {
for (pos = stack.length - 1; pos >= 0; pos--) {
if (stack[pos].lowerCasedTag === lowerCasedTagName) {
break
}
}
} else {
// If no tag name is provided, clean shop
pos = 0
}
if (pos >= 0) {
// Close all the open elements, up the stack
for (let i = stack.length - 1; i >= pos; i--) {
if (process.env.NODE_ENV !== 'production' &&
(i > pos || !tagName) &&
options.warn
) {
options.warn(
`tag <${stack[i].tag}> has no matching end tag.`
)
}
if (options.end) {
options.end(stack[i].tag, start, end)
}
}
// Remove the open elements from the stack
stack.length = pos
lastTag = pos && stack[pos - 1].tag
} else if (lowerCasedTagName === 'br') {
if (options.start) {
options.start(tagName, [], true, start, end)
}
} else if (lowerCasedTagName === 'p') {
if (options.start) {
options.start(tagName, [], false, start, end)
}
if (options.end) {
options.end(tagName, start, end)
}
}
}
}
| src/compiler/parser/html-parser.js | 1 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00017866217240225524,
0.0001696170074865222,
0.00016369055083487183,
0.00016881815099623054,
0.00000273230352831888
] |
{
"id": 7,
"code_window": [
"import { compileToFunctions } from './compiler/index'\n",
"\n",
"const idToTemplate = cached(id => {\n",
" const el = query(id)\n",
" return el && el.innerHTML\n",
"})\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { shouldDecodeNewlines, shouldDecodeNewlinesForHref } from './util/compat'\n"
],
"file_path": "src/platforms/web/entry-runtime-with-compiler.js",
"type": "add",
"edit_start_line_idx": 10
} | .DS_Store
node_modules
*.log
explorations
TODOs.md
dist/*.gz
dist/*.map
dist/vue.common.min.js
test/e2e/reports
test/e2e/screenshots
coverage
RELEASE_NOTE*.md
dist/*.js
packages/vue-server-renderer/basic.js
packages/vue-server-renderer/build.js
packages/vue-server-renderer/server-plugin.js
packages/vue-server-renderer/client-plugin.js
packages/vue-template-compiler/build.js
.vscode
| .gitignore | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00017461157403886318,
0.00017010161536745727,
0.00016559165669605136,
0.00017010161536745727,
0.0000045099586714059114
] |
{
"id": 7,
"code_window": [
"import { compileToFunctions } from './compiler/index'\n",
"\n",
"const idToTemplate = cached(id => {\n",
" const el = query(id)\n",
" return el && el.innerHTML\n",
"})\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { shouldDecodeNewlines, shouldDecodeNewlinesForHref } from './util/compat'\n"
],
"file_path": "src/platforms/web/entry-runtime-with-compiler.js",
"type": "add",
"edit_start_line_idx": 10
} | /* @flow */
import { warn } from 'core/util/index'
import { cached, isUndef } from 'shared/util'
const normalizeEvent = cached((name: string): {
name: string,
once: boolean,
capture: boolean,
passive: boolean
} => {
const passive = name.charAt(0) === '&'
name = passive ? name.slice(1) : name
const once = name.charAt(0) === '~' // Prefixed last, checked first
name = once ? name.slice(1) : name
const capture = name.charAt(0) === '!'
name = capture ? name.slice(1) : name
return {
name,
once,
capture,
passive
}
})
export function createFnInvoker (fns: Function | Array<Function>): Function {
function invoker () {
const fns = invoker.fns
if (Array.isArray(fns)) {
const cloned = fns.slice()
for (let i = 0; i < cloned.length; i++) {
cloned[i].apply(null, arguments)
}
} else {
// return handler return value for single handlers
return fns.apply(null, arguments)
}
}
invoker.fns = fns
return invoker
}
export function updateListeners (
on: Object,
oldOn: Object,
add: Function,
remove: Function,
vm: Component
) {
let name, cur, old, event
for (name in on) {
cur = on[name]
old = oldOn[name]
event = normalizeEvent(name)
if (isUndef(cur)) {
process.env.NODE_ENV !== 'production' && warn(
`Invalid handler for event "${event.name}": got ` + String(cur),
vm
)
} else if (isUndef(old)) {
if (isUndef(cur.fns)) {
cur = on[name] = createFnInvoker(cur)
}
add(event.name, cur, event.once, event.capture, event.passive)
} else if (cur !== old) {
old.fns = cur
on[name] = old
}
}
for (name in oldOn) {
if (isUndef(on[name])) {
event = normalizeEvent(name)
remove(event.name, oldOn[name], event.capture)
}
}
}
| src/core/vdom/helpers/update-listeners.js | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.0007598374504595995,
0.0002454215718898922,
0.00016653441707603633,
0.0001729563227854669,
0.0001944457762874663
] |
{
"id": 7,
"code_window": [
"import { compileToFunctions } from './compiler/index'\n",
"\n",
"const idToTemplate = cached(id => {\n",
" const el = query(id)\n",
" return el && el.innerHTML\n",
"})\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { shouldDecodeNewlines, shouldDecodeNewlinesForHref } from './util/compat'\n"
],
"file_path": "src/platforms/web/entry-runtime-with-compiler.js",
"type": "add",
"edit_start_line_idx": 10
} | var alias = require('../../build/alias')
var webpack = require('webpack')
var webpackConfig = {
resolve: {
alias: alias
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
}
]
},
plugins: [
new webpack.DefinePlugin({
__WEEX__: false,
'process.env': {
NODE_ENV: '"development"',
TRANSITION_DURATION: 50,
TRANSITION_BUFFER: 10
}
})
],
devtool: '#inline-source-map'
}
// shared config for all unit tests
module.exports = {
frameworks: ['jasmine'],
files: [
'./index.js'
],
preprocessors: {
'./index.js': ['webpack', 'sourcemap']
},
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true
},
plugins: [
'karma-jasmine',
'karma-mocha-reporter',
'karma-sourcemap-loader',
'karma-webpack'
]
}
| test/unit/karma.base.config.js | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00017174896493088454,
0.00017078856762964278,
0.0001693595404503867,
0.00017063229461200535,
8.629567673779093e-7
] |
{
"id": 8,
"code_window": [
" mark('compile')\n",
" }\n",
"\n",
" const { render, staticRenderFns } = compileToFunctions(template, {\n",
" shouldDecodeNewlines,\n",
" delimiters: options.delimiters,\n",
" comments: options.comments\n",
" }, this)\n",
" options.render = render\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" shouldDecodeNewlinesForHref,\n"
],
"file_path": "src/platforms/web/entry-runtime-with-compiler.js",
"type": "add",
"edit_start_line_idx": 66
} | /* @flow */
import { inBrowser } from 'core/util/index'
// check whether current browser encodes a char inside attribute values
function shouldDecode (content: string, encoded: string): boolean {
const div = document.createElement('div')
div.innerHTML = `<div a="${content}"/>`
return div.innerHTML.indexOf(encoded) > 0
}
// #3663
// IE encodes newlines inside attribute values while other browsers don't
export const shouldDecodeNewlines = inBrowser ? shouldDecode('\n', ' ') : false
| src/platforms/web/util/compat.js | 1 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.001913084532134235,
0.0017984238220378757,
0.0016837631119415164,
0.0017984238220378757,
0.00011466071009635925
] |
{
"id": 8,
"code_window": [
" mark('compile')\n",
" }\n",
"\n",
" const { render, staticRenderFns } = compileToFunctions(template, {\n",
" shouldDecodeNewlines,\n",
" delimiters: options.delimiters,\n",
" comments: options.comments\n",
" }, this)\n",
" options.render = render\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" shouldDecodeNewlinesForHref,\n"
],
"file_path": "src/platforms/web/entry-runtime-with-compiler.js",
"type": "add",
"edit_start_line_idx": 66
} | /* @flow */
import { createPromiseCallback } from '../util'
import { createBundleRunner } from './create-bundle-runner'
import type { Renderer, RenderOptions } from '../create-renderer'
import { createSourceMapConsumers, rewriteErrorTrace } from './source-map-support'
const fs = require('fs')
const path = require('path')
const PassThrough = require('stream').PassThrough
const INVALID_MSG =
'Invalid server-rendering bundle format. Should be a string ' +
'or a bundle Object of type:\n\n' +
`{
entry: string;
files: { [filename: string]: string; };
maps: { [filename: string]: string; };
}\n`
// The render bundle can either be a string (single bundled file)
// or a bundle manifest object generated by vue-ssr-webpack-plugin.
type RenderBundle = {
basedir?: string;
entry: string;
files: { [filename: string]: string; };
maps: { [filename: string]: string; };
modules?: { [filename: string]: Array<string> };
};
export function createBundleRendererCreator (
createRenderer: (options?: RenderOptions) => Renderer
) {
return function createBundleRenderer (
bundle: string | RenderBundle,
rendererOptions?: RenderOptions = {}
) {
let files, entry, maps
let basedir = rendererOptions.basedir
// load bundle if given filepath
if (
typeof bundle === 'string' &&
/\.js(on)?$/.test(bundle) &&
path.isAbsolute(bundle)
) {
if (fs.existsSync(bundle)) {
const isJSON = /\.json$/.test(bundle)
basedir = basedir || path.dirname(bundle)
bundle = fs.readFileSync(bundle, 'utf-8')
if (isJSON) {
try {
bundle = JSON.parse(bundle)
} catch (e) {
throw new Error(`Invalid JSON bundle file: ${bundle}`)
}
}
} else {
throw new Error(`Cannot locate bundle file: ${bundle}`)
}
}
if (typeof bundle === 'object') {
entry = bundle.entry
files = bundle.files
basedir = basedir || bundle.basedir
maps = createSourceMapConsumers(bundle.maps)
if (typeof entry !== 'string' || typeof files !== 'object') {
throw new Error(INVALID_MSG)
}
} else if (typeof bundle === 'string') {
entry = '__vue_ssr_bundle__'
files = { '__vue_ssr_bundle__': bundle }
maps = {}
} else {
throw new Error(INVALID_MSG)
}
const renderer = createRenderer(rendererOptions)
const run = createBundleRunner(
entry,
files,
basedir,
rendererOptions.runInNewContext
)
return {
renderToString: (context?: Object, cb: any) => {
if (typeof context === 'function') {
cb = context
context = {}
}
let promise
if (!cb) {
({ promise, cb } = createPromiseCallback())
}
run(context).catch(err => {
rewriteErrorTrace(err, maps)
cb(err)
}).then(app => {
if (app) {
renderer.renderToString(app, context, (err, res) => {
rewriteErrorTrace(err, maps)
cb(err, res)
})
}
})
return promise
},
renderToStream: (context?: Object) => {
const res = new PassThrough()
run(context).catch(err => {
rewriteErrorTrace(err, maps)
// avoid emitting synchronously before user can
// attach error listener
process.nextTick(() => {
res.emit('error', err)
})
}).then(app => {
if (app) {
const renderStream = renderer.renderToStream(app, context)
renderStream.on('error', err => {
rewriteErrorTrace(err, maps)
res.emit('error', err)
})
// relay HTMLStream special events
if (rendererOptions && rendererOptions.template) {
renderStream.on('beforeStart', () => {
res.emit('beforeStart')
})
renderStream.on('beforeEnd', () => {
res.emit('beforeEnd')
})
}
renderStream.pipe(res)
}
})
return res
}
}
}
}
| src/server/bundle-renderer/create-bundle-renderer.js | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.0002508526958990842,
0.0001783748739399016,
0.00016495026648044586,
0.00017286519869230688,
0.00002144254176528193
] |
{
"id": 8,
"code_window": [
" mark('compile')\n",
" }\n",
"\n",
" const { render, staticRenderFns } = compileToFunctions(template, {\n",
" shouldDecodeNewlines,\n",
" delimiters: options.delimiters,\n",
" comments: options.comments\n",
" }, this)\n",
" options.render = render\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" shouldDecodeNewlinesForHref,\n"
],
"file_path": "src/platforms/web/entry-runtime-with-compiler.js",
"type": "add",
"edit_start_line_idx": 66
} | /* @flow */
import {
no,
noop,
identity
} from 'shared/util'
import { LIFECYCLE_HOOKS } from 'shared/constants'
export type Config = {
// user
optionMergeStrategies: { [key: string]: Function };
silent: boolean;
productionTip: boolean;
performance: boolean;
devtools: boolean;
errorHandler: ?(err: Error, vm: Component, info: string) => void;
warnHandler: ?(msg: string, vm: Component, trace: string) => void;
ignoredElements: Array<string | RegExp>;
keyCodes: { [key: string]: number | Array<number> };
// platform
isReservedTag: (x?: string) => boolean;
isReservedAttr: (x?: string) => boolean;
parsePlatformTagName: (x: string) => string;
isUnknownElement: (x?: string) => boolean;
getTagNamespace: (x?: string) => string | void;
mustUseProp: (tag: string, type: ?string, name: string) => boolean;
// legacy
_lifecycleHooks: Array<string>;
};
export default ({
/**
* Option merge strategies (used in core/util/options)
*/
optionMergeStrategies: Object.create(null),
/**
* Whether to suppress warnings.
*/
silent: false,
/**
* Show production mode tip message on boot?
*/
productionTip: process.env.NODE_ENV !== 'production',
/**
* Whether to enable devtools
*/
devtools: process.env.NODE_ENV !== 'production',
/**
* Whether to record perf
*/
performance: false,
/**
* Error handler for watcher errors
*/
errorHandler: null,
/**
* Warn handler for watcher warns
*/
warnHandler: null,
/**
* Ignore certain custom elements
*/
ignoredElements: [],
/**
* Custom user key aliases for v-on
*/
keyCodes: Object.create(null),
/**
* Check if a tag is reserved so that it cannot be registered as a
* component. This is platform-dependent and may be overwritten.
*/
isReservedTag: no,
/**
* Check if an attribute is reserved so that it cannot be used as a component
* prop. This is platform-dependent and may be overwritten.
*/
isReservedAttr: no,
/**
* Check if a tag is an unknown element.
* Platform-dependent.
*/
isUnknownElement: no,
/**
* Get the namespace of an element
*/
getTagNamespace: noop,
/**
* Parse the real tag name for the specific platform.
*/
parsePlatformTagName: identity,
/**
* Check if an attribute must be bound using property, e.g. value
* Platform-dependent.
*/
mustUseProp: no,
/**
* Exposed for legacy reasons
*/
_lifecycleHooks: LIFECYCLE_HOOKS
}: Config)
| src/core/config.js | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00024047133047133684,
0.0001767008943716064,
0.000165305013069883,
0.00017232488607987761,
0.000019397786672925577
] |
{
"id": 8,
"code_window": [
" mark('compile')\n",
" }\n",
"\n",
" const { render, staticRenderFns } = compileToFunctions(template, {\n",
" shouldDecodeNewlines,\n",
" delimiters: options.delimiters,\n",
" comments: options.comments\n",
" }, this)\n",
" options.render = render\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" shouldDecodeNewlinesForHref,\n"
],
"file_path": "src/platforms/web/entry-runtime-with-compiler.js",
"type": "add",
"edit_start_line_idx": 66
} | import { Plugin } from 'webpack';
interface WebpackPluginOptions {
filename?: string;
}
export interface WebpackPlugin {
new (options?: WebpackPluginOptions): Plugin;
}
| packages/vue-server-renderer/types/plugin.d.ts | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.0003795140655711293,
0.0003795140655711293,
0.0003795140655711293,
0.0003795140655711293,
0
] |
{
"id": 9,
"code_window": [
"import { inBrowser } from 'core/util/index'\n",
"\n",
"// check whether current browser encodes a char inside attribute values\n",
"function shouldDecode (content: string, encoded: string): boolean {\n",
" const div = document.createElement('div')\n",
" div.innerHTML = `<div a=\"${content}\"/>`\n",
" return div.innerHTML.indexOf(encoded) > 0\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"let div\n",
"function getShouldDecode (href: boolean): boolean {\n",
" div = div || document.createElement('div')\n",
" div.innerHTML = href ? `<a href=\"\\n\"/>` : `<div a=\"\\n\"/>`\n",
" return div.innerHTML.indexOf(' ') > 0\n"
],
"file_path": "src/platforms/web/util/compat.js",
"type": "replace",
"edit_start_line_idx": 5
} | /**
* Not type-checking this file because it's mostly vendor code.
*/
/*!
* HTML Parser By John Resig (ejohn.org)
* Modified by Juriy "kangax" Zaytsev
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*/
import { makeMap, no } from 'shared/util'
import { isNonPhrasingTag } from 'web/compiler/util'
// Regular Expressions for parsing tags and attributes
const attribute = /^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/
// could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName
// but for Vue templates we can enforce a simple charset
const ncname = '[a-zA-Z_][\\w\\-\\.]*'
const qnameCapture = `((?:${ncname}\\:)?${ncname})`
const startTagOpen = new RegExp(`^<${qnameCapture}`)
const startTagClose = /^\s*(\/?)>/
const endTag = new RegExp(`^<\\/${qnameCapture}[^>]*>`)
const doctype = /^<!DOCTYPE [^>]+>/i
const comment = /^<!--/
const conditionalComment = /^<!\[/
let IS_REGEX_CAPTURING_BROKEN = false
'x'.replace(/x(.)?/g, function (m, g) {
IS_REGEX_CAPTURING_BROKEN = g === ''
})
// Special Elements (can contain anything)
export const isPlainTextElement = makeMap('script,style,textarea', true)
const reCache = {}
const decodingMap = {
'<': '<',
'>': '>',
'"': '"',
'&': '&',
' ': '\n'
}
const encodedAttr = /&(?:lt|gt|quot|amp);/g
const encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10);/g
// #5992
const isIgnoreNewlineTag = makeMap('pre,textarea', true)
const shouldIgnoreFirstNewline = (tag, html) => tag && isIgnoreNewlineTag(tag) && html[0] === '\n'
function decodeAttr (value, shouldDecodeNewlines) {
const re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr
return value.replace(re, match => decodingMap[match])
}
export function parseHTML (html, options) {
const stack = []
const expectHTML = options.expectHTML
const isUnaryTag = options.isUnaryTag || no
const canBeLeftOpenTag = options.canBeLeftOpenTag || no
let index = 0
let last, lastTag
while (html) {
last = html
// Make sure we're not in a plaintext content element like script/style
if (!lastTag || !isPlainTextElement(lastTag)) {
let textEnd = html.indexOf('<')
if (textEnd === 0) {
// Comment:
if (comment.test(html)) {
const commentEnd = html.indexOf('-->')
if (commentEnd >= 0) {
if (options.shouldKeepComment) {
options.comment(html.substring(4, commentEnd))
}
advance(commentEnd + 3)
continue
}
}
// http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment
if (conditionalComment.test(html)) {
const conditionalEnd = html.indexOf(']>')
if (conditionalEnd >= 0) {
advance(conditionalEnd + 2)
continue
}
}
// Doctype:
const doctypeMatch = html.match(doctype)
if (doctypeMatch) {
advance(doctypeMatch[0].length)
continue
}
// End tag:
const endTagMatch = html.match(endTag)
if (endTagMatch) {
const curIndex = index
advance(endTagMatch[0].length)
parseEndTag(endTagMatch[1], curIndex, index)
continue
}
// Start tag:
const startTagMatch = parseStartTag()
if (startTagMatch) {
handleStartTag(startTagMatch)
if (shouldIgnoreFirstNewline(lastTag, html)) {
advance(1)
}
continue
}
}
let text, rest, next
if (textEnd >= 0) {
rest = html.slice(textEnd)
while (
!endTag.test(rest) &&
!startTagOpen.test(rest) &&
!comment.test(rest) &&
!conditionalComment.test(rest)
) {
// < in plain text, be forgiving and treat it as text
next = rest.indexOf('<', 1)
if (next < 0) break
textEnd += next
rest = html.slice(textEnd)
}
text = html.substring(0, textEnd)
advance(textEnd)
}
if (textEnd < 0) {
text = html
html = ''
}
if (options.chars && text) {
options.chars(text)
}
} else {
let endTagLength = 0
const stackedTag = lastTag.toLowerCase()
const reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i'))
const rest = html.replace(reStackedTag, function (all, text, endTag) {
endTagLength = endTag.length
if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') {
text = text
.replace(/<!--([\s\S]*?)-->/g, '$1')
.replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1')
}
if (shouldIgnoreFirstNewline(stackedTag, text)) {
text = text.slice(1)
}
if (options.chars) {
options.chars(text)
}
return ''
})
index += html.length - rest.length
html = rest
parseEndTag(stackedTag, index - endTagLength, index)
}
if (html === last) {
options.chars && options.chars(html)
if (process.env.NODE_ENV !== 'production' && !stack.length && options.warn) {
options.warn(`Mal-formatted tag at end of template: "${html}"`)
}
break
}
}
// Clean up any remaining tags
parseEndTag()
function advance (n) {
index += n
html = html.substring(n)
}
function parseStartTag () {
const start = html.match(startTagOpen)
if (start) {
const match = {
tagName: start[1],
attrs: [],
start: index
}
advance(start[0].length)
let end, attr
while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) {
advance(attr[0].length)
match.attrs.push(attr)
}
if (end) {
match.unarySlash = end[1]
advance(end[0].length)
match.end = index
return match
}
}
}
function handleStartTag (match) {
const tagName = match.tagName
const unarySlash = match.unarySlash
if (expectHTML) {
if (lastTag === 'p' && isNonPhrasingTag(tagName)) {
parseEndTag(lastTag)
}
if (canBeLeftOpenTag(tagName) && lastTag === tagName) {
parseEndTag(tagName)
}
}
const unary = isUnaryTag(tagName) || !!unarySlash
const l = match.attrs.length
const attrs = new Array(l)
for (let i = 0; i < l; i++) {
const args = match.attrs[i]
// hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778
if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) {
if (args[3] === '') { delete args[3] }
if (args[4] === '') { delete args[4] }
if (args[5] === '') { delete args[5] }
}
const value = args[3] || args[4] || args[5] || ''
attrs[i] = {
name: args[1],
value: decodeAttr(
value,
options.shouldDecodeNewlines
)
}
}
if (!unary) {
stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs })
lastTag = tagName
}
if (options.start) {
options.start(tagName, attrs, unary, match.start, match.end)
}
}
function parseEndTag (tagName, start, end) {
let pos, lowerCasedTagName
if (start == null) start = index
if (end == null) end = index
if (tagName) {
lowerCasedTagName = tagName.toLowerCase()
}
// Find the closest opened tag of the same type
if (tagName) {
for (pos = stack.length - 1; pos >= 0; pos--) {
if (stack[pos].lowerCasedTag === lowerCasedTagName) {
break
}
}
} else {
// If no tag name is provided, clean shop
pos = 0
}
if (pos >= 0) {
// Close all the open elements, up the stack
for (let i = stack.length - 1; i >= pos; i--) {
if (process.env.NODE_ENV !== 'production' &&
(i > pos || !tagName) &&
options.warn
) {
options.warn(
`tag <${stack[i].tag}> has no matching end tag.`
)
}
if (options.end) {
options.end(stack[i].tag, start, end)
}
}
// Remove the open elements from the stack
stack.length = pos
lastTag = pos && stack[pos - 1].tag
} else if (lowerCasedTagName === 'br') {
if (options.start) {
options.start(tagName, [], true, start, end)
}
} else if (lowerCasedTagName === 'p') {
if (options.start) {
options.start(tagName, [], false, start, end)
}
if (options.end) {
options.end(tagName, start, end)
}
}
}
}
| src/compiler/parser/html-parser.js | 1 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.12359698116779327,
0.005907805636525154,
0.00016636920918244869,
0.00017084491264540702,
0.023372313007712364
] |
{
"id": 9,
"code_window": [
"import { inBrowser } from 'core/util/index'\n",
"\n",
"// check whether current browser encodes a char inside attribute values\n",
"function shouldDecode (content: string, encoded: string): boolean {\n",
" const div = document.createElement('div')\n",
" div.innerHTML = `<div a=\"${content}\"/>`\n",
" return div.innerHTML.indexOf(encoded) > 0\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"let div\n",
"function getShouldDecode (href: boolean): boolean {\n",
" div = div || document.createElement('div')\n",
" div.innerHTML = href ? `<a href=\"\\n\"/>` : `<div a=\"\\n\"/>`\n",
" return div.innerHTML.indexOf(' ') > 0\n"
],
"file_path": "src/platforms/web/util/compat.js",
"type": "replace",
"edit_start_line_idx": 5
} | const { test, ln, chmod } = require('shelljs')
function installHooks () {
if (test('-e', '.git/hooks')) {
ln('-sf', '../../build/git-hooks/pre-commit', '.git/hooks/pre-commit')
chmod('+x', '.git/hooks/pre-commit')
ln('-sf', '../../build/git-hooks/commit-msg', '.git/hooks/commit-msg')
chmod('+x', '.git/hooks/commit-msg')
}
}
installHooks()
| build/setup.js | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00017243387992493808,
0.00017099446267820895,
0.00016955505998339504,
0.00017099446267820895,
0.000001439410084458359
] |
{
"id": 9,
"code_window": [
"import { inBrowser } from 'core/util/index'\n",
"\n",
"// check whether current browser encodes a char inside attribute values\n",
"function shouldDecode (content: string, encoded: string): boolean {\n",
" const div = document.createElement('div')\n",
" div.innerHTML = `<div a=\"${content}\"/>`\n",
" return div.innerHTML.indexOf(encoded) > 0\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"let div\n",
"function getShouldDecode (href: boolean): boolean {\n",
" div = div || document.createElement('div')\n",
" div.innerHTML = href ? `<a href=\"\\n\"/>` : `<div a=\"\\n\"/>`\n",
" return div.innerHTML.indexOf(' ') > 0\n"
],
"file_path": "src/platforms/web/util/compat.js",
"type": "replace",
"edit_start_line_idx": 5
} | /* @flow */
/**
* Original RenderStream implementation by Sasha Aickin (@aickin)
* Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Modified by Evan You (@yyx990803)
*/
const stream = require('stream')
import { isTrue, isUndef } from 'shared/util'
import { createWriteFunction } from './write'
export default class RenderStream extends stream.Readable {
buffer: string;
render: (write: Function, done: Function) => void;
expectedSize: number;
write: Function;
next: Function;
end: Function;
done: boolean;
constructor (render: Function) {
super()
this.buffer = ''
this.render = render
this.expectedSize = 0
this.write = createWriteFunction((text, next) => {
const n = this.expectedSize
this.buffer += text
if (this.buffer.length >= n) {
this.next = next
this.pushBySize(n)
return true // we will decide when to call next
}
return false
}, err => {
this.emit('error', err)
})
this.end = () => {
// the rendering is finished; we should push out the last of the buffer.
this.done = true
this.push(this.buffer)
}
}
pushBySize (n: number) {
const bufferToPush = this.buffer.substring(0, n)
this.buffer = this.buffer.substring(n)
this.push(bufferToPush)
}
tryRender () {
try {
this.render(this.write, this.end)
} catch (e) {
this.emit('error', e)
}
}
tryNext () {
try {
this.next()
} catch (e) {
this.emit('error', e)
}
}
_read (n: number) {
this.expectedSize = n
// it's possible that the last chunk added bumped the buffer up to > 2 * n,
// which means we will need to go through multiple read calls to drain it
// down to < n.
if (isTrue(this.done)) {
this.push(null)
return
}
if (this.buffer.length >= n) {
this.pushBySize(n)
return
}
if (isUndef(this.next)) {
// start the rendering chain.
this.tryRender()
} else {
// continue with the rendering.
this.tryNext()
}
}
}
| src/server/render-stream.js | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00017232343088835478,
0.00017034480697475374,
0.0001685016613919288,
0.00017009599832817912,
0.0000012338592796368175
] |
{
"id": 9,
"code_window": [
"import { inBrowser } from 'core/util/index'\n",
"\n",
"// check whether current browser encodes a char inside attribute values\n",
"function shouldDecode (content: string, encoded: string): boolean {\n",
" const div = document.createElement('div')\n",
" div.innerHTML = `<div a=\"${content}\"/>`\n",
" return div.innerHTML.indexOf(encoded) > 0\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"let div\n",
"function getShouldDecode (href: boolean): boolean {\n",
" div = div || document.createElement('div')\n",
" div.innerHTML = href ? `<a href=\"\\n\"/>` : `<div a=\"\\n\"/>`\n",
" return div.innerHTML.indexOf(' ') > 0\n"
],
"file_path": "src/platforms/web/util/compat.js",
"type": "replace",
"edit_start_line_idx": 5
} | /* @flow */
import config from 'core/config'
import { addHandler, addProp, getBindingAttr } from 'compiler/helpers'
import { genComponentModel, genAssignmentCode } from 'compiler/directives/model'
let warn
// in some cases, the event used has to be determined at runtime
// so we used some reserved tokens during compile.
export const RANGE_TOKEN = '__r'
export const CHECKBOX_RADIO_TOKEN = '__c'
export default function model (
el: ASTElement,
dir: ASTDirective,
_warn: Function
): ?boolean {
warn = _warn
const value = dir.value
const modifiers = dir.modifiers
const tag = el.tag
const type = el.attrsMap.type
if (process.env.NODE_ENV !== 'production') {
// inputs with type="file" are read only and setting the input's
// value will throw an error.
if (tag === 'input' && type === 'file') {
warn(
`<${el.tag} v-model="${value}" type="file">:\n` +
`File inputs are read only. Use a v-on:change listener instead.`
)
}
}
if (el.component) {
genComponentModel(el, value, modifiers)
// component v-model doesn't need extra runtime
return false
} else if (tag === 'select') {
genSelect(el, value, modifiers)
} else if (tag === 'input' && type === 'checkbox') {
genCheckboxModel(el, value, modifiers)
} else if (tag === 'input' && type === 'radio') {
genRadioModel(el, value, modifiers)
} else if (tag === 'input' || tag === 'textarea') {
genDefaultModel(el, value, modifiers)
} else if (!config.isReservedTag(tag)) {
genComponentModel(el, value, modifiers)
// component v-model doesn't need extra runtime
return false
} else if (process.env.NODE_ENV !== 'production') {
warn(
`<${el.tag} v-model="${value}">: ` +
`v-model is not supported on this element type. ` +
'If you are working with contenteditable, it\'s recommended to ' +
'wrap a library dedicated for that purpose inside a custom component.'
)
}
// ensure runtime directive metadata
return true
}
function genCheckboxModel (
el: ASTElement,
value: string,
modifiers: ?ASTModifiers
) {
const number = modifiers && modifiers.number
const valueBinding = getBindingAttr(el, 'value') || 'null'
const trueValueBinding = getBindingAttr(el, 'true-value') || 'true'
const falseValueBinding = getBindingAttr(el, 'false-value') || 'false'
addProp(el, 'checked',
`Array.isArray(${value})` +
`?_i(${value},${valueBinding})>-1` + (
trueValueBinding === 'true'
? `:(${value})`
: `:_q(${value},${trueValueBinding})`
)
)
addHandler(el, 'change',
`var $$a=${value},` +
'$$el=$event.target,' +
`$$c=$$el.checked?(${trueValueBinding}):(${falseValueBinding});` +
'if(Array.isArray($$a)){' +
`var $$v=${number ? '_n(' + valueBinding + ')' : valueBinding},` +
'$$i=_i($$a,$$v);' +
`if($$el.checked){$$i<0&&(${value}=$$a.concat([$$v]))}` +
`else{$$i>-1&&(${value}=$$a.slice(0,$$i).concat($$a.slice($$i+1)))}` +
`}else{${genAssignmentCode(value, '$$c')}}`,
null, true
)
}
function genRadioModel (
el: ASTElement,
value: string,
modifiers: ?ASTModifiers
) {
const number = modifiers && modifiers.number
let valueBinding = getBindingAttr(el, 'value') || 'null'
valueBinding = number ? `_n(${valueBinding})` : valueBinding
addProp(el, 'checked', `_q(${value},${valueBinding})`)
addHandler(el, 'change', genAssignmentCode(value, valueBinding), null, true)
}
function genSelect (
el: ASTElement,
value: string,
modifiers: ?ASTModifiers
) {
const number = modifiers && modifiers.number
const selectedVal = `Array.prototype.filter` +
`.call($event.target.options,function(o){return o.selected})` +
`.map(function(o){var val = "_value" in o ? o._value : o.value;` +
`return ${number ? '_n(val)' : 'val'}})`
const assignment = '$event.target.multiple ? $$selectedVal : $$selectedVal[0]'
let code = `var $$selectedVal = ${selectedVal};`
code = `${code} ${genAssignmentCode(value, assignment)}`
addHandler(el, 'change', code, null, true)
}
function genDefaultModel (
el: ASTElement,
value: string,
modifiers: ?ASTModifiers
): ?boolean {
const type = el.attrsMap.type
const { lazy, number, trim } = modifiers || {}
const needCompositionGuard = !lazy && type !== 'range'
const event = lazy
? 'change'
: type === 'range'
? RANGE_TOKEN
: 'input'
let valueExpression = '$event.target.value'
if (trim) {
valueExpression = `$event.target.value.trim()`
}
if (number) {
valueExpression = `_n(${valueExpression})`
}
let code = genAssignmentCode(value, valueExpression)
if (needCompositionGuard) {
code = `if($event.target.composing)return;${code}`
}
addProp(el, 'value', `(${value})`)
addHandler(el, event, code, null, true)
if (trim || number) {
addHandler(el, 'blur', '$forceUpdate()')
}
}
| src/platforms/web/compiler/directives/model.js | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.0005243196501396596,
0.00020320044131949544,
0.0001664882292971015,
0.00017133928486146033,
0.00008889701712178066
] |
{
"id": 10,
"code_window": [
"}\n",
"\n",
"// #3663\n",
"// IE encodes newlines inside attribute values while other browsers don't\n",
"export const shouldDecodeNewlines = inBrowser ? shouldDecode('\\n', ' ') : false\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace"
],
"after_edit": [
"// #3663: IE encodes newlines inside attribute values while other browsers don't\n",
"export const shouldDecodeNewlines = inBrowser ? getShouldDecode(false) : false\n",
"// #6828: chrome encodes content in a[href]\n",
"export const shouldDecodeNewlinesForHref = inBrowser ? getShouldDecode(true) : false"
],
"file_path": "src/platforms/web/util/compat.js",
"type": "replace",
"edit_start_line_idx": 11
} | /* @flow */
import he from 'he'
import { parseHTML } from './html-parser'
import { parseText } from './text-parser'
import { parseFilters } from './filter-parser'
import { cached, no, camelize } from 'shared/util'
import { genAssignmentCode } from '../directives/model'
import { isIE, isEdge, isServerRendering } from 'core/util/env'
import {
addProp,
addAttr,
baseWarn,
addHandler,
addDirective,
getBindingAttr,
getAndRemoveAttr,
pluckModuleFunction
} from '../helpers'
export const onRE = /^@|^v-on:/
export const dirRE = /^v-|^@|^:/
export const forAliasRE = /(.*?)\s+(?:in|of)\s+(.*)/
export const forIteratorRE = /\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/
const argRE = /:(.*)$/
const bindRE = /^:|^v-bind:/
const modifierRE = /\.[^.]+/g
const decodeHTMLCached = cached(he.decode)
// configurable state
export let warn: any
let delimiters
let transforms
let preTransforms
let postTransforms
let platformIsPreTag
let platformMustUseProp
let platformGetTagNamespace
type Attr = { name: string; value: string };
export function createASTElement (
tag: string,
attrs: Array<Attr>,
parent: ASTElement | void
): ASTElement {
return {
type: 1,
tag,
attrsList: attrs,
attrsMap: makeAttrsMap(attrs),
parent,
children: []
}
}
/**
* Convert HTML string to AST.
*/
export function parse (
template: string,
options: CompilerOptions
): ASTElement | void {
warn = options.warn || baseWarn
platformIsPreTag = options.isPreTag || no
platformMustUseProp = options.mustUseProp || no
platformGetTagNamespace = options.getTagNamespace || no
transforms = pluckModuleFunction(options.modules, 'transformNode')
preTransforms = pluckModuleFunction(options.modules, 'preTransformNode')
postTransforms = pluckModuleFunction(options.modules, 'postTransformNode')
delimiters = options.delimiters
const stack = []
const preserveWhitespace = options.preserveWhitespace !== false
let root
let currentParent
let inVPre = false
let inPre = false
let warned = false
function warnOnce (msg) {
if (!warned) {
warned = true
warn(msg)
}
}
function endPre (element) {
// check pre state
if (element.pre) {
inVPre = false
}
if (platformIsPreTag(element.tag)) {
inPre = false
}
}
parseHTML(template, {
warn,
expectHTML: options.expectHTML,
isUnaryTag: options.isUnaryTag,
canBeLeftOpenTag: options.canBeLeftOpenTag,
shouldDecodeNewlines: options.shouldDecodeNewlines,
shouldKeepComment: options.comments,
start (tag, attrs, unary) {
// check namespace.
// inherit parent ns if there is one
const ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag)
// handle IE svg bug
/* istanbul ignore if */
if (isIE && ns === 'svg') {
attrs = guardIESVGBug(attrs)
}
let element: ASTElement = createASTElement(tag, attrs, currentParent)
if (ns) {
element.ns = ns
}
if (isForbiddenTag(element) && !isServerRendering()) {
element.forbidden = true
process.env.NODE_ENV !== 'production' && warn(
'Templates should only be responsible for mapping the state to the ' +
'UI. Avoid placing tags with side-effects in your templates, such as ' +
`<${tag}>` + ', as they will not be parsed.'
)
}
// apply pre-transforms
for (let i = 0; i < preTransforms.length; i++) {
element = preTransforms[i](element, options) || element
}
if (!inVPre) {
processPre(element)
if (element.pre) {
inVPre = true
}
}
if (platformIsPreTag(element.tag)) {
inPre = true
}
if (inVPre) {
processRawAttrs(element)
} else if (!element.processed) {
// structural directives
processFor(element)
processIf(element)
processOnce(element)
// element-scope stuff
processElement(element, options)
}
function checkRootConstraints (el) {
if (process.env.NODE_ENV !== 'production') {
if (el.tag === 'slot' || el.tag === 'template') {
warnOnce(
`Cannot use <${el.tag}> as component root element because it may ` +
'contain multiple nodes.'
)
}
if (el.attrsMap.hasOwnProperty('v-for')) {
warnOnce(
'Cannot use v-for on stateful component root element because ' +
'it renders multiple elements.'
)
}
}
}
// tree management
if (!root) {
root = element
checkRootConstraints(root)
} else if (!stack.length) {
// allow root elements with v-if, v-else-if and v-else
if (root.if && (element.elseif || element.else)) {
checkRootConstraints(element)
addIfCondition(root, {
exp: element.elseif,
block: element
})
} else if (process.env.NODE_ENV !== 'production') {
warnOnce(
`Component template should contain exactly one root element. ` +
`If you are using v-if on multiple elements, ` +
`use v-else-if to chain them instead.`
)
}
}
if (currentParent && !element.forbidden) {
if (element.elseif || element.else) {
processIfConditions(element, currentParent)
} else if (element.slotScope) { // scoped slot
currentParent.plain = false
const name = element.slotTarget || '"default"'
;(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element
} else {
currentParent.children.push(element)
element.parent = currentParent
}
}
if (!unary) {
currentParent = element
stack.push(element)
} else {
endPre(element)
}
// apply post-transforms
for (let i = 0; i < postTransforms.length; i++) {
postTransforms[i](element, options)
}
},
end () {
// remove trailing whitespace
const element = stack[stack.length - 1]
const lastNode = element.children[element.children.length - 1]
if (lastNode && lastNode.type === 3 && lastNode.text === ' ' && !inPre) {
element.children.pop()
}
// pop stack
stack.length -= 1
currentParent = stack[stack.length - 1]
endPre(element)
},
chars (text: string) {
if (!currentParent) {
if (process.env.NODE_ENV !== 'production') {
if (text === template) {
warnOnce(
'Component template requires a root element, rather than just text.'
)
} else if ((text = text.trim())) {
warnOnce(
`text "${text}" outside root element will be ignored.`
)
}
}
return
}
// IE textarea placeholder bug
/* istanbul ignore if */
if (isIE &&
currentParent.tag === 'textarea' &&
currentParent.attrsMap.placeholder === text
) {
return
}
const children = currentParent.children
text = inPre || text.trim()
? isTextTag(currentParent) ? text : decodeHTMLCached(text)
// only preserve whitespace if its not right after a starting tag
: preserveWhitespace && children.length ? ' ' : ''
if (text) {
let expression
if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) {
children.push({
type: 2,
expression,
text
})
} else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') {
children.push({
type: 3,
text
})
}
}
},
comment (text: string) {
currentParent.children.push({
type: 3,
text,
isComment: true
})
}
})
return root
}
function processPre (el) {
if (getAndRemoveAttr(el, 'v-pre') != null) {
el.pre = true
}
}
function processRawAttrs (el) {
const l = el.attrsList.length
if (l) {
const attrs = el.attrs = new Array(l)
for (let i = 0; i < l; i++) {
attrs[i] = {
name: el.attrsList[i].name,
value: JSON.stringify(el.attrsList[i].value)
}
}
} else if (!el.pre) {
// non root node in pre blocks with no attributes
el.plain = true
}
}
export function processElement (element: ASTElement, options: CompilerOptions) {
processKey(element)
// determine whether this is a plain element after
// removing structural attributes
element.plain = !element.key && !element.attrsList.length
processRef(element)
processSlot(element)
processComponent(element)
for (let i = 0; i < transforms.length; i++) {
element = transforms[i](element, options) || element
}
processAttrs(element)
}
function processKey (el) {
const exp = getBindingAttr(el, 'key')
if (exp) {
if (process.env.NODE_ENV !== 'production' && el.tag === 'template') {
warn(`<template> cannot be keyed. Place the key on real elements instead.`)
}
el.key = exp
}
}
function processRef (el) {
const ref = getBindingAttr(el, 'ref')
if (ref) {
el.ref = ref
el.refInFor = checkInFor(el)
}
}
export function processFor (el: ASTElement) {
let exp
if ((exp = getAndRemoveAttr(el, 'v-for'))) {
const inMatch = exp.match(forAliasRE)
if (!inMatch) {
process.env.NODE_ENV !== 'production' && warn(
`Invalid v-for expression: ${exp}`
)
return
}
el.for = inMatch[2].trim()
const alias = inMatch[1].trim()
const iteratorMatch = alias.match(forIteratorRE)
if (iteratorMatch) {
el.alias = iteratorMatch[1].trim()
el.iterator1 = iteratorMatch[2].trim()
if (iteratorMatch[3]) {
el.iterator2 = iteratorMatch[3].trim()
}
} else {
el.alias = alias
}
}
}
function processIf (el) {
const exp = getAndRemoveAttr(el, 'v-if')
if (exp) {
el.if = exp
addIfCondition(el, {
exp: exp,
block: el
})
} else {
if (getAndRemoveAttr(el, 'v-else') != null) {
el.else = true
}
const elseif = getAndRemoveAttr(el, 'v-else-if')
if (elseif) {
el.elseif = elseif
}
}
}
function processIfConditions (el, parent) {
const prev = findPrevElement(parent.children)
if (prev && prev.if) {
addIfCondition(prev, {
exp: el.elseif,
block: el
})
} else if (process.env.NODE_ENV !== 'production') {
warn(
`v-${el.elseif ? ('else-if="' + el.elseif + '"') : 'else'} ` +
`used on element <${el.tag}> without corresponding v-if.`
)
}
}
function findPrevElement (children: Array<any>): ASTElement | void {
let i = children.length
while (i--) {
if (children[i].type === 1) {
return children[i]
} else {
if (process.env.NODE_ENV !== 'production' && children[i].text !== ' ') {
warn(
`text "${children[i].text.trim()}" between v-if and v-else(-if) ` +
`will be ignored.`
)
}
children.pop()
}
}
}
export function addIfCondition (el: ASTElement, condition: ASTIfCondition) {
if (!el.ifConditions) {
el.ifConditions = []
}
el.ifConditions.push(condition)
}
function processOnce (el) {
const once = getAndRemoveAttr(el, 'v-once')
if (once != null) {
el.once = true
}
}
function processSlot (el) {
if (el.tag === 'slot') {
el.slotName = getBindingAttr(el, 'name')
if (process.env.NODE_ENV !== 'production' && el.key) {
warn(
`\`key\` does not work on <slot> because slots are abstract outlets ` +
`and can possibly expand into multiple elements. ` +
`Use the key on a wrapping element instead.`
)
}
} else {
let slotScope
if (el.tag === 'template') {
slotScope = getAndRemoveAttr(el, 'scope')
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && slotScope) {
warn(
`the "scope" attribute for scoped slots have been deprecated and ` +
`replaced by "slot-scope" since 2.5. The new "slot-scope" attribute ` +
`can also be used on plain elements in addition to <template> to ` +
`denote scoped slots.`,
true
)
}
el.slotScope = slotScope || getAndRemoveAttr(el, 'slot-scope')
} else if ((slotScope = getAndRemoveAttr(el, 'slot-scope'))) {
el.slotScope = slotScope
}
const slotTarget = getBindingAttr(el, 'slot')
if (slotTarget) {
el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget
// preserve slot as an attribute for native shadow DOM compat
// only for non-scoped slots.
if (!el.slotScope) {
addAttr(el, 'slot', slotTarget)
}
}
}
}
function processComponent (el) {
let binding
if ((binding = getBindingAttr(el, 'is'))) {
el.component = binding
}
if (getAndRemoveAttr(el, 'inline-template') != null) {
el.inlineTemplate = true
}
}
function processAttrs (el) {
const list = el.attrsList
let i, l, name, rawName, value, modifiers, isProp
for (i = 0, l = list.length; i < l; i++) {
name = rawName = list[i].name
value = list[i].value
if (dirRE.test(name)) {
// mark element as dynamic
el.hasBindings = true
// modifiers
modifiers = parseModifiers(name)
if (modifiers) {
name = name.replace(modifierRE, '')
}
if (bindRE.test(name)) { // v-bind
name = name.replace(bindRE, '')
value = parseFilters(value)
isProp = false
if (modifiers) {
if (modifiers.prop) {
isProp = true
name = camelize(name)
if (name === 'innerHtml') name = 'innerHTML'
}
if (modifiers.camel) {
name = camelize(name)
}
if (modifiers.sync) {
addHandler(
el,
`update:${camelize(name)}`,
genAssignmentCode(value, `$event`)
)
}
}
if (isProp || (
!el.component && platformMustUseProp(el.tag, el.attrsMap.type, name)
)) {
addProp(el, name, value)
} else {
addAttr(el, name, value)
}
} else if (onRE.test(name)) { // v-on
name = name.replace(onRE, '')
addHandler(el, name, value, modifiers, false, warn)
} else { // normal directives
name = name.replace(dirRE, '')
// parse arg
const argMatch = name.match(argRE)
const arg = argMatch && argMatch[1]
if (arg) {
name = name.slice(0, -(arg.length + 1))
}
addDirective(el, name, rawName, value, arg, modifiers)
if (process.env.NODE_ENV !== 'production' && name === 'model') {
checkForAliasModel(el, value)
}
}
} else {
// literal attribute
if (process.env.NODE_ENV !== 'production') {
const expression = parseText(value, delimiters)
if (expression) {
warn(
`${name}="${value}": ` +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of <div id="{{ val }}">, use <div :id="val">.'
)
}
}
addAttr(el, name, JSON.stringify(value))
}
}
}
function checkInFor (el: ASTElement): boolean {
let parent = el
while (parent) {
if (parent.for !== undefined) {
return true
}
parent = parent.parent
}
return false
}
function parseModifiers (name: string): Object | void {
const match = name.match(modifierRE)
if (match) {
const ret = {}
match.forEach(m => { ret[m.slice(1)] = true })
return ret
}
}
function makeAttrsMap (attrs: Array<Object>): Object {
const map = {}
for (let i = 0, l = attrs.length; i < l; i++) {
if (
process.env.NODE_ENV !== 'production' &&
map[attrs[i].name] && !isIE && !isEdge
) {
warn('duplicate attribute: ' + attrs[i].name)
}
map[attrs[i].name] = attrs[i].value
}
return map
}
// for script (e.g. type="x/template") or style, do not decode content
function isTextTag (el): boolean {
return el.tag === 'script' || el.tag === 'style'
}
function isForbiddenTag (el): boolean {
return (
el.tag === 'style' ||
(el.tag === 'script' && (
!el.attrsMap.type ||
el.attrsMap.type === 'text/javascript'
))
)
}
const ieNSBug = /^xmlns:NS\d+/
const ieNSPrefix = /^NS\d+:/
/* istanbul ignore next */
function guardIESVGBug (attrs) {
const res = []
for (let i = 0; i < attrs.length; i++) {
const attr = attrs[i]
if (!ieNSBug.test(attr.name)) {
attr.name = attr.name.replace(ieNSPrefix, '')
res.push(attr)
}
}
return res
}
function checkForAliasModel (el, value) {
let _el = el
while (_el) {
if (_el.for && _el.alias === value) {
warn(
`<${el.tag} v-model="${value}">: ` +
`You are binding v-model directly to a v-for iteration alias. ` +
`This will not be able to modify the v-for source array because ` +
`writing to the alias is like modifying a function local variable. ` +
`Consider using an array of objects and use v-model on an object property instead.`
)
}
_el = _el.parent
}
}
| src/compiler/parser/index.js | 1 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.9984198808670044,
0.01557815633714199,
0.00016593874897807837,
0.00017067136650439352,
0.12285535037517548
] |
{
"id": 10,
"code_window": [
"}\n",
"\n",
"// #3663\n",
"// IE encodes newlines inside attribute values while other browsers don't\n",
"export const shouldDecodeNewlines = inBrowser ? shouldDecode('\\n', ' ') : false\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace"
],
"after_edit": [
"// #3663: IE encodes newlines inside attribute values while other browsers don't\n",
"export const shouldDecodeNewlines = inBrowser ? getShouldDecode(false) : false\n",
"// #6828: chrome encodes content in a[href]\n",
"export const shouldDecodeNewlinesForHref = inBrowser ? getShouldDecode(true) : false"
],
"file_path": "src/platforms/web/util/compat.js",
"type": "replace",
"edit_start_line_idx": 11
} | // register the grid component
Vue.component('demo-grid', {
template: '#grid-template',
replace: true,
props: {
data: Array,
columns: Array,
filterKey: String
},
data: function () {
var sortOrders = {}
this.columns.forEach(function (key) {
sortOrders[key] = 1
})
return {
sortKey: '',
sortOrders: sortOrders
}
},
computed: {
filteredData: function () {
var sortKey = this.sortKey
var filterKey = this.filterKey && this.filterKey.toLowerCase()
var order = this.sortOrders[sortKey] || 1
var data = this.data
if (filterKey) {
data = data.filter(function (row) {
return Object.keys(row).some(function (key) {
return String(row[key]).toLowerCase().indexOf(filterKey) > -1
})
})
}
if (sortKey) {
data = data.slice().sort(function (a, b) {
a = a[sortKey]
b = b[sortKey]
return (a === b ? 0 : a > b ? 1 : -1) * order
})
}
return data
}
},
filters: {
capitalize: function (str) {
return str.charAt(0).toUpperCase() + str.slice(1)
}
},
methods: {
sortBy: function (key) {
this.sortKey = key
this.sortOrders[key] = this.sortOrders[key] * -1
}
}
})
// bootstrap the demo
var demo = new Vue({
el: '#demo',
data: {
searchQuery: '',
gridColumns: ['name', 'power'],
gridData: [
{ name: 'Chuck Norris', power: Infinity },
{ name: 'Bruce Lee', power: 9000 },
{ name: 'Jackie Chan', power: 7000 },
{ name: 'Jet Li', power: 8000 }
]
}
})
| examples/grid/grid.js | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.0001731558731989935,
0.00016972101002465934,
0.00016728499031160027,
0.00016951592988334596,
0.000001836246156017296
] |
{
"id": 10,
"code_window": [
"}\n",
"\n",
"// #3663\n",
"// IE encodes newlines inside attribute values while other browsers don't\n",
"export const shouldDecodeNewlines = inBrowser ? shouldDecode('\\n', ' ') : false\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace"
],
"after_edit": [
"// #3663: IE encodes newlines inside attribute values while other browsers don't\n",
"export const shouldDecodeNewlines = inBrowser ? getShouldDecode(false) : false\n",
"// #6828: chrome encodes content in a[href]\n",
"export const shouldDecodeNewlinesForHref = inBrowser ? getShouldDecode(true) : false"
],
"file_path": "src/platforms/web/util/compat.js",
"type": "replace",
"edit_start_line_idx": 11
} | import Vue from 'vue'
describe('vdom patch: edge cases', () => {
// exposed by #3406
// When a static vnode is inside v-for, it's possible for the same vnode
// to be used in multiple places, and its element will be replaced. This
// causes patch errors when node ops depend on the vnode's element position.
it('should handle static vnodes by key', done => {
const vm = new Vue({
data: {
ok: true
},
template: `
<div>
<div v-for="i in 2">
<div v-if="ok">a</div><div>b</div><div v-if="!ok">c</div><div>d</div>
</div>
</div>
`
}).$mount()
expect(vm.$el.textContent).toBe('abdabd')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.textContent).toBe('bcdbcd')
}).then(done)
})
// #3533
// a static node (<br>) is reused in createElm, which changes its elm reference
// and is inserted into a different parent.
// later when patching the next element a DOM insertion uses it as the
// reference node, causing a parent mismatch.
it('should handle static node edge case when it\'s reused AND used as a reference node for insertion', done => {
const vm = new Vue({
data: {
ok: true
},
template: `
<div>
<button @click="ok = !ok">toggle</button>
<div class="b" v-if="ok">123</div>
<div class="c">
<br><p>{{ 1 }}</p>
</div>
<div class="d">
<label>{{ 2 }}</label>
</div>
</div>
`
}).$mount()
expect(vm.$el.querySelector('.c').textContent).toBe('1')
expect(vm.$el.querySelector('.d').textContent).toBe('2')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.querySelector('.c').textContent).toBe('1')
expect(vm.$el.querySelector('.d').textContent).toBe('2')
}).then(done)
})
it('should synchronize vm\' vnode', done => {
const comp = {
data: () => ({ swap: true }),
render (h) {
return this.swap
? h('a', 'atag')
: h('span', 'span')
}
}
const wrapper = {
render: h => h('comp'),
components: { comp }
}
const vm = new Vue({
render (h) {
const children = [
h('wrapper'),
h('div', 'row')
]
if (this.swap) {
children.reverse()
}
return h('div', children)
},
data: () => ({ swap: false }),
components: { wrapper }
}).$mount()
expect(vm.$el.innerHTML).toBe('<a>atag</a><div>row</div>')
const wrapperVm = vm.$children[0]
const compVm = wrapperVm.$children[0]
vm.swap = true
waitForUpdate(() => {
expect(compVm.$vnode.parent).toBe(wrapperVm.$vnode)
expect(vm.$el.innerHTML).toBe('<div>row</div><a>atag</a>')
vm.swap = false
})
.then(() => {
expect(compVm.$vnode.parent).toBe(wrapperVm.$vnode)
expect(vm.$el.innerHTML).toBe('<a>atag</a><div>row</div>')
compVm.swap = false
})
.then(() => {
expect(vm.$el.innerHTML).toBe('<span>span</span><div>row</div>')
expect(compVm.$vnode.parent).toBe(wrapperVm.$vnode)
vm.swap = true
})
.then(() => {
expect(vm.$el.innerHTML).toBe('<div>row</div><span>span</span>')
expect(compVm.$vnode.parent).toBe(wrapperVm.$vnode)
vm.swap = true
})
.then(done)
})
// #4530
it('should not reset value when patching between dynamic/static bindings', done => {
const vm = new Vue({
data: { ok: true },
template: `
<div>
<input type="button" v-if="ok" value="a">
<input type="button" :value="'b'">
</div>
`
}).$mount()
expect(vm.$el.children[0].value).toBe('a')
vm.ok = false
waitForUpdate(() => {
expect(vm.$el.children[0].value).toBe('b')
vm.ok = true
}).then(() => {
expect(vm.$el.children[0].value).toBe('a')
}).then(done)
})
// #6313
it('should not replace node when switching between text-like inputs', done => {
const vm = new Vue({
data: { show: false },
template: `
<div>
<input :type="show ? 'text' : 'password'">
</div>
`
}).$mount()
const node = vm.$el.children[0]
expect(vm.$el.children[0].type).toBe('password')
vm.$el.children[0].value = 'test'
vm.show = true
waitForUpdate(() => {
expect(vm.$el.children[0]).toBe(node)
expect(vm.$el.children[0].value).toBe('test')
expect(vm.$el.children[0].type).toBe('text')
vm.show = false
}).then(() => {
expect(vm.$el.children[0]).toBe(node)
expect(vm.$el.children[0].value).toBe('test')
expect(vm.$el.children[0].type).toBe('password')
}).then(done)
})
it('should properly patch nested HOC when root element is replaced', done => {
const vm = new Vue({
template: `<foo class="hello" ref="foo" />`,
components: {
foo: {
template: `<bar ref="bar" />`,
components: {
bar: {
template: `<div v-if="ok"></div><span v-else></span>`,
data () {
return { ok: true }
}
}
}
}
}
}).$mount()
expect(vm.$refs.foo.$refs.bar.$el.tagName).toBe('DIV')
expect(vm.$refs.foo.$refs.bar.$el.className).toBe(`hello`)
vm.$refs.foo.$refs.bar.ok = false
waitForUpdate(() => {
expect(vm.$refs.foo.$refs.bar.$el.tagName).toBe('SPAN')
expect(vm.$refs.foo.$refs.bar.$el.className).toBe(`hello`)
}).then(done)
})
// #6790
it('should not render undefined for empty nested arrays', () => {
const vm = new Vue({
template: `<div><template v-for="i in emptyArr"></template></div>`,
data: { emptyArr: [] }
}).$mount()
expect(vm.$el.textContent).toBe('')
})
// #6803
it('backwards compat with checkbox code generated before 2.4', () => {
const spy = jasmine.createSpy()
const vm = new Vue({
data: {
label: 'foobar',
name: 'foobar'
},
computed: {
value: {
get () {
return 1
},
set: spy
}
},
render (h) {
const _vm = this
return h('div', {},
[h('input', {
directives: [{
name: 'model',
rawName: 'v-model',
value: (_vm.value),
expression: 'value'
}],
attrs: {
'type': 'radio',
'name': _vm.name
},
domProps: {
'value': _vm.label,
'checked': _vm._q(_vm.value, _vm.label)
},
on: {
'__c': function ($event) {
_vm.value = _vm.label
}
}
})])
}
}).$mount()
document.body.appendChild(vm.$el)
vm.$el.children[0].click()
expect(spy).toHaveBeenCalled()
})
})
| test/unit/modules/vdom/patch/edge-cases.spec.js | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00017371599096804857,
0.00017005157133098692,
0.0001662640570430085,
0.00016977150517050177,
0.0000019685169263539137
] |
{
"id": 10,
"code_window": [
"}\n",
"\n",
"// #3663\n",
"// IE encodes newlines inside attribute values while other browsers don't\n",
"export const shouldDecodeNewlines = inBrowser ? shouldDecode('\\n', ' ') : false\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace"
],
"after_edit": [
"// #3663: IE encodes newlines inside attribute values while other browsers don't\n",
"export const shouldDecodeNewlines = inBrowser ? getShouldDecode(false) : false\n",
"// #6828: chrome encodes content in a[href]\n",
"export const shouldDecodeNewlinesForHref = inBrowser ? getShouldDecode(true) : false"
],
"file_path": "src/platforms/web/util/compat.js",
"type": "replace",
"edit_start_line_idx": 11
} | /*!
* Vue.js v2.5.2
* (c) 2014-2017 Evan You
* Released under the MIT License.
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.Vue=t()}(this,function(){"use strict";function e(e){return void 0===e||null===e}function t(e){return void 0!==e&&null!==e}function n(e){return!0===e}function r(e){return!1===e}function i(e){return"string"==typeof e||"number"==typeof e||"boolean"==typeof e}function o(e){return null!==e&&"object"==typeof e}function a(e){return"[object Object]"===Ai.call(e)}function s(e){return"[object RegExp]"===Ai.call(e)}function c(e){var t=parseFloat(String(e));return t>=0&&Math.floor(t)===t&&isFinite(e)}function u(e){return null==e?"":"object"==typeof e?JSON.stringify(e,null,2):String(e)}function l(e){var t=parseFloat(e);return isNaN(t)?e:t}function f(e,t){for(var n=Object.create(null),r=e.split(","),i=0;i<r.length;i++)n[r[i]]=!0;return t?function(e){return n[e.toLowerCase()]}:function(e){return n[e]}}function d(e,t){if(e.length){var n=e.indexOf(t);if(n>-1)return e.splice(n,1)}}function p(e,t){return Ti.call(e,t)}function v(e){var t=Object.create(null);return function(n){return t[n]||(t[n]=e(n))}}function h(e,t){function n(n){var r=arguments.length;return r?r>1?e.apply(t,arguments):e.call(t,n):e.call(t)}return n._length=e.length,n}function m(e,t){t=t||0;for(var n=e.length-t,r=new Array(n);n--;)r[n]=e[n+t];return r}function y(e,t){for(var n in t)e[n]=t[n];return e}function g(e){for(var t={},n=0;n<e.length;n++)e[n]&&y(t,e[n]);return t}function _(e,t,n){}function b(e,t){if(e===t)return!0;var n=o(e),r=o(t);if(!n||!r)return!n&&!r&&String(e)===String(t);try{var i=Array.isArray(e),a=Array.isArray(t);if(i&&a)return e.length===t.length&&e.every(function(e,n){return b(e,t[n])});if(i||a)return!1;var s=Object.keys(e),c=Object.keys(t);return s.length===c.length&&s.every(function(n){return b(e[n],t[n])})}catch(e){return!1}}function $(e,t){for(var n=0;n<e.length;n++)if(b(e[n],t))return n;return-1}function C(e){var t=!1;return function(){t||(t=!0,e.apply(this,arguments))}}function w(e){var t=(e+"").charCodeAt(0);return 36===t||95===t}function x(e,t,n,r){Object.defineProperty(e,t,{value:n,enumerable:!!r,writable:!0,configurable:!0})}function k(e){if(!Ui.test(e)){var t=e.split(".");return function(e){for(var n=0;n<t.length;n++){if(!e)return;e=e[t[n]]}return e}}}function A(e){return"function"==typeof e&&/native code/.test(e.toString())}function O(e){so.target&&co.push(so.target),so.target=e}function S(){so.target=co.pop()}function T(e){return new uo(void 0,void 0,void 0,String(e))}function E(e,t){var n=new uo(e.tag,e.data,e.children,e.text,e.elm,e.context,e.componentOptions,e.asyncFactory);return n.ns=e.ns,n.isStatic=e.isStatic,n.key=e.key,n.isComment=e.isComment,n.isCloned=!0,t&&e.children&&(n.children=j(e.children)),n}function j(e,t){for(var n=e.length,r=new Array(n),i=0;i<n;i++)r[i]=E(e[i],t);return r}function L(e,t,n){e.__proto__=t}function N(e,t,n){for(var r=0,i=n.length;r<i;r++){var o=n[r];x(e,o,t[o])}}function I(e,t){if(o(e)&&!(e instanceof uo)){var n;return p(e,"__ob__")&&e.__ob__ instanceof yo?n=e.__ob__:mo.shouldConvert&&!no()&&(Array.isArray(e)||a(e))&&Object.isExtensible(e)&&!e._isVue&&(n=new yo(e)),t&&n&&n.vmCount++,n}}function M(e,t,n,r,i){var o=new so,a=Object.getOwnPropertyDescriptor(e,t);if(!a||!1!==a.configurable){var s=a&&a.get,c=a&&a.set,u=!i&&I(n);Object.defineProperty(e,t,{enumerable:!0,configurable:!0,get:function(){var t=s?s.call(e):n;return so.target&&(o.depend(),u&&(u.dep.depend(),Array.isArray(t)&&R(t))),t},set:function(t){var r=s?s.call(e):n;t===r||t!==t&&r!==r||(c?c.call(e,t):n=t,u=!i&&I(t),o.notify())}})}}function P(e,t,n){if(Array.isArray(e)&&c(t))return e.length=Math.max(e.length,t),e.splice(t,1,n),n;if(p(e,t))return e[t]=n,n;var r=e.__ob__;return e._isVue||r&&r.vmCount?n:r?(M(r.value,t,n),r.dep.notify(),n):(e[t]=n,n)}function D(e,t){if(Array.isArray(e)&&c(t))e.splice(t,1);else{var n=e.__ob__;e._isVue||n&&n.vmCount||p(e,t)&&(delete e[t],n&&n.dep.notify())}}function R(e){for(var t=void 0,n=0,r=e.length;n<r;n++)(t=e[n])&&t.__ob__&&t.__ob__.dep.depend(),Array.isArray(t)&&R(t)}function F(e,t){if(!t)return e;for(var n,r,i,o=Object.keys(t),s=0;s<o.length;s++)r=e[n=o[s]],i=t[n],p(e,n)?a(r)&&a(i)&&F(r,i):P(e,n,i);return e}function H(e,t,n){return n?e||t?function(){var r="function"==typeof t?t.call(n):t,i="function"==typeof e?e.call(n):e;return r?F(r,i):i}:void 0:t?e?function(){return F("function"==typeof t?t.call(this):t,"function"==typeof e?e.call(this):e)}:t:e}function B(e,t){return t?e?e.concat(t):Array.isArray(t)?t:[t]:e}function U(e,t,n,r){var i=Object.create(e||null);return t?y(i,t):i}function V(e,t){var n=e.props;if(n){var r,i,o={};if(Array.isArray(n))for(r=n.length;r--;)"string"==typeof(i=n[r])&&(o[ji(i)]={type:null});else if(a(n))for(var s in n)i=n[s],o[ji(s)]=a(i)?i:{type:i};e.props=o}}function z(e,t){var n=e.inject,r=e.inject={};if(Array.isArray(n))for(var i=0;i<n.length;i++)r[n[i]]={from:n[i]};else if(a(n))for(var o in n){var s=n[o];r[o]=a(s)?y({from:o},s):{from:s}}}function K(e){var t=e.directives;if(t)for(var n in t){var r=t[n];"function"==typeof r&&(t[n]={bind:r,update:r})}}function J(e,t,n){function r(r){var i=go[r]||$o;c[r]=i(e[r],t[r],n,r)}"function"==typeof t&&(t=t.options),V(t,n),z(t,n),K(t);var i=t.extends;if(i&&(e=J(e,i,n)),t.mixins)for(var o=0,a=t.mixins.length;o<a;o++)e=J(e,t.mixins[o],n);var s,c={};for(s in e)r(s);for(s in t)p(e,s)||r(s);return c}function q(e,t,n,r){if("string"==typeof n){var i=e[t];if(p(i,n))return i[n];var o=ji(n);if(p(i,o))return i[o];var a=Li(o);if(p(i,a))return i[a];var s=i[n]||i[o]||i[a];return s}}function W(e,t,n,r){var i=t[e],o=!p(n,e),a=n[e];if(Y(Boolean,i.type)&&(o&&!p(i,"default")?a=!1:Y(String,i.type)||""!==a&&a!==Ii(e)||(a=!0)),void 0===a){a=G(r,i,e);var s=mo.shouldConvert;mo.shouldConvert=!0,I(a),mo.shouldConvert=s}return a}function G(e,t,n){if(p(t,"default")){var r=t.default;return e&&e.$options.propsData&&void 0===e.$options.propsData[n]&&void 0!==e._props[n]?e._props[n]:"function"==typeof r&&"Function"!==Z(t.type)?r.call(e):r}}function Z(e){var t=e&&e.toString().match(/^\s*function (\w+)/);return t?t[1]:""}function Y(e,t){if(!Array.isArray(t))return Z(t)===Z(e);for(var n=0,r=t.length;n<r;n++)if(Z(t[n])===Z(e))return!0;return!1}function Q(e,t,n){if(t)for(var r=t;r=r.$parent;){var i=r.$options.errorCaptured;if(i)for(var o=0;o<i.length;o++)try{if(!1===i[o].call(r,e,t,n))return}catch(e){X(e,r,"errorCaptured hook")}}X(e,t,n)}function X(e,t,n){if(Hi.errorHandler)try{return Hi.errorHandler.call(null,e,t,n)}catch(e){ee(e,null,"config.errorHandler")}ee(e,t,n)}function ee(e,t,n){if(!zi||"undefined"==typeof console)throw e;console.error(e)}function te(){wo=!1;var e=Co.slice(0);Co.length=0;for(var t=0;t<e.length;t++)e[t]()}function ne(e){return e._withTask||(e._withTask=function(){xo=!0;var t=e.apply(null,arguments);return xo=!1,t})}function re(e,t){var n;if(Co.push(function(){if(e)try{e.call(t)}catch(e){Q(e,t,"nextTick")}else n&&n(t)}),wo||(wo=!0,xo?bo():_o()),!e&&"undefined"!=typeof Promise)return new Promise(function(e){n=e})}function ie(e){function t(){var e=arguments,n=t.fns;if(!Array.isArray(n))return n.apply(null,arguments);for(var r=n.slice(),i=0;i<r.length;i++)r[i].apply(null,e)}return t.fns=e,t}function oe(t,n,r,i,o){var a,s,c,u;for(a in t)s=t[a],c=n[a],u=To(a),e(s)||(e(c)?(e(s.fns)&&(s=t[a]=ie(s)),r(u.name,s,u.once,u.capture,u.passive)):s!==c&&(c.fns=s,t[a]=c));for(a in n)e(t[a])&&i((u=To(a)).name,n[a],u.capture)}function ae(r,i,o){function a(){o.apply(this,arguments),d(s.fns,a)}var s,c=r[i];e(c)?s=ie([a]):t(c.fns)&&n(c.merged)?(s=c).fns.push(a):s=ie([c,a]),s.merged=!0,r[i]=s}function se(n,r,i){var o=r.options.props;if(!e(o)){var a={},s=n.attrs,c=n.props;if(t(s)||t(c))for(var u in o){var l=Ii(u);ce(a,c,u,l,!0)||ce(a,s,u,l,!1)}return a}}function ce(e,n,r,i,o){if(t(n)){if(p(n,r))return e[r]=n[r],o||delete n[r],!0;if(p(n,i))return e[r]=n[i],o||delete n[i],!0}return!1}function ue(e){for(var t=0;t<e.length;t++)if(Array.isArray(e[t]))return Array.prototype.concat.apply([],e);return e}function le(e){return i(e)?[T(e)]:Array.isArray(e)?de(e):void 0}function fe(e){return t(e)&&t(e.text)&&r(e.isComment)}function de(r,o){var a,s,c,u,l=[];for(a=0;a<r.length;a++)e(s=r[a])||"boolean"==typeof s||(u=l[c=l.length-1],Array.isArray(s)?s.length>0&&(fe((s=de(s,(o||"")+"_"+a))[0])&&fe(u)&&(l[c]=T(u.text+s[0].text),s.shift()),l.push.apply(l,s)):i(s)?fe(u)?l[c]=T(u.text+s):""!==s&&l.push(T(s)):fe(s)&&fe(u)?l[c]=T(u.text+s.text):(n(r._isVList)&&t(s.tag)&&e(s.key)&&t(o)&&(s.key="__vlist"+o+"_"+a+"__"),l.push(s)));return l}function pe(e,t){return(e.__esModule||io&&"Module"===e[Symbol.toStringTag])&&(e=e.default),o(e)?t.extend(e):e}function ve(e,t,n,r,i){var o=fo();return o.asyncFactory=e,o.asyncMeta={data:t,context:n,children:r,tag:i},o}function he(r,i,a){if(n(r.error)&&t(r.errorComp))return r.errorComp;if(t(r.resolved))return r.resolved;if(n(r.loading)&&t(r.loadingComp))return r.loadingComp;if(!t(r.contexts)){var s=r.contexts=[a],c=!0,u=function(){for(var e=0,t=s.length;e<t;e++)s[e].$forceUpdate()},l=C(function(e){r.resolved=pe(e,i),c||u()}),f=C(function(e){t(r.errorComp)&&(r.error=!0,u())}),d=r(l,f);return o(d)&&("function"==typeof d.then?e(r.resolved)&&d.then(l,f):t(d.component)&&"function"==typeof d.component.then&&(d.component.then(l,f),t(d.error)&&(r.errorComp=pe(d.error,i)),t(d.loading)&&(r.loadingComp=pe(d.loading,i),0===d.delay?r.loading=!0:setTimeout(function(){e(r.resolved)&&e(r.error)&&(r.loading=!0,u())},d.delay||200)),t(d.timeout)&&setTimeout(function(){e(r.resolved)&&f(null)},d.timeout))),c=!1,r.loading?r.loadingComp:r.resolved}r.contexts.push(a)}function me(e){return e.isComment&&e.asyncFactory}function ye(e){if(Array.isArray(e))for(var n=0;n<e.length;n++){var r=e[n];if(t(r)&&(t(r.componentOptions)||me(r)))return r}}function ge(e){e._events=Object.create(null),e._hasHookEvent=!1;var t=e.$options._parentListeners;t&&$e(e,t)}function _e(e,t,n){n?So.$once(e,t):So.$on(e,t)}function be(e,t){So.$off(e,t)}function $e(e,t,n){So=e,oe(t,n||{},_e,be,e)}function Ce(e,t){var n={};if(!e)return n;for(var r=[],i=0,o=e.length;i<o;i++){var a=e[i],s=a.data;if(s&&s.attrs&&s.attrs.slot&&delete s.attrs.slot,a.context!==t&&a.functionalContext!==t||!s||null==s.slot)r.push(a);else{var c=a.data.slot,u=n[c]||(n[c]=[]);"template"===a.tag?u.push.apply(u,a.children):u.push(a)}}return r.every(we)||(n.default=r),n}function we(e){return e.isComment||" "===e.text}function xe(e,t){t=t||{};for(var n=0;n<e.length;n++)Array.isArray(e[n])?xe(e[n],t):t[e[n].key]=e[n].fn;return t}function ke(e){var t=e.$options,n=t.parent;if(n&&!t.abstract){for(;n.$options.abstract&&n.$parent;)n=n.$parent;n.$children.push(e)}e.$parent=n,e.$root=n?n.$root:e,e.$children=[],e.$refs={},e._watcher=null,e._inactive=null,e._directInactive=!1,e._isMounted=!1,e._isDestroyed=!1,e._isBeingDestroyed=!1}function Ae(e,t,n){e.$el=t,e.$options.render||(e.$options.render=fo),je(e,"beforeMount");var r;return r=function(){e._update(e._render(),n)},e._watcher=new Ro(e,r,_),n=!1,null==e.$vnode&&(e._isMounted=!0,je(e,"mounted")),e}function Oe(e,t,n,r,i){var o=!!(i||e.$options._renderChildren||r.data.scopedSlots||e.$scopedSlots!==Bi);if(e.$options._parentVnode=r,e.$vnode=r,e._vnode&&(e._vnode.parent=r),e.$options._renderChildren=i,e.$attrs=r.data&&r.data.attrs||Bi,e.$listeners=n||Bi,t&&e.$options.props){mo.shouldConvert=!1;for(var a=e._props,s=e.$options._propKeys||[],c=0;c<s.length;c++){var u=s[c];a[u]=W(u,e.$options.props,t,e)}mo.shouldConvert=!0,e.$options.propsData=t}if(n){var l=e.$options._parentListeners;e.$options._parentListeners=n,$e(e,n,l)}o&&(e.$slots=Ce(i,r.context),e.$forceUpdate())}function Se(e){for(;e&&(e=e.$parent);)if(e._inactive)return!0;return!1}function Te(e,t){if(t){if(e._directInactive=!1,Se(e))return}else if(e._directInactive)return;if(e._inactive||null===e._inactive){e._inactive=!1;for(var n=0;n<e.$children.length;n++)Te(e.$children[n]);je(e,"activated")}}function Ee(e,t){if(!(t&&(e._directInactive=!0,Se(e))||e._inactive)){e._inactive=!0;for(var n=0;n<e.$children.length;n++)Ee(e.$children[n]);je(e,"deactivated")}}function je(e,t){var n=e.$options[t];if(n)for(var r=0,i=n.length;r<i;r++)try{n[r].call(e)}catch(n){Q(n,e,t+" hook")}e._hasHookEvent&&e.$emit("hook:"+t)}function Le(){Po=jo.length=Lo.length=0,No={},Io=Mo=!1}function Ne(){Mo=!0;var e,t;for(jo.sort(function(e,t){return e.id-t.id}),Po=0;Po<jo.length;Po++)t=(e=jo[Po]).id,No[t]=null,e.run();var n=Lo.slice(),r=jo.slice();Le(),Pe(n),Ie(r),ro&&Hi.devtools&&ro.emit("flush")}function Ie(e){for(var t=e.length;t--;){var n=e[t],r=n.vm;r._watcher===n&&r._isMounted&&je(r,"updated")}}function Me(e){e._inactive=!1,Lo.push(e)}function Pe(e){for(var t=0;t<e.length;t++)e[t]._inactive=!0,Te(e[t],!0)}function De(e){var t=e.id;if(null==No[t]){if(No[t]=!0,Mo){for(var n=jo.length-1;n>Po&&jo[n].id>e.id;)n--;jo.splice(n+1,0,e)}else jo.push(e);Io||(Io=!0,re(Ne))}}function Re(e){Fo.clear(),Fe(e,Fo)}function Fe(e,t){var n,r,i=Array.isArray(e);if((i||o(e))&&Object.isExtensible(e)){if(e.__ob__){var a=e.__ob__.dep.id;if(t.has(a))return;t.add(a)}if(i)for(n=e.length;n--;)Fe(e[n],t);else for(n=(r=Object.keys(e)).length;n--;)Fe(e[r[n]],t)}}function He(e,t,n){Ho.get=function(){return this[t][n]},Ho.set=function(e){this[t][n]=e},Object.defineProperty(e,n,Ho)}function Be(e){e._watchers=[];var t=e.$options;t.props&&Ue(e,t.props),t.methods&&We(e,t.methods),t.data?Ve(e):I(e._data={},!0),t.computed&&Ke(e,t.computed),t.watch&&t.watch!==Yi&&Ge(e,t.watch)}function Ue(e,t){var n=e.$options.propsData||{},r=e._props={},i=e.$options._propKeys=[],o=!e.$parent;mo.shouldConvert=o;for(var a in t)!function(o){i.push(o);var a=W(o,t,n,e);M(r,o,a),o in e||He(e,"_props",o)}(a);mo.shouldConvert=!0}function Ve(e){var t=e.$options.data;a(t=e._data="function"==typeof t?ze(t,e):t||{})||(t={});for(var n=Object.keys(t),r=e.$options.props,i=n.length;i--;){var o=n[i];r&&p(r,o)||w(o)||He(e,"_data",o)}I(t,!0)}function ze(e,t){try{return e.call(t,t)}catch(e){return Q(e,t,"data()"),{}}}function Ke(e,t){var n=e._computedWatchers=Object.create(null),r=no();for(var i in t){var o=t[i],a="function"==typeof o?o:o.get;r||(n[i]=new Ro(e,a||_,_,Bo)),i in e||Je(e,i,o)}}function Je(e,t,n){var r=!no();"function"==typeof n?(Ho.get=r?qe(t):n,Ho.set=_):(Ho.get=n.get?r&&!1!==n.cache?qe(t):n.get:_,Ho.set=n.set?n.set:_),Object.defineProperty(e,t,Ho)}function qe(e){return function(){var t=this._computedWatchers&&this._computedWatchers[e];if(t)return t.dirty&&t.evaluate(),so.target&&t.depend(),t.value}}function We(e,t){for(var n in t)e[n]=null==t[n]?_:h(t[n],e)}function Ge(e,t){for(var n in t){var r=t[n];if(Array.isArray(r))for(var i=0;i<r.length;i++)Ze(e,n,r[i]);else Ze(e,n,r)}}function Ze(e,t,n,r){return a(n)&&(r=n,n=n.handler),"string"==typeof n&&(n=e[n]),e.$watch(t,n,r)}function Ye(e){var t=e.$options.provide;t&&(e._provided="function"==typeof t?t.call(e):t)}function Qe(e){var t=Xe(e.$options.inject,e);t&&(mo.shouldConvert=!1,Object.keys(t).forEach(function(n){M(e,n,t[n])}),mo.shouldConvert=!0)}function Xe(e,t){if(e){for(var n=Object.create(null),r=io?Reflect.ownKeys(e).filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}):Object.keys(e),i=0;i<r.length;i++){for(var o=r[i],a=e[o].from,s=t;s;){if(s._provided&&a in s._provided){n[o]=s._provided[a];break}s=s.$parent}if(!s&&"default"in e[o]){var c=e[o].default;n[o]="function"==typeof c?c.call(t):c}}return n}}function et(e,n){var r,i,a,s,c;if(Array.isArray(e)||"string"==typeof e)for(r=new Array(e.length),i=0,a=e.length;i<a;i++)r[i]=n(e[i],i);else if("number"==typeof e)for(r=new Array(e),i=0;i<e;i++)r[i]=n(i+1,i);else if(o(e))for(s=Object.keys(e),r=new Array(s.length),i=0,a=s.length;i<a;i++)c=s[i],r[i]=n(e[c],c,i);return t(r)&&(r._isVList=!0),r}function tt(e,t,n,r){var i=this.$scopedSlots[e];if(i)return n=n||{},r&&(n=y(y({},r),n)),i(n)||t;var o=this.$slots[e];return o||t}function nt(e){return q(this.$options,"filters",e,!0)||Pi}function rt(e,t,n,r){var i=Hi.keyCodes[t]||n;return i?Array.isArray(i)?-1===i.indexOf(e):i!==e:r?Ii(r)!==t:void 0}function it(e,t,n,r,i){if(n)if(o(n)){Array.isArray(n)&&(n=g(n));var a;for(var s in n)!function(o){if("class"===o||"style"===o||Si(o))a=e;else{var s=e.attrs&&e.attrs.type;a=r||Hi.mustUseProp(t,s,o)?e.domProps||(e.domProps={}):e.attrs||(e.attrs={})}o in a||(a[o]=n[o],i&&((e.on||(e.on={}))["update:"+o]=function(e){n[o]=e}))}(s)}else;return e}function ot(e,t){var n=this.$options.staticRenderFns,r=n.cached||(n.cached=[]),i=r[e];return i&&!t?Array.isArray(i)?j(i):E(i):(i=r[e]=n[e].call(this._renderProxy,null,this),st(i,"__static__"+e,!1),i)}function at(e,t,n){return st(e,"__once__"+t+(n?"_"+n:""),!0),e}function st(e,t,n){if(Array.isArray(e))for(var r=0;r<e.length;r++)e[r]&&"string"!=typeof e[r]&&ct(e[r],t+"_"+r,n);else ct(e,t,n)}function ct(e,t,n){e.isStatic=!0,e.key=t,e.isOnce=n}function ut(e,t){if(t)if(a(t)){var n=e.on=e.on?y({},e.on):{};for(var r in t){var i=n[r],o=t[r];n[r]=i?[].concat(i,o):o}}else;return e}function lt(e){e._o=at,e._n=l,e._s=u,e._l=et,e._t=tt,e._q=b,e._i=$,e._m=ot,e._f=nt,e._k=rt,e._b=it,e._v=T,e._e=fo,e._u=xe,e._g=ut}function ft(e,t,r,i,o){var a=o.options;this.data=e,this.props=t,this.children=r,this.parent=i,this.listeners=e.on||Bi,this.injections=Xe(a.inject,i),this.slots=function(){return Ce(r,i)};var s=Object.create(i),c=n(a._compiled),u=!c;c&&(this.$options=a,this.$slots=this.slots(),this.$scopedSlots=e.scopedSlots||Bi),a._scopeId?this._c=function(e,t,n,r){var o=_t(s,e,t,n,r,u);return o&&(o.functionalScopeId=a._scopeId,o.functionalContext=i),o}:this._c=function(e,t,n,r){return _t(s,e,t,n,r,u)}}function dt(e,n,r,i,o){var a=e.options,s={},c=a.props;if(t(c))for(var u in c)s[u]=W(u,c,n||Bi);else t(r.attrs)&&pt(s,r.attrs),t(r.props)&&pt(s,r.props);var l=new ft(r,s,o,i,e),f=a.render.call(null,l._c,l);return f instanceof uo&&(f.functionalContext=i,f.functionalOptions=a,r.slot&&((f.data||(f.data={})).slot=r.slot)),f}function pt(e,t){for(var n in t)e[ji(n)]=t[n]}function vt(r,i,a,s,c){if(!e(r)){var u=a.$options._base;if(o(r)&&(r=u.extend(r)),"function"==typeof r){var l;if(e(r.cid)&&(l=r,void 0===(r=he(l,u,a))))return ve(l,i,a,s,c);i=i||{},xt(r),t(i.model)&>(r.options,i);var f=se(i,r,c);if(n(r.options.functional))return dt(r,f,i,a,s);var d=i.on;if(i.on=i.nativeOn,n(r.options.abstract)){var p=i.slot;i={},p&&(i.slot=p)}mt(i);var v=r.options.name||c;return new uo("vue-component-"+r.cid+(v?"-"+v:""),i,void 0,void 0,void 0,a,{Ctor:r,propsData:f,listeners:d,tag:c,children:s},l)}}}function ht(e,n,r,i){var o=e.componentOptions,a={_isComponent:!0,parent:n,propsData:o.propsData,_componentTag:o.tag,_parentVnode:e,_parentListeners:o.listeners,_renderChildren:o.children,_parentElm:r||null,_refElm:i||null},s=e.data.inlineTemplate;return t(s)&&(a.render=s.render,a.staticRenderFns=s.staticRenderFns),new o.Ctor(a)}function mt(e){e.hook||(e.hook={});for(var t=0;t<Vo.length;t++){var n=Vo[t],r=e.hook[n],i=Uo[n];e.hook[n]=r?yt(i,r):i}}function yt(e,t){return function(n,r,i,o){e(n,r,i,o),t(n,r,i,o)}}function gt(e,n){var r=e.model&&e.model.prop||"value",i=e.model&&e.model.event||"input";(n.props||(n.props={}))[r]=n.model.value;var o=n.on||(n.on={});t(o[i])?o[i]=[n.model.callback].concat(o[i]):o[i]=n.model.callback}function _t(e,t,r,o,a,s){return(Array.isArray(r)||i(r))&&(a=o,o=r,r=void 0),n(s)&&(a=Ko),bt(e,t,r,o,a)}function bt(e,n,r,i,o){if(t(r)&&t(r.__ob__))return fo();if(t(r)&&t(r.is)&&(n=r.is),!n)return fo();Array.isArray(i)&&"function"==typeof i[0]&&((r=r||{}).scopedSlots={default:i[0]},i.length=0),o===Ko?i=le(i):o===zo&&(i=ue(i));var a,s;if("string"==typeof n){var c;s=e.$vnode&&e.$vnode.ns||Hi.getTagNamespace(n),a=Hi.isReservedTag(n)?new uo(Hi.parsePlatformTagName(n),r,i,void 0,void 0,e):t(c=q(e.$options,"components",n))?vt(c,r,e,i,n):new uo(n,r,i,void 0,void 0,e)}else a=vt(n,r,e,i);return t(a)?(s&&$t(a,s),a):fo()}function $t(r,i,o){if(r.ns=i,"foreignObject"===r.tag&&(i=void 0,o=!0),t(r.children))for(var a=0,s=r.children.length;a<s;a++){var c=r.children[a];t(c.tag)&&(e(c.ns)||n(o))&&$t(c,i,o)}}function Ct(e){e._vnode=null;var t=e.$options,n=e.$vnode=t._parentVnode,r=n&&n.context;e.$slots=Ce(t._renderChildren,r),e.$scopedSlots=Bi,e._c=function(t,n,r,i){return _t(e,t,n,r,i,!1)},e.$createElement=function(t,n,r,i){return _t(e,t,n,r,i,!0)};var i=n&&n.data;M(e,"$attrs",i&&i.attrs||Bi,null,!0),M(e,"$listeners",t._parentListeners||Bi,null,!0)}function wt(e,t){var n=e.$options=Object.create(e.constructor.options);n.parent=t.parent,n.propsData=t.propsData,n._parentVnode=t._parentVnode,n._parentListeners=t._parentListeners,n._renderChildren=t._renderChildren,n._componentTag=t._componentTag,n._parentElm=t._parentElm,n._refElm=t._refElm,t.render&&(n.render=t.render,n.staticRenderFns=t.staticRenderFns)}function xt(e){var t=e.options;if(e.super){var n=xt(e.super);if(n!==e.superOptions){e.superOptions=n;var r=kt(e);r&&y(e.extendOptions,r),(t=e.options=J(n,e.extendOptions)).name&&(t.components[t.name]=e)}}return t}function kt(e){var t,n=e.options,r=e.extendOptions,i=e.sealedOptions;for(var o in n)n[o]!==i[o]&&(t||(t={}),t[o]=At(n[o],r[o],i[o]));return t}function At(e,t,n){if(Array.isArray(e)){var r=[];n=Array.isArray(n)?n:[n],t=Array.isArray(t)?t:[t];for(var i=0;i<e.length;i++)(t.indexOf(e[i])>=0||n.indexOf(e[i])<0)&&r.push(e[i]);return r}return e}function Ot(e){this._init(e)}function St(e){e.use=function(e){var t=this._installedPlugins||(this._installedPlugins=[]);if(t.indexOf(e)>-1)return this;var n=m(arguments,1);return n.unshift(this),"function"==typeof e.install?e.install.apply(e,n):"function"==typeof e&&e.apply(null,n),t.push(e),this}}function Tt(e){e.mixin=function(e){return this.options=J(this.options,e),this}}function Et(e){e.cid=0;var t=1;e.extend=function(e){e=e||{};var n=this,r=n.cid,i=e._Ctor||(e._Ctor={});if(i[r])return i[r];var o=e.name||n.options.name,a=function(e){this._init(e)};return a.prototype=Object.create(n.prototype),a.prototype.constructor=a,a.cid=t++,a.options=J(n.options,e),a.super=n,a.options.props&&jt(a),a.options.computed&&Lt(a),a.extend=n.extend,a.mixin=n.mixin,a.use=n.use,Ri.forEach(function(e){a[e]=n[e]}),o&&(a.options.components[o]=a),a.superOptions=n.options,a.extendOptions=e,a.sealedOptions=y({},a.options),i[r]=a,a}}function jt(e){var t=e.options.props;for(var n in t)He(e.prototype,"_props",n)}function Lt(e){var t=e.options.computed;for(var n in t)Je(e.prototype,n,t[n])}function Nt(e){Ri.forEach(function(t){e[t]=function(e,n){return n?("component"===t&&a(n)&&(n.name=n.name||e,n=this.options._base.extend(n)),"directive"===t&&"function"==typeof n&&(n={bind:n,update:n}),this.options[t+"s"][e]=n,n):this.options[t+"s"][e]}})}function It(e){return e&&(e.Ctor.options.name||e.tag)}function Mt(e,t){return Array.isArray(e)?e.indexOf(t)>-1:"string"==typeof e?e.split(",").indexOf(t)>-1:!!s(e)&&e.test(t)}function Pt(e,t){var n=e.cache,r=e.keys,i=e._vnode;for(var o in n){var a=n[o];if(a){var s=It(a.componentOptions);s&&!t(s)&&Dt(n,o,r,i)}}}function Dt(e,t,n,r){var i=e[t];i&&i!==r&&i.componentInstance.$destroy(),e[t]=null,d(n,t)}function Rt(e){for(var n=e.data,r=e,i=e;t(i.componentInstance);)(i=i.componentInstance._vnode).data&&(n=Ft(i.data,n));for(;t(r=r.parent);)r.data&&(n=Ft(n,r.data));return Ht(n.staticClass,n.class)}function Ft(e,n){return{staticClass:Bt(e.staticClass,n.staticClass),class:t(e.class)?[e.class,n.class]:n.class}}function Ht(e,n){return t(e)||t(n)?Bt(e,Ut(n)):""}function Bt(e,t){return e?t?e+" "+t:e:t||""}function Ut(e){return Array.isArray(e)?Vt(e):o(e)?zt(e):"string"==typeof e?e:""}function Vt(e){for(var n,r="",i=0,o=e.length;i<o;i++)t(n=Ut(e[i]))&&""!==n&&(r&&(r+=" "),r+=n);return r}function zt(e){var t="";for(var n in e)e[n]&&(t&&(t+=" "),t+=n);return t}function Kt(e){return va(e)?"svg":"math"===e?"math":void 0}function Jt(e){if("string"==typeof e){var t=document.querySelector(e);return t||document.createElement("div")}return e}function qt(e,t){var n=e.data.ref;if(n){var r=e.context,i=e.componentInstance||e.elm,o=r.$refs;t?Array.isArray(o[n])?d(o[n],i):o[n]===i&&(o[n]=void 0):e.data.refInFor?Array.isArray(o[n])?o[n].indexOf(i)<0&&o[n].push(i):o[n]=[i]:o[n]=i}}function Wt(r,i){return r.key===i.key&&(r.tag===i.tag&&r.isComment===i.isComment&&t(r.data)===t(i.data)&&Gt(r,i)||n(r.isAsyncPlaceholder)&&r.asyncFactory===i.asyncFactory&&e(i.asyncFactory.error))}function Gt(e,n){if("input"!==e.tag)return!0;var r,i=t(r=e.data)&&t(r=r.attrs)&&r.type,o=t(r=n.data)&&t(r=r.attrs)&&r.type;return i===o||ya(i)&&ya(o)}function Zt(e,n,r){var i,o,a={};for(i=n;i<=r;++i)t(o=e[i].key)&&(a[o]=i);return a}function Yt(e,t){(e.data.directives||t.data.directives)&&Qt(e,t)}function Qt(e,t){var n,r,i,o=e===ba,a=t===ba,s=Xt(e.data.directives,e.context),c=Xt(t.data.directives,t.context),u=[],l=[];for(n in c)r=s[n],i=c[n],r?(i.oldValue=r.value,tn(i,"update",t,e),i.def&&i.def.componentUpdated&&l.push(i)):(tn(i,"bind",t,e),i.def&&i.def.inserted&&u.push(i));if(u.length){var f=function(){for(var n=0;n<u.length;n++)tn(u[n],"inserted",t,e)};o?ae(t.data.hook||(t.data.hook={}),"insert",f):f()}if(l.length&&ae(t.data.hook||(t.data.hook={}),"postpatch",function(){for(var n=0;n<l.length;n++)tn(l[n],"componentUpdated",t,e)}),!o)for(n in s)c[n]||tn(s[n],"unbind",e,e,a)}function Xt(e,t){var n=Object.create(null);if(!e)return n;var r,i;for(r=0;r<e.length;r++)(i=e[r]).modifiers||(i.modifiers=wa),n[en(i)]=i,i.def=q(t.$options,"directives",i.name,!0);return n}function en(e){return e.rawName||e.name+"."+Object.keys(e.modifiers||{}).join(".")}function tn(e,t,n,r,i){var o=e.def&&e.def[t];if(o)try{o(n.elm,e,n,r,i)}catch(r){Q(r,n.context,"directive "+e.name+" "+t+" hook")}}function nn(n,r){var i=r.componentOptions;if(!(t(i)&&!1===i.Ctor.options.inheritAttrs||e(n.data.attrs)&&e(r.data.attrs))){var o,a,s=r.elm,c=n.data.attrs||{},u=r.data.attrs||{};t(u.__ob__)&&(u=r.data.attrs=y({},u));for(o in u)a=u[o],c[o]!==a&&rn(s,o,a);(qi||Wi)&&u.value!==c.value&&rn(s,"value",u.value);for(o in c)e(u[o])&&(ua(o)?s.removeAttributeNS(ca,la(o)):aa(o)||s.removeAttribute(o))}}function rn(e,t,n){sa(t)?fa(n)?e.removeAttribute(t):(n="allowfullscreen"===t&&"EMBED"===e.tagName?"true":t,e.setAttribute(t,n)):aa(t)?e.setAttribute(t,fa(n)||"false"===n?"false":"true"):ua(t)?fa(n)?e.removeAttributeNS(ca,la(t)):e.setAttributeNS(ca,t,n):fa(n)?e.removeAttribute(t):e.setAttribute(t,n)}function on(n,r){var i=r.elm,o=r.data,a=n.data;if(!(e(o.staticClass)&&e(o.class)&&(e(a)||e(a.staticClass)&&e(a.class)))){var s=Rt(r),c=i._transitionClasses;t(c)&&(s=Bt(s,Ut(c))),s!==i._prevClass&&(i.setAttribute("class",s),i._prevClass=s)}}function an(e){function t(){(a||(a=[])).push(e.slice(v,i).trim()),v=i+1}var n,r,i,o,a,s=!1,c=!1,u=!1,l=!1,f=0,d=0,p=0,v=0;for(i=0;i<e.length;i++)if(r=n,n=e.charCodeAt(i),s)39===n&&92!==r&&(s=!1);else if(c)34===n&&92!==r&&(c=!1);else if(u)96===n&&92!==r&&(u=!1);else if(l)47===n&&92!==r&&(l=!1);else if(124!==n||124===e.charCodeAt(i+1)||124===e.charCodeAt(i-1)||f||d||p){switch(n){case 34:c=!0;break;case 39:s=!0;break;case 96:u=!0;break;case 40:p++;break;case 41:p--;break;case 91:d++;break;case 93:d--;break;case 123:f++;break;case 125:f--}if(47===n){for(var h=i-1,m=void 0;h>=0&&" "===(m=e.charAt(h));h--);m&&Oa.test(m)||(l=!0)}}else void 0===o?(v=i+1,o=e.slice(0,i).trim()):t();if(void 0===o?o=e.slice(0,i).trim():0!==v&&t(),a)for(i=0;i<a.length;i++)o=sn(o,a[i]);return o}function sn(e,t){var n=t.indexOf("(");return n<0?'_f("'+t+'")('+e+")":'_f("'+t.slice(0,n)+'")('+e+","+t.slice(n+1)}function cn(e){console.error("[Vue compiler]: "+e)}function un(e,t){return e?e.map(function(e){return e[t]}).filter(function(e){return e}):[]}function ln(e,t,n){(e.props||(e.props=[])).push({name:t,value:n})}function fn(e,t,n){(e.attrs||(e.attrs=[])).push({name:t,value:n})}function dn(e,t,n,r,i,o){(e.directives||(e.directives=[])).push({name:t,rawName:n,value:r,arg:i,modifiers:o})}function pn(e,t,n,r,i,o){r&&r.capture&&(delete r.capture,t="!"+t),r&&r.once&&(delete r.once,t="~"+t),r&&r.passive&&(delete r.passive,t="&"+t);var a;r&&r.native?(delete r.native,a=e.nativeEvents||(e.nativeEvents={})):a=e.events||(e.events={});var s={value:n,modifiers:r},c=a[t];Array.isArray(c)?i?c.unshift(s):c.push(s):a[t]=c?i?[s,c]:[c,s]:s}function vn(e,t,n){var r=hn(e,":"+t)||hn(e,"v-bind:"+t);if(null!=r)return an(r);if(!1!==n){var i=hn(e,t);if(null!=i)return JSON.stringify(i)}}function hn(e,t,n){var r;if(null!=(r=e.attrsMap[t]))for(var i=e.attrsList,o=0,a=i.length;o<a;o++)if(i[o].name===t){i.splice(o,1);break}return n&&delete e.attrsMap[t],r}function mn(e,t,n){var r=n||{},i=r.number,o="$$v";r.trim&&(o="(typeof $$v === 'string'? $$v.trim(): $$v)"),i&&(o="_n("+o+")");var a=yn(t,o);e.model={value:"("+t+")",expression:'"'+t+'"',callback:"function ($$v) {"+a+"}"}}function yn(e,t){var n=gn(e);return null===n.key?e+"="+t:"$set("+n.exp+", "+n.key+", "+t+")"}function gn(e){if(Go=e.length,e.indexOf("[")<0||e.lastIndexOf("]")<Go-1)return(Qo=e.lastIndexOf("."))>-1?{exp:e.slice(0,Qo),key:'"'+e.slice(Qo+1)+'"'}:{exp:e,key:null};for(Zo=e,Qo=Xo=ea=0;!bn();)$n(Yo=_n())?wn(Yo):91===Yo&&Cn(Yo);return{exp:e.slice(0,Xo),key:e.slice(Xo+1,ea)}}function _n(){return Zo.charCodeAt(++Qo)}function bn(){return Qo>=Go}function $n(e){return 34===e||39===e}function Cn(e){var t=1;for(Xo=Qo;!bn();)if(e=_n(),$n(e))wn(e);else if(91===e&&t++,93===e&&t--,0===t){ea=Qo;break}}function wn(e){for(var t=e;!bn()&&(e=_n())!==t;);}function xn(e,t,n){var r=n&&n.number,i=vn(e,"value")||"null",o=vn(e,"true-value")||"true",a=vn(e,"false-value")||"false";ln(e,"checked","Array.isArray("+t+")?_i("+t+","+i+")>-1"+("true"===o?":("+t+")":":_q("+t+","+o+")")),pn(e,"change","var $$a="+t+",$$el=$event.target,$$c=$$el.checked?("+o+"):("+a+");if(Array.isArray($$a)){var $$v="+(r?"_n("+i+")":i)+",$$i=_i($$a,$$v);if($$el.checked){$$i<0&&("+t+"=$$a.concat([$$v]))}else{$$i>-1&&("+t+"=$$a.slice(0,$$i).concat($$a.slice($$i+1)))}}else{"+yn(t,"$$c")+"}",null,!0)}function kn(e,t,n){var r=n&&n.number,i=vn(e,"value")||"null";ln(e,"checked","_q("+t+","+(i=r?"_n("+i+")":i)+")"),pn(e,"change",yn(t,i),null,!0)}function An(e,t,n){var r="var $$selectedVal = "+('Array.prototype.filter.call($event.target.options,function(o){return o.selected}).map(function(o){var val = "_value" in o ? o._value : o.value;return '+(n&&n.number?"_n(val)":"val")+"})")+";";pn(e,"change",r=r+" "+yn(t,"$event.target.multiple ? $$selectedVal : $$selectedVal[0]"),null,!0)}function On(e,t,n){var r=e.attrsMap.type,i=n||{},o=i.lazy,a=i.number,s=i.trim,c=!o&&"range"!==r,u=o?"change":"range"===r?Sa:"input",l="$event.target.value";s&&(l="$event.target.value.trim()"),a&&(l="_n("+l+")");var f=yn(t,l);c&&(f="if($event.target.composing)return;"+f),ln(e,"value","("+t+")"),pn(e,u,f,null,!0),(s||a)&&pn(e,"blur","$forceUpdate()")}function Sn(e){if(t(e[Sa])){var n=Ji?"change":"input";e[n]=[].concat(e[Sa],e[n]||[]),delete e[Sa]}t(e[Ta])&&(e.change=[].concat(e[Ta],e.change||[]),delete e[Ta])}function Tn(e,t,n){var r=ta;return function i(){null!==e.apply(null,arguments)&&jn(t,i,n,r)}}function En(e,t,n,r,i){t=ne(t),n&&(t=Tn(t,e,r)),ta.addEventListener(e,t,Qi?{capture:r,passive:i}:r)}function jn(e,t,n,r){(r||ta).removeEventListener(e,t._withTask||t,n)}function Ln(t,n){if(!e(t.data.on)||!e(n.data.on)){var r=n.data.on||{},i=t.data.on||{};ta=n.elm,Sn(r),oe(r,i,En,jn,n.context)}}function Nn(n,r){if(!e(n.data.domProps)||!e(r.data.domProps)){var i,o,a=r.elm,s=n.data.domProps||{},c=r.data.domProps||{};t(c.__ob__)&&(c=r.data.domProps=y({},c));for(i in s)e(c[i])&&(a[i]="");for(i in c){if(o=c[i],"textContent"===i||"innerHTML"===i){if(r.children&&(r.children.length=0),o===s[i])continue;1===a.childNodes.length&&a.removeChild(a.childNodes[0])}if("value"===i){a._value=o;var u=e(o)?"":String(o);In(a,u)&&(a.value=u)}else a[i]=o}}}function In(e,t){return!e.composing&&("OPTION"===e.tagName||Mn(e,t)||Pn(e,t))}function Mn(e,t){var n=!0;try{n=document.activeElement!==e}catch(e){}return n&&e.value!==t}function Pn(e,n){var r=e.value,i=e._vModifiers;return t(i)&&i.number?l(r)!==l(n):t(i)&&i.trim?r.trim()!==n.trim():r!==n}function Dn(e){var t=Rn(e.style);return e.staticStyle?y(e.staticStyle,t):t}function Rn(e){return Array.isArray(e)?g(e):"string"==typeof e?La(e):e}function Fn(e,t){var n,r={};if(t)for(var i=e;i.componentInstance;)(i=i.componentInstance._vnode).data&&(n=Dn(i.data))&&y(r,n);(n=Dn(e.data))&&y(r,n);for(var o=e;o=o.parent;)o.data&&(n=Dn(o.data))&&y(r,n);return r}function Hn(n,r){var i=r.data,o=n.data;if(!(e(i.staticStyle)&&e(i.style)&&e(o.staticStyle)&&e(o.style))){var a,s,c=r.elm,u=o.staticStyle,l=o.normalizedStyle||o.style||{},f=u||l,d=Rn(r.data.style)||{};r.data.normalizedStyle=t(d.__ob__)?y({},d):d;var p=Fn(r,!0);for(s in f)e(p[s])&&Ma(c,s,"");for(s in p)(a=p[s])!==f[s]&&Ma(c,s,null==a?"":a)}}function Bn(e,t){if(t&&(t=t.trim()))if(e.classList)t.indexOf(" ")>-1?t.split(/\s+/).forEach(function(t){return e.classList.add(t)}):e.classList.add(t);else{var n=" "+(e.getAttribute("class")||"")+" ";n.indexOf(" "+t+" ")<0&&e.setAttribute("class",(n+t).trim())}}function Un(e,t){if(t&&(t=t.trim()))if(e.classList)t.indexOf(" ")>-1?t.split(/\s+/).forEach(function(t){return e.classList.remove(t)}):e.classList.remove(t),e.classList.length||e.removeAttribute("class");else{for(var n=" "+(e.getAttribute("class")||"")+" ",r=" "+t+" ";n.indexOf(r)>=0;)n=n.replace(r," ");(n=n.trim())?e.setAttribute("class",n):e.removeAttribute("class")}}function Vn(e){if(e){if("object"==typeof e){var t={};return!1!==e.css&&y(t,Fa(e.name||"v")),y(t,e),t}return"string"==typeof e?Fa(e):void 0}}function zn(e){qa(function(){qa(e)})}function Kn(e,t){var n=e._transitionClasses||(e._transitionClasses=[]);n.indexOf(t)<0&&(n.push(t),Bn(e,t))}function Jn(e,t){e._transitionClasses&&d(e._transitionClasses,t),Un(e,t)}function qn(e,t,n){var r=Wn(e,t),i=r.type,o=r.timeout,a=r.propCount;if(!i)return n();var s=i===Ba?za:Ja,c=0,u=function(){e.removeEventListener(s,l),n()},l=function(t){t.target===e&&++c>=a&&u()};setTimeout(function(){c<a&&u()},o+1),e.addEventListener(s,l)}function Wn(e,t){var n,r=window.getComputedStyle(e),i=r[Va+"Delay"].split(", "),o=r[Va+"Duration"].split(", "),a=Gn(i,o),s=r[Ka+"Delay"].split(", "),c=r[Ka+"Duration"].split(", "),u=Gn(s,c),l=0,f=0;return t===Ba?a>0&&(n=Ba,l=a,f=o.length):t===Ua?u>0&&(n=Ua,l=u,f=c.length):f=(n=(l=Math.max(a,u))>0?a>u?Ba:Ua:null)?n===Ba?o.length:c.length:0,{type:n,timeout:l,propCount:f,hasTransform:n===Ba&&Wa.test(r[Va+"Property"])}}function Gn(e,t){for(;e.length<t.length;)e=e.concat(e);return Math.max.apply(null,t.map(function(t,n){return Zn(t)+Zn(e[n])}))}function Zn(e){return 1e3*Number(e.slice(0,-1))}function Yn(n,r){var i=n.elm;t(i._leaveCb)&&(i._leaveCb.cancelled=!0,i._leaveCb());var a=Vn(n.data.transition);if(!e(a)&&!t(i._enterCb)&&1===i.nodeType){for(var s=a.css,c=a.type,u=a.enterClass,f=a.enterToClass,d=a.enterActiveClass,p=a.appearClass,v=a.appearToClass,h=a.appearActiveClass,m=a.beforeEnter,y=a.enter,g=a.afterEnter,_=a.enterCancelled,b=a.beforeAppear,$=a.appear,w=a.afterAppear,x=a.appearCancelled,k=a.duration,A=Eo,O=Eo.$vnode;O&&O.parent;)A=(O=O.parent).context;var S=!A._isMounted||!n.isRootInsert;if(!S||$||""===$){var T=S&&p?p:u,E=S&&h?h:d,j=S&&v?v:f,L=S?b||m:m,N=S&&"function"==typeof $?$:y,I=S?w||g:g,M=S?x||_:_,P=l(o(k)?k.enter:k),D=!1!==s&&!qi,R=er(N),F=i._enterCb=C(function(){D&&(Jn(i,j),Jn(i,E)),F.cancelled?(D&&Jn(i,T),M&&M(i)):I&&I(i),i._enterCb=null});n.data.show||ae(n.data.hook||(n.data.hook={}),"insert",function(){var e=i.parentNode,t=e&&e._pending&&e._pending[n.key];t&&t.tag===n.tag&&t.elm._leaveCb&&t.elm._leaveCb(),N&&N(i,F)}),L&&L(i),D&&(Kn(i,T),Kn(i,E),zn(function(){Kn(i,j),Jn(i,T),F.cancelled||R||(Xn(P)?setTimeout(F,P):qn(i,c,F))})),n.data.show&&(r&&r(),N&&N(i,F)),D||R||F()}}}function Qn(n,r){function i(){x.cancelled||(n.data.show||((a.parentNode._pending||(a.parentNode._pending={}))[n.key]=n),v&&v(a),b&&(Kn(a,f),Kn(a,p),zn(function(){Kn(a,d),Jn(a,f),x.cancelled||$||(Xn(w)?setTimeout(x,w):qn(a,u,x))})),h&&h(a,x),b||$||x())}var a=n.elm;t(a._enterCb)&&(a._enterCb.cancelled=!0,a._enterCb());var s=Vn(n.data.transition);if(e(s))return r();if(!t(a._leaveCb)&&1===a.nodeType){var c=s.css,u=s.type,f=s.leaveClass,d=s.leaveToClass,p=s.leaveActiveClass,v=s.beforeLeave,h=s.leave,m=s.afterLeave,y=s.leaveCancelled,g=s.delayLeave,_=s.duration,b=!1!==c&&!qi,$=er(h),w=l(o(_)?_.leave:_),x=a._leaveCb=C(function(){a.parentNode&&a.parentNode._pending&&(a.parentNode._pending[n.key]=null),b&&(Jn(a,d),Jn(a,p)),x.cancelled?(b&&Jn(a,f),y&&y(a)):(r(),m&&m(a)),a._leaveCb=null});g?g(i):i()}}function Xn(e){return"number"==typeof e&&!isNaN(e)}function er(n){if(e(n))return!1;var r=n.fns;return t(r)?er(Array.isArray(r)?r[0]:r):(n._length||n.length)>1}function tr(e,t){!0!==t.data.show&&Yn(t)}function nr(e,t,n){rr(e,t,n),(Ji||Wi)&&setTimeout(function(){rr(e,t,n)},0)}function rr(e,t,n){var r=t.value,i=e.multiple;if(!i||Array.isArray(r)){for(var o,a,s=0,c=e.options.length;s<c;s++)if(a=e.options[s],i)o=$(r,or(a))>-1,a.selected!==o&&(a.selected=o);else if(b(or(a),r))return void(e.selectedIndex!==s&&(e.selectedIndex=s));i||(e.selectedIndex=-1)}}function ir(e,t){return t.every(function(t){return!b(t,e)})}function or(e){return"_value"in e?e._value:e.value}function ar(e){e.target.composing=!0}function sr(e){e.target.composing&&(e.target.composing=!1,cr(e.target,"input"))}function cr(e,t){var n=document.createEvent("HTMLEvents");n.initEvent(t,!0,!0),e.dispatchEvent(n)}function ur(e){return!e.componentInstance||e.data&&e.data.transition?e:ur(e.componentInstance._vnode)}function lr(e){var t=e&&e.componentOptions;return t&&t.Ctor.options.abstract?lr(ye(t.children)):e}function fr(e){var t={},n=e.$options;for(var r in n.propsData)t[r]=e[r];var i=n._parentListeners;for(var o in i)t[ji(o)]=i[o];return t}function dr(e,t){if(/\d-keep-alive$/.test(t.tag))return e("keep-alive",{props:t.componentOptions.propsData})}function pr(e){for(;e=e.parent;)if(e.data.transition)return!0}function vr(e,t){return t.key===e.key&&t.tag===e.tag}function hr(e){e.elm._moveCb&&e.elm._moveCb(),e.elm._enterCb&&e.elm._enterCb()}function mr(e){e.data.newPos=e.elm.getBoundingClientRect()}function yr(e){var t=e.data.pos,n=e.data.newPos,r=t.left-n.left,i=t.top-n.top;if(r||i){e.data.moved=!0;var o=e.elm.style;o.transform=o.WebkitTransform="translate("+r+"px,"+i+"px)",o.transitionDuration="0s"}}function gr(e,t){var n=t?os(t):rs;if(n.test(e)){for(var r,i,o=[],a=n.lastIndex=0;r=n.exec(e);){(i=r.index)>a&&o.push(JSON.stringify(e.slice(a,i)));var s=an(r[1].trim());o.push("_s("+s+")"),a=i+r[0].length}return a<e.length&&o.push(JSON.stringify(e.slice(a))),o.join("+")}}function _r(e,t){var n=t?Ps:Ms;return e.replace(n,function(e){return Is[e]})}function br(e,t){function n(t){l+=t,e=e.substring(t)}function r(e,n,r){var i,s;if(null==n&&(n=l),null==r&&(r=l),e&&(s=e.toLowerCase()),e)for(i=a.length-1;i>=0&&a[i].lowerCasedTag!==s;i--);else i=0;if(i>=0){for(var c=a.length-1;c>=i;c--)t.end&&t.end(a[c].tag,n,r);a.length=i,o=i&&a[i-1].tag}else"br"===s?t.start&&t.start(e,[],!0,n,r):"p"===s&&(t.start&&t.start(e,[],!1,n,r),t.end&&t.end(e,n,r))}for(var i,o,a=[],s=t.expectHTML,c=t.isUnaryTag||Mi,u=t.canBeLeftOpenTag||Mi,l=0;e;){if(i=e,o&&Ls(o)){var f=0,d=o.toLowerCase(),p=Ns[d]||(Ns[d]=new RegExp("([\\s\\S]*?)(</"+d+"[^>]*>)","i")),v=e.replace(p,function(e,n,r){return f=r.length,Ls(d)||"noscript"===d||(n=n.replace(/<!--([\s\S]*?)-->/g,"$1").replace(/<!\[CDATA\[([\s\S]*?)]]>/g,"$1")),Rs(d,n)&&(n=n.slice(1)),t.chars&&t.chars(n),""});l+=e.length-v.length,e=v,r(d,l-f,l)}else{var h=e.indexOf("<");if(0===h){if(_s.test(e)){var m=e.indexOf("--\x3e");if(m>=0){t.shouldKeepComment&&t.comment(e.substring(4,m)),n(m+3);continue}}if(bs.test(e)){var y=e.indexOf("]>");if(y>=0){n(y+2);continue}}var g=e.match(gs);if(g){n(g[0].length);continue}var _=e.match(ys);if(_){var b=l;n(_[0].length),r(_[1],b,l);continue}var $=function(){var t=e.match(hs);if(t){var r={tagName:t[1],attrs:[],start:l};n(t[0].length);for(var i,o;!(i=e.match(ms))&&(o=e.match(ds));)n(o[0].length),r.attrs.push(o);if(i)return r.unarySlash=i[1],n(i[0].length),r.end=l,r}}();if($){!function(e){var n=e.tagName,i=e.unarySlash;s&&("p"===o&&fs(n)&&r(o),u(n)&&o===n&&r(n));for(var l=c(n)||!!i,f=e.attrs.length,d=new Array(f),p=0;p<f;p++){var v=e.attrs[p];$s&&-1===v[0].indexOf('""')&&(""===v[3]&&delete v[3],""===v[4]&&delete v[4],""===v[5]&&delete v[5]);var h=v[3]||v[4]||v[5]||"";d[p]={name:v[1],value:_r(h,t.shouldDecodeNewlines)}}l||(a.push({tag:n,lowerCasedTag:n.toLowerCase(),attrs:d}),o=n),t.start&&t.start(n,d,l,e.start,e.end)}($),Rs(o,e)&&n(1);continue}}var C=void 0,w=void 0,x=void 0;if(h>=0){for(w=e.slice(h);!(ys.test(w)||hs.test(w)||_s.test(w)||bs.test(w)||(x=w.indexOf("<",1))<0);)h+=x,w=e.slice(h);C=e.substring(0,h),n(h)}h<0&&(C=e,e=""),t.chars&&C&&t.chars(C)}if(e===i){t.chars&&t.chars(e);break}}r()}function $r(e,t,n){return{type:1,tag:e,attrsList:t,attrsMap:Fr(t),parent:n,children:[]}}function Cr(e,t){function n(e){e.pre&&(s=!1),Os(e.tag)&&(c=!1)}Cs=t.warn||cn,Os=t.isPreTag||Mi,Ss=t.mustUseProp||Mi,Ts=t.getTagNamespace||Mi,xs=un(t.modules,"transformNode"),ks=un(t.modules,"preTransformNode"),As=un(t.modules,"postTransformNode"),ws=t.delimiters;var r,i,o=[],a=!1!==t.preserveWhitespace,s=!1,c=!1;return br(e,{warn:Cs,expectHTML:t.expectHTML,isUnaryTag:t.isUnaryTag,canBeLeftOpenTag:t.canBeLeftOpenTag,shouldDecodeNewlines:t.shouldDecodeNewlines,shouldKeepComment:t.comments,start:function(e,a,u){var l=i&&i.ns||Ts(e);Ji&&"svg"===l&&(a=Ur(a));var f=$r(e,a,i);l&&(f.ns=l),Br(f)&&!no()&&(f.forbidden=!0);for(var d=0;d<ks.length;d++)f=ks[d](f,t)||f;if(s||(wr(f),f.pre&&(s=!0)),Os(f.tag)&&(c=!0),s?xr(f):f.processed||(Sr(f),Tr(f),Nr(f),kr(f,t)),r?o.length||r.if&&(f.elseif||f.else)&&Lr(r,{exp:f.elseif,block:f}):r=f,i&&!f.forbidden)if(f.elseif||f.else)Er(f,i);else if(f.slotScope){i.plain=!1;var p=f.slotTarget||'"default"';(i.scopedSlots||(i.scopedSlots={}))[p]=f}else i.children.push(f),f.parent=i;u?n(f):(i=f,o.push(f));for(var v=0;v<As.length;v++)As[v](f,t)},end:function(){var e=o[o.length-1],t=e.children[e.children.length-1];t&&3===t.type&&" "===t.text&&!c&&e.children.pop(),o.length-=1,i=o[o.length-1],n(e)},chars:function(e){if(i&&(!Ji||"textarea"!==i.tag||i.attrsMap.placeholder!==e)){var t=i.children;if(e=c||e.trim()?Hr(i)?e:Js(e):a&&t.length?" ":""){var n;!s&&" "!==e&&(n=gr(e,ws))?t.push({type:2,expression:n,text:e}):" "===e&&t.length&&" "===t[t.length-1].text||t.push({type:3,text:e})}}},comment:function(e){i.children.push({type:3,text:e,isComment:!0})}}),r}function wr(e){null!=hn(e,"v-pre")&&(e.pre=!0)}function xr(e){var t=e.attrsList.length;if(t)for(var n=e.attrs=new Array(t),r=0;r<t;r++)n[r]={name:e.attrsList[r].name,value:JSON.stringify(e.attrsList[r].value)};else e.pre||(e.plain=!0)}function kr(e,t){Ar(e),e.plain=!e.key&&!e.attrsList.length,Or(e),Ir(e),Mr(e);for(var n=0;n<xs.length;n++)e=xs[n](e,t)||e;Pr(e)}function Ar(e){var t=vn(e,"key");t&&(e.key=t)}function Or(e){var t=vn(e,"ref");t&&(e.ref=t,e.refInFor=Dr(e))}function Sr(e){var t;if(t=hn(e,"v-for")){var n=t.match(Bs);if(!n)return;e.for=n[2].trim();var r=n[1].trim(),i=r.match(Us);i?(e.alias=i[1].trim(),e.iterator1=i[2].trim(),i[3]&&(e.iterator2=i[3].trim())):e.alias=r}}function Tr(e){var t=hn(e,"v-if");if(t)e.if=t,Lr(e,{exp:t,block:e});else{null!=hn(e,"v-else")&&(e.else=!0);var n=hn(e,"v-else-if");n&&(e.elseif=n)}}function Er(e,t){var n=jr(t.children);n&&n.if&&Lr(n,{exp:e.elseif,block:e})}function jr(e){for(var t=e.length;t--;){if(1===e[t].type)return e[t];e.pop()}}function Lr(e,t){e.ifConditions||(e.ifConditions=[]),e.ifConditions.push(t)}function Nr(e){null!=hn(e,"v-once")&&(e.once=!0)}function Ir(e){if("slot"===e.tag)e.slotName=vn(e,"name");else{var t;"template"===e.tag?(t=hn(e,"scope"),e.slotScope=t||hn(e,"slot-scope")):(t=hn(e,"slot-scope"))&&(e.slotScope=t);var n=vn(e,"slot");n&&(e.slotTarget='""'===n?'"default"':n,e.slotScope||fn(e,"slot",n))}}function Mr(e){var t;(t=vn(e,"is"))&&(e.component=t),null!=hn(e,"inline-template")&&(e.inlineTemplate=!0)}function Pr(e){var t,n,r,i,o,a,s,c=e.attrsList;for(t=0,n=c.length;t<n;t++)if(r=i=c[t].name,o=c[t].value,Hs.test(r))if(e.hasBindings=!0,(a=Rr(r))&&(r=r.replace(Ks,"")),zs.test(r))r=r.replace(zs,""),o=an(o),s=!1,a&&(a.prop&&(s=!0,"innerHtml"===(r=ji(r))&&(r="innerHTML")),a.camel&&(r=ji(r)),a.sync&&pn(e,"update:"+ji(r),yn(o,"$event"))),s||!e.component&&Ss(e.tag,e.attrsMap.type,r)?ln(e,r,o):fn(e,r,o);else if(Fs.test(r))pn(e,r=r.replace(Fs,""),o,a,!1,Cs);else{var u=(r=r.replace(Hs,"")).match(Vs),l=u&&u[1];l&&(r=r.slice(0,-(l.length+1))),dn(e,r,i,o,l,a)}else fn(e,r,JSON.stringify(o))}function Dr(e){for(var t=e;t;){if(void 0!==t.for)return!0;t=t.parent}return!1}function Rr(e){var t=e.match(Ks);if(t){var n={};return t.forEach(function(e){n[e.slice(1)]=!0}),n}}function Fr(e){for(var t={},n=0,r=e.length;n<r;n++)t[e[n].name]=e[n].value;return t}function Hr(e){return"script"===e.tag||"style"===e.tag}function Br(e){return"style"===e.tag||"script"===e.tag&&(!e.attrsMap.type||"text/javascript"===e.attrsMap.type)}function Ur(e){for(var t=[],n=0;n<e.length;n++){var r=e[n];qs.test(r.name)||(r.name=r.name.replace(Ws,""),t.push(r))}return t}function Vr(e){return $r(e.tag,e.attrsList.slice(),e.parent)}function zr(e,t,n){e.attrsMap[t]=n,e.attrsList.push({name:t,value:n})}function Kr(e,t){e&&(Es=Ys(t.staticKeys||""),js=t.isReservedTag||Mi,Jr(e),qr(e,!1))}function Jr(e){if(e.static=Wr(e),1===e.type){if(!js(e.tag)&&"slot"!==e.tag&&null==e.attrsMap["inline-template"])return;for(var t=0,n=e.children.length;t<n;t++){var r=e.children[t];Jr(r),r.static||(e.static=!1)}if(e.ifConditions)for(var i=1,o=e.ifConditions.length;i<o;i++){var a=e.ifConditions[i].block;Jr(a),a.static||(e.static=!1)}}}function qr(e,t){if(1===e.type){if((e.static||e.once)&&(e.staticInFor=t),e.static&&e.children.length&&(1!==e.children.length||3!==e.children[0].type))return void(e.staticRoot=!0);if(e.staticRoot=!1,e.children)for(var n=0,r=e.children.length;n<r;n++)qr(e.children[n],t||!!e.for);if(e.ifConditions)for(var i=1,o=e.ifConditions.length;i<o;i++)qr(e.ifConditions[i].block,t)}}function Wr(e){return 2!==e.type&&(3===e.type||!(!e.pre&&(e.hasBindings||e.if||e.for||Oi(e.tag)||!js(e.tag)||Gr(e)||!Object.keys(e).every(Es))))}function Gr(e){for(;e.parent;){if("template"!==(e=e.parent).tag)return!1;if(e.for)return!0}return!1}function Zr(e,t,n){var r=t?"nativeOn:{":"on:{";for(var i in e){var o=e[i];r+='"'+i+'":'+Yr(i,o)+","}return r.slice(0,-1)+"}"}function Yr(e,t){if(!t)return"function(){}";if(Array.isArray(t))return"["+t.map(function(t){return Yr(e,t)}).join(",")+"]";var n=Xs.test(t.value),r=Qs.test(t.value);if(t.modifiers){var i="",o="",a=[];for(var s in t.modifiers)if(nc[s])o+=nc[s],ec[s]&&a.push(s);else if("exact"===s){var c=t.modifiers;o+=tc(["ctrl","shift","alt","meta"].filter(function(e){return!c[e]}).map(function(e){return"$event."+e+"Key"}).join("||"))}else a.push(s);return a.length&&(i+=Qr(a)),o&&(i+=o),"function($event){"+i+(n?t.value+"($event)":r?"("+t.value+")($event)":t.value)+"}"}return n||r?t.value:"function($event){"+t.value+"}"}function Qr(e){return"if(!('button' in $event)&&"+e.map(Xr).join("&&")+")return null;"}function Xr(e){var t=parseInt(e,10);if(t)return"$event.keyCode!=="+t;var n=ec[e];return"_k($event.keyCode,"+JSON.stringify(e)+","+JSON.stringify(n)+",$event.key)"}function ei(e,t){var n=new ic(t);return{render:"with(this){return "+(e?ti(e,n):'_c("div")')+"}",staticRenderFns:n.staticRenderFns}}function ti(e,t){if(e.staticRoot&&!e.staticProcessed)return ni(e,t);if(e.once&&!e.onceProcessed)return ri(e,t);if(e.for&&!e.forProcessed)return ai(e,t);if(e.if&&!e.ifProcessed)return ii(e,t);if("template"!==e.tag||e.slotTarget){if("slot"===e.tag)return _i(e,t);var n;if(e.component)n=bi(e.component,e,t);else{var r=e.plain?void 0:si(e,t),i=e.inlineTemplate?null:pi(e,t,!0);n="_c('"+e.tag+"'"+(r?","+r:"")+(i?","+i:"")+")"}for(var o=0;o<t.transforms.length;o++)n=t.transforms[o](e,n);return n}return pi(e,t)||"void 0"}function ni(e,t){return e.staticProcessed=!0,t.staticRenderFns.push("with(this){return "+ti(e,t)+"}"),"_m("+(t.staticRenderFns.length-1)+(e.staticInFor?",true":"")+")"}function ri(e,t){if(e.onceProcessed=!0,e.if&&!e.ifProcessed)return ii(e,t);if(e.staticInFor){for(var n="",r=e.parent;r;){if(r.for){n=r.key;break}r=r.parent}return n?"_o("+ti(e,t)+","+t.onceId+++","+n+")":ti(e,t)}return ni(e,t)}function ii(e,t,n,r){return e.ifProcessed=!0,oi(e.ifConditions.slice(),t,n,r)}function oi(e,t,n,r){function i(e){return n?n(e,t):e.once?ri(e,t):ti(e,t)}if(!e.length)return r||"_e()";var o=e.shift();return o.exp?"("+o.exp+")?"+i(o.block)+":"+oi(e,t,n,r):""+i(o.block)}function ai(e,t,n,r){var i=e.for,o=e.alias,a=e.iterator1?","+e.iterator1:"",s=e.iterator2?","+e.iterator2:"";return e.forProcessed=!0,(r||"_l")+"(("+i+"),function("+o+a+s+"){return "+(n||ti)(e,t)+"})"}function si(e,t){var n="{",r=ci(e,t);r&&(n+=r+","),e.key&&(n+="key:"+e.key+","),e.ref&&(n+="ref:"+e.ref+","),e.refInFor&&(n+="refInFor:true,"),e.pre&&(n+="pre:true,"),e.component&&(n+='tag:"'+e.tag+'",');for(var i=0;i<t.dataGenFns.length;i++)n+=t.dataGenFns[i](e);if(e.attrs&&(n+="attrs:{"+$i(e.attrs)+"},"),e.props&&(n+="domProps:{"+$i(e.props)+"},"),e.events&&(n+=Zr(e.events,!1,t.warn)+","),e.nativeEvents&&(n+=Zr(e.nativeEvents,!0,t.warn)+","),e.slotTarget&&!e.slotScope&&(n+="slot:"+e.slotTarget+","),e.scopedSlots&&(n+=li(e.scopedSlots,t)+","),e.model&&(n+="model:{value:"+e.model.value+",callback:"+e.model.callback+",expression:"+e.model.expression+"},"),e.inlineTemplate){var o=ui(e,t);o&&(n+=o+",")}return n=n.replace(/,$/,"")+"}",e.wrapData&&(n=e.wrapData(n)),e.wrapListeners&&(n=e.wrapListeners(n)),n}function ci(e,t){var n=e.directives;if(n){var r,i,o,a,s="directives:[",c=!1;for(r=0,i=n.length;r<i;r++){o=n[r],a=!0;var u=t.directives[o.name];u&&(a=!!u(e,o,t.warn)),a&&(c=!0,s+='{name:"'+o.name+'",rawName:"'+o.rawName+'"'+(o.value?",value:("+o.value+"),expression:"+JSON.stringify(o.value):"")+(o.arg?',arg:"'+o.arg+'"':"")+(o.modifiers?",modifiers:"+JSON.stringify(o.modifiers):"")+"},")}return c?s.slice(0,-1)+"]":void 0}}function ui(e,t){var n=e.children[0];if(1===n.type){var r=ei(n,t.options);return"inlineTemplate:{render:function(){"+r.render+"},staticRenderFns:["+r.staticRenderFns.map(function(e){return"function(){"+e+"}"}).join(",")+"]}"}}function li(e,t){return"scopedSlots:_u(["+Object.keys(e).map(function(n){return fi(n,e[n],t)}).join(",")+"])"}function fi(e,t,n){return t.for&&!t.forProcessed?di(e,t,n):"{key:"+e+",fn:"+("function("+String(t.slotScope)+"){return "+("template"===t.tag?t.if?t.if+"?"+(pi(t,n)||"undefined")+":undefined":pi(t,n)||"undefined":ti(t,n))+"}")+"}"}function di(e,t,n){var r=t.for,i=t.alias,o=t.iterator1?","+t.iterator1:"",a=t.iterator2?","+t.iterator2:"";return t.forProcessed=!0,"_l(("+r+"),function("+i+o+a+"){return "+fi(e,t,n)+"})"}function pi(e,t,n,r,i){var o=e.children;if(o.length){var a=o[0];if(1===o.length&&a.for&&"template"!==a.tag&&"slot"!==a.tag)return(r||ti)(a,t);var s=n?vi(o,t.maybeComponent):0,c=i||mi;return"["+o.map(function(e){return c(e,t)}).join(",")+"]"+(s?","+s:"")}}function vi(e,t){for(var n=0,r=0;r<e.length;r++){var i=e[r];if(1===i.type){if(hi(i)||i.ifConditions&&i.ifConditions.some(function(e){return hi(e.block)})){n=2;break}(t(i)||i.ifConditions&&i.ifConditions.some(function(e){return t(e.block)}))&&(n=1)}}return n}function hi(e){return void 0!==e.for||"template"===e.tag||"slot"===e.tag}function mi(e,t){return 1===e.type?ti(e,t):3===e.type&&e.isComment?gi(e):yi(e)}function yi(e){return"_v("+(2===e.type?e.expression:Ci(JSON.stringify(e.text)))+")"}function gi(e){return"_e("+JSON.stringify(e.text)+")"}function _i(e,t){var n=e.slotName||'"default"',r=pi(e,t),i="_t("+n+(r?","+r:""),o=e.attrs&&"{"+e.attrs.map(function(e){return ji(e.name)+":"+e.value}).join(",")+"}",a=e.attrsMap["v-bind"];return!o&&!a||r||(i+=",null"),o&&(i+=","+o),a&&(i+=(o?"":",null")+","+a),i+")"}function bi(e,t,n){var r=t.inlineTemplate?null:pi(t,n,!0);return"_c("+e+","+si(t,n)+(r?","+r:"")+")"}function $i(e){for(var t="",n=0;n<e.length;n++){var r=e[n];t+='"'+r.name+'":'+Ci(r.value)+","}return t.slice(0,-1)}function Ci(e){return e.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function wi(e,t){try{return new Function(e)}catch(n){return t.push({err:n,code:e}),_}}function xi(e){var t=Object.create(null);return function(n,r,i){delete(r=y({},r)).warn;var o=r.delimiters?String(r.delimiters)+n:n;if(t[o])return t[o];var a=e(n,r),s={},c=[];return s.render=wi(a.render,c),s.staticRenderFns=a.staticRenderFns.map(function(e){return wi(e,c)}),t[o]=s}}function ki(e){if(e.outerHTML)return e.outerHTML;var t=document.createElement("div");return t.appendChild(e.cloneNode(!0)),t.innerHTML}var Ai=Object.prototype.toString,Oi=f("slot,component",!0),Si=f("key,ref,slot,slot-scope,is"),Ti=Object.prototype.hasOwnProperty,Ei=/-(\w)/g,ji=v(function(e){return e.replace(Ei,function(e,t){return t?t.toUpperCase():""})}),Li=v(function(e){return e.charAt(0).toUpperCase()+e.slice(1)}),Ni=/\B([A-Z])/g,Ii=v(function(e){return e.replace(Ni,"-$1").toLowerCase()}),Mi=function(e,t,n){return!1},Pi=function(e){return e},Di="data-server-rendered",Ri=["component","directive","filter"],Fi=["beforeCreate","created","beforeMount","mounted","beforeUpdate","updated","beforeDestroy","destroyed","activated","deactivated","errorCaptured"],Hi={optionMergeStrategies:Object.create(null),silent:!1,productionTip:!1,devtools:!1,performance:!1,errorHandler:null,warnHandler:null,ignoredElements:[],keyCodes:Object.create(null),isReservedTag:Mi,isReservedAttr:Mi,isUnknownElement:Mi,getTagNamespace:_,parsePlatformTagName:Pi,mustUseProp:Mi,_lifecycleHooks:Fi},Bi=Object.freeze({}),Ui=/[^\w.$]/,Vi="__proto__"in{},zi="undefined"!=typeof window,Ki=zi&&window.navigator.userAgent.toLowerCase(),Ji=Ki&&/msie|trident/.test(Ki),qi=Ki&&Ki.indexOf("msie 9.0")>0,Wi=Ki&&Ki.indexOf("edge/")>0,Gi=Ki&&Ki.indexOf("android")>0,Zi=Ki&&/iphone|ipad|ipod|ios/.test(Ki),Yi=(Ki&&/chrome\/\d+/.test(Ki),{}.watch),Qi=!1;if(zi)try{var Xi={};Object.defineProperty(Xi,"passive",{get:function(){Qi=!0}}),window.addEventListener("test-passive",null,Xi)}catch(e){}var eo,to,no=function(){return void 0===eo&&(eo=!zi&&"undefined"!=typeof global&&"server"===global.process.env.VUE_ENV),eo},ro=zi&&window.__VUE_DEVTOOLS_GLOBAL_HOOK__,io="undefined"!=typeof Symbol&&A(Symbol)&&"undefined"!=typeof Reflect&&A(Reflect.ownKeys);to="undefined"!=typeof Set&&A(Set)?Set:function(){function e(){this.set=Object.create(null)}return e.prototype.has=function(e){return!0===this.set[e]},e.prototype.add=function(e){this.set[e]=!0},e.prototype.clear=function(){this.set=Object.create(null)},e}();var oo=_,ao=0,so=function(){this.id=ao++,this.subs=[]};so.prototype.addSub=function(e){this.subs.push(e)},so.prototype.removeSub=function(e){d(this.subs,e)},so.prototype.depend=function(){so.target&&so.target.addDep(this)},so.prototype.notify=function(){for(var e=this.subs.slice(),t=0,n=e.length;t<n;t++)e[t].update()},so.target=null;var co=[],uo=function(e,t,n,r,i,o,a,s){this.tag=e,this.data=t,this.children=n,this.text=r,this.elm=i,this.ns=void 0,this.context=o,this.functionalContext=void 0,this.functionalOptions=void 0,this.functionalScopeId=void 0,this.key=t&&t.key,this.componentOptions=a,this.componentInstance=void 0,this.parent=void 0,this.raw=!1,this.isStatic=!1,this.isRootInsert=!0,this.isComment=!1,this.isCloned=!1,this.isOnce=!1,this.asyncFactory=s,this.asyncMeta=void 0,this.isAsyncPlaceholder=!1},lo={child:{configurable:!0}};lo.child.get=function(){return this.componentInstance},Object.defineProperties(uo.prototype,lo);var fo=function(e){void 0===e&&(e="");var t=new uo;return t.text=e,t.isComment=!0,t},po=Array.prototype,vo=Object.create(po);["push","pop","shift","unshift","splice","sort","reverse"].forEach(function(e){var t=po[e];x(vo,e,function(){for(var n=[],r=arguments.length;r--;)n[r]=arguments[r];var i,o=t.apply(this,n),a=this.__ob__;switch(e){case"push":case"unshift":i=n;break;case"splice":i=n.slice(2)}return i&&a.observeArray(i),a.dep.notify(),o})});var ho=Object.getOwnPropertyNames(vo),mo={shouldConvert:!0},yo=function(e){this.value=e,this.dep=new so,this.vmCount=0,x(e,"__ob__",this),Array.isArray(e)?((Vi?L:N)(e,vo,ho),this.observeArray(e)):this.walk(e)};yo.prototype.walk=function(e){for(var t=Object.keys(e),n=0;n<t.length;n++)M(e,t[n],e[t[n]])},yo.prototype.observeArray=function(e){for(var t=0,n=e.length;t<n;t++)I(e[t])};var go=Hi.optionMergeStrategies;go.data=function(e,t,n){return n?H(e,t,n):t&&"function"!=typeof t?e:H.call(this,e,t)},Fi.forEach(function(e){go[e]=B}),Ri.forEach(function(e){go[e+"s"]=U}),go.watch=function(e,t,n,r){if(e===Yi&&(e=void 0),t===Yi&&(t=void 0),!t)return Object.create(e||null);if(!e)return t;var i={};y(i,e);for(var o in t){var a=i[o],s=t[o];a&&!Array.isArray(a)&&(a=[a]),i[o]=a?a.concat(s):Array.isArray(s)?s:[s]}return i},go.props=go.methods=go.inject=go.computed=function(e,t,n,r){if(!e)return t;var i=Object.create(null);return y(i,e),t&&y(i,t),i},go.provide=H;var _o,bo,$o=function(e,t){return void 0===t?e:t},Co=[],wo=!1,xo=!1;if("undefined"!=typeof setImmediate&&A(setImmediate))bo=function(){setImmediate(te)};else if("undefined"==typeof MessageChannel||!A(MessageChannel)&&"[object MessageChannelConstructor]"!==MessageChannel.toString())bo=function(){setTimeout(te,0)};else{var ko=new MessageChannel,Ao=ko.port2;ko.port1.onmessage=te,bo=function(){Ao.postMessage(1)}}if("undefined"!=typeof Promise&&A(Promise)){var Oo=Promise.resolve();_o=function(){Oo.then(te),Zi&&setTimeout(_)}}else _o=bo;var So,To=v(function(e){var t="&"===e.charAt(0),n="~"===(e=t?e.slice(1):e).charAt(0),r="!"===(e=n?e.slice(1):e).charAt(0);return e=r?e.slice(1):e,{name:e,once:n,capture:r,passive:t}}),Eo=null,jo=[],Lo=[],No={},Io=!1,Mo=!1,Po=0,Do=0,Ro=function(e,t,n,r){this.vm=e,e._watchers.push(this),r?(this.deep=!!r.deep,this.user=!!r.user,this.lazy=!!r.lazy,this.sync=!!r.sync):this.deep=this.user=this.lazy=this.sync=!1,this.cb=n,this.id=++Do,this.active=!0,this.dirty=this.lazy,this.deps=[],this.newDeps=[],this.depIds=new to,this.newDepIds=new to,this.expression="","function"==typeof t?this.getter=t:(this.getter=k(t),this.getter||(this.getter=function(){})),this.value=this.lazy?void 0:this.get()};Ro.prototype.get=function(){O(this);var e,t=this.vm;try{e=this.getter.call(t,t)}catch(e){if(!this.user)throw e;Q(e,t,'getter for watcher "'+this.expression+'"')}finally{this.deep&&Re(e),S(),this.cleanupDeps()}return e},Ro.prototype.addDep=function(e){var t=e.id;this.newDepIds.has(t)||(this.newDepIds.add(t),this.newDeps.push(e),this.depIds.has(t)||e.addSub(this))},Ro.prototype.cleanupDeps=function(){for(var e=this,t=this.deps.length;t--;){var n=e.deps[t];e.newDepIds.has(n.id)||n.removeSub(e)}var r=this.depIds;this.depIds=this.newDepIds,this.newDepIds=r,this.newDepIds.clear(),r=this.deps,this.deps=this.newDeps,this.newDeps=r,this.newDeps.length=0},Ro.prototype.update=function(){this.lazy?this.dirty=!0:this.sync?this.run():De(this)},Ro.prototype.run=function(){if(this.active){var e=this.get();if(e!==this.value||o(e)||this.deep){var t=this.value;if(this.value=e,this.user)try{this.cb.call(this.vm,e,t)}catch(e){Q(e,this.vm,'callback for watcher "'+this.expression+'"')}else this.cb.call(this.vm,e,t)}}},Ro.prototype.evaluate=function(){this.value=this.get(),this.dirty=!1},Ro.prototype.depend=function(){for(var e=this,t=this.deps.length;t--;)e.deps[t].depend()},Ro.prototype.teardown=function(){var e=this;if(this.active){this.vm._isBeingDestroyed||d(this.vm._watchers,this);for(var t=this.deps.length;t--;)e.deps[t].removeSub(e);this.active=!1}};var Fo=new to,Ho={enumerable:!0,configurable:!0,get:_,set:_},Bo={lazy:!0};lt(ft.prototype);var Uo={init:function(e,t,n,r){if(!e.componentInstance||e.componentInstance._isDestroyed)(e.componentInstance=ht(e,Eo,n,r)).$mount(t?e.elm:void 0,t);else if(e.data.keepAlive){var i=e;Uo.prepatch(i,i)}},prepatch:function(e,t){var n=t.componentOptions;Oe(t.componentInstance=e.componentInstance,n.propsData,n.listeners,t,n.children)},insert:function(e){var t=e.context,n=e.componentInstance;n._isMounted||(n._isMounted=!0,je(n,"mounted")),e.data.keepAlive&&(t._isMounted?Me(n):Te(n,!0))},destroy:function(e){var t=e.componentInstance;t._isDestroyed||(e.data.keepAlive?Ee(t,!0):t.$destroy())}},Vo=Object.keys(Uo),zo=1,Ko=2,Jo=0;!function(e){e.prototype._init=function(e){var t=this;t._uid=Jo++,t._isVue=!0,e&&e._isComponent?wt(t,e):t.$options=J(xt(t.constructor),e||{},t),t._renderProxy=t,t._self=t,ke(t),ge(t),Ct(t),je(t,"beforeCreate"),Qe(t),Be(t),Ye(t),je(t,"created"),t.$options.el&&t.$mount(t.$options.el)}}(Ot),function(e){var t={};t.get=function(){return this._data};var n={};n.get=function(){return this._props},Object.defineProperty(e.prototype,"$data",t),Object.defineProperty(e.prototype,"$props",n),e.prototype.$set=P,e.prototype.$delete=D,e.prototype.$watch=function(e,t,n){var r=this;if(a(t))return Ze(r,e,t,n);(n=n||{}).user=!0;var i=new Ro(r,e,t,n);return n.immediate&&t.call(r,i.value),function(){i.teardown()}}}(Ot),function(e){var t=/^hook:/;e.prototype.$on=function(e,n){var r=this,i=this;if(Array.isArray(e))for(var o=0,a=e.length;o<a;o++)r.$on(e[o],n);else(i._events[e]||(i._events[e]=[])).push(n),t.test(e)&&(i._hasHookEvent=!0);return i},e.prototype.$once=function(e,t){function n(){r.$off(e,n),t.apply(r,arguments)}var r=this;return n.fn=t,r.$on(e,n),r},e.prototype.$off=function(e,t){var n=this,r=this;if(!arguments.length)return r._events=Object.create(null),r;if(Array.isArray(e)){for(var i=0,o=e.length;i<o;i++)n.$off(e[i],t);return r}var a=r._events[e];if(!a)return r;if(1===arguments.length)return r._events[e]=null,r;if(t)for(var s,c=a.length;c--;)if((s=a[c])===t||s.fn===t){a.splice(c,1);break}return r},e.prototype.$emit=function(e){var t=this,n=t._events[e];if(n){n=n.length>1?m(n):n;for(var r=m(arguments,1),i=0,o=n.length;i<o;i++)try{n[i].apply(t,r)}catch(n){Q(n,t,'event handler for "'+e+'"')}}return t}}(Ot),function(e){e.prototype._update=function(e,t){var n=this;n._isMounted&&je(n,"beforeUpdate");var r=n.$el,i=n._vnode,o=Eo;Eo=n,n._vnode=e,i?n.$el=n.__patch__(i,e):(n.$el=n.__patch__(n.$el,e,t,!1,n.$options._parentElm,n.$options._refElm),n.$options._parentElm=n.$options._refElm=null),Eo=o,r&&(r.__vue__=null),n.$el&&(n.$el.__vue__=n),n.$vnode&&n.$parent&&n.$vnode===n.$parent._vnode&&(n.$parent.$el=n.$el)},e.prototype.$forceUpdate=function(){var e=this;e._watcher&&e._watcher.update()},e.prototype.$destroy=function(){var e=this;if(!e._isBeingDestroyed){je(e,"beforeDestroy"),e._isBeingDestroyed=!0;var t=e.$parent;!t||t._isBeingDestroyed||e.$options.abstract||d(t.$children,e),e._watcher&&e._watcher.teardown();for(var n=e._watchers.length;n--;)e._watchers[n].teardown();e._data.__ob__&&e._data.__ob__.vmCount--,e._isDestroyed=!0,e.__patch__(e._vnode,null),je(e,"destroyed"),e.$off(),e.$el&&(e.$el.__vue__=null),e.$vnode&&(e.$vnode.parent=null)}}}(Ot),function(e){lt(e.prototype),e.prototype.$nextTick=function(e){return re(e,this)},e.prototype._render=function(){var e=this,t=e.$options,n=t.render,r=t._parentVnode;if(e._isMounted)for(var i in e.$slots){var o=e.$slots[i];o._rendered&&(e.$slots[i]=j(o,!0))}e.$scopedSlots=r&&r.data.scopedSlots||Bi,e.$vnode=r;var a;try{a=n.call(e._renderProxy,e.$createElement)}catch(t){Q(t,e,"render"),a=e._vnode}return a instanceof uo||(a=fo()),a.parent=r,a}}(Ot);var qo=[String,RegExp,Array],Wo={KeepAlive:{name:"keep-alive",abstract:!0,props:{include:qo,exclude:qo,max:[String,Number]},created:function(){this.cache=Object.create(null),this.keys=[]},destroyed:function(){var e=this;for(var t in e.cache)Dt(e.cache,t,e.keys)},watch:{include:function(e){Pt(this,function(t){return Mt(e,t)})},exclude:function(e){Pt(this,function(t){return!Mt(e,t)})}},render:function(){var e=ye(this.$slots.default),t=e&&e.componentOptions;if(t){var n=It(t);if(n&&(this.include&&!Mt(this.include,n)||this.exclude&&Mt(this.exclude,n)))return e;var r=this,i=r.cache,o=r.keys,a=null==e.key?t.Ctor.cid+(t.tag?"::"+t.tag:""):e.key;i[a]?(e.componentInstance=i[a].componentInstance,d(o,a),o.push(a)):(i[a]=e,o.push(a),this.max&&o.length>parseInt(this.max)&&Dt(i,o[0],o,this._vnode)),e.data.keepAlive=!0}return e}}};!function(e){var t={};t.get=function(){return Hi},Object.defineProperty(e,"config",t),e.util={warn:oo,extend:y,mergeOptions:J,defineReactive:M},e.set=P,e.delete=D,e.nextTick=re,e.options=Object.create(null),Ri.forEach(function(t){e.options[t+"s"]=Object.create(null)}),e.options._base=e,y(e.options.components,Wo),St(e),Tt(e),Et(e),Nt(e)}(Ot),Object.defineProperty(Ot.prototype,"$isServer",{get:no}),Object.defineProperty(Ot.prototype,"$ssrContext",{get:function(){return this.$vnode&&this.$vnode.ssrContext}}),Ot.version="2.5.2";var Go,Zo,Yo,Qo,Xo,ea,ta,na,ra=f("style,class"),ia=f("input,textarea,option,select,progress"),oa=function(e,t,n){return"value"===n&&ia(e)&&"button"!==t||"selected"===n&&"option"===e||"checked"===n&&"input"===e||"muted"===n&&"video"===e},aa=f("contenteditable,draggable,spellcheck"),sa=f("allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,default,defaultchecked,defaultmuted,defaultselected,defer,disabled,enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,required,reversed,scoped,seamless,selected,sortable,translate,truespeed,typemustmatch,visible"),ca="http://www.w3.org/1999/xlink",ua=function(e){return":"===e.charAt(5)&&"xlink"===e.slice(0,5)},la=function(e){return ua(e)?e.slice(6,e.length):""},fa=function(e){return null==e||!1===e},da={svg:"http://www.w3.org/2000/svg",math:"http://www.w3.org/1998/Math/MathML"},pa=f("html,body,base,head,link,meta,style,title,address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,menuitem,summary,content,element,shadow,template,blockquote,iframe,tfoot"),va=f("svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,foreignObject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view",!0),ha=function(e){return pa(e)||va(e)},ma=Object.create(null),ya=f("text,number,password,search,email,tel,url"),ga=Object.freeze({createElement:function(e,t){var n=document.createElement(e);return"select"!==e?n:(t.data&&t.data.attrs&&void 0!==t.data.attrs.multiple&&n.setAttribute("multiple","multiple"),n)},createElementNS:function(e,t){return document.createElementNS(da[e],t)},createTextNode:function(e){return document.createTextNode(e)},createComment:function(e){return document.createComment(e)},insertBefore:function(e,t,n){e.insertBefore(t,n)},removeChild:function(e,t){e.removeChild(t)},appendChild:function(e,t){e.appendChild(t)},parentNode:function(e){return e.parentNode},nextSibling:function(e){return e.nextSibling},tagName:function(e){return e.tagName},setTextContent:function(e,t){e.textContent=t},setAttribute:function(e,t,n){e.setAttribute(t,n)}}),_a={create:function(e,t){qt(t)},update:function(e,t){e.data.ref!==t.data.ref&&(qt(e,!0),qt(t))},destroy:function(e){qt(e,!0)}},ba=new uo("",{},[]),$a=["create","activate","update","remove","destroy"],Ca={create:Yt,update:Yt,destroy:function(e){Yt(e,ba)}},wa=Object.create(null),xa=[_a,Ca],ka={create:nn,update:nn},Aa={create:on,update:on},Oa=/[\w).+\-_$\]]/,Sa="__r",Ta="__c",Ea={create:Ln,update:Ln},ja={create:Nn,update:Nn},La=v(function(e){var t={},n=/;(?![^(]*\))/g,r=/:(.+)/;return e.split(n).forEach(function(e){if(e){var n=e.split(r);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}),Na=/^--/,Ia=/\s*!important$/,Ma=function(e,t,n){if(Na.test(t))e.style.setProperty(t,n);else if(Ia.test(n))e.style.setProperty(t,n.replace(Ia,""),"important");else{var r=Da(t);if(Array.isArray(n))for(var i=0,o=n.length;i<o;i++)e.style[r]=n[i];else e.style[r]=n}},Pa=["Webkit","Moz","ms"],Da=v(function(e){if(na=na||document.createElement("div").style,"filter"!==(e=ji(e))&&e in na)return e;for(var t=e.charAt(0).toUpperCase()+e.slice(1),n=0;n<Pa.length;n++){var r=Pa[n]+t;if(r in na)return r}}),Ra={create:Hn,update:Hn},Fa=v(function(e){return{enterClass:e+"-enter",enterToClass:e+"-enter-to",enterActiveClass:e+"-enter-active",leaveClass:e+"-leave",leaveToClass:e+"-leave-to",leaveActiveClass:e+"-leave-active"}}),Ha=zi&&!qi,Ba="transition",Ua="animation",Va="transition",za="transitionend",Ka="animation",Ja="animationend";Ha&&(void 0===window.ontransitionend&&void 0!==window.onwebkittransitionend&&(Va="WebkitTransition",za="webkitTransitionEnd"),void 0===window.onanimationend&&void 0!==window.onwebkitanimationend&&(Ka="WebkitAnimation",Ja="webkitAnimationEnd"));var qa=zi?window.requestAnimationFrame?window.requestAnimationFrame.bind(window):setTimeout:function(e){return e()},Wa=/\b(transform|all)(,|$)/,Ga=function(r){function o(e){return new uo(j.tagName(e).toLowerCase(),{},[],void 0,e)}function a(e,t){function n(){0==--n.listeners&&s(e)}return n.listeners=t,n}function s(e){var n=j.parentNode(e);t(n)&&j.removeChild(n,e)}function c(e,r,i,o,a){if(e.isRootInsert=!a,!u(e,r,i,o)){var s=e.data,c=e.children,l=e.tag;t(l)?(e.elm=e.ns?j.createElementNS(e.ns,l):j.createElement(l,e),y(e),v(e,c,r),t(s)&&m(e,r),p(i,e.elm,o)):n(e.isComment)?(e.elm=j.createComment(e.text),p(i,e.elm,o)):(e.elm=j.createTextNode(e.text),p(i,e.elm,o))}}function u(e,r,i,o){var a=e.data;if(t(a)){var s=t(e.componentInstance)&&a.keepAlive;if(t(a=a.hook)&&t(a=a.init)&&a(e,!1,i,o),t(e.componentInstance))return l(e,r),n(s)&&d(e,r,i,o),!0}}function l(e,n){t(e.data.pendingInsert)&&(n.push.apply(n,e.data.pendingInsert),e.data.pendingInsert=null),e.elm=e.componentInstance.$el,h(e)?(m(e,n),y(e)):(qt(e),n.push(e))}function d(e,n,r,i){for(var o,a=e;a.componentInstance;)if(a=a.componentInstance._vnode,t(o=a.data)&&t(o=o.transition)){for(o=0;o<T.activate.length;++o)T.activate[o](ba,a);n.push(a);break}p(r,e.elm,i)}function p(e,n,r){t(e)&&(t(r)?r.parentNode===e&&j.insertBefore(e,n,r):j.appendChild(e,n))}function v(e,t,n){if(Array.isArray(t))for(var r=0;r<t.length;++r)c(t[r],n,e.elm,null,!0);else i(e.text)&&j.appendChild(e.elm,j.createTextNode(e.text))}function h(e){for(;e.componentInstance;)e=e.componentInstance._vnode;return t(e.tag)}function m(e,n){for(var r=0;r<T.create.length;++r)T.create[r](ba,e);t(O=e.data.hook)&&(t(O.create)&&O.create(ba,e),t(O.insert)&&n.push(e))}function y(e){var n;if(t(n=e.functionalScopeId))j.setAttribute(e.elm,n,"");else for(var r=e;r;)t(n=r.context)&&t(n=n.$options._scopeId)&&j.setAttribute(e.elm,n,""),r=r.parent;t(n=Eo)&&n!==e.context&&n!==e.functionalContext&&t(n=n.$options._scopeId)&&j.setAttribute(e.elm,n,"")}function g(e,t,n,r,i,o){for(;r<=i;++r)c(n[r],o,e,t)}function _(e){var n,r,i=e.data;if(t(i))for(t(n=i.hook)&&t(n=n.destroy)&&n(e),n=0;n<T.destroy.length;++n)T.destroy[n](e);if(t(n=e.children))for(r=0;r<e.children.length;++r)_(e.children[r])}function b(e,n,r,i){for(;r<=i;++r){var o=n[r];t(o)&&(t(o.tag)?($(o),_(o)):s(o.elm))}}function $(e,n){if(t(n)||t(e.data)){var r,i=T.remove.length+1;for(t(n)?n.listeners+=i:n=a(e.elm,i),t(r=e.componentInstance)&&t(r=r._vnode)&&t(r.data)&&$(r,n),r=0;r<T.remove.length;++r)T.remove[r](e,n);t(r=e.data.hook)&&t(r=r.remove)?r(e,n):n()}else s(e.elm)}function C(n,r,i,o,a){for(var s,u,l,f=0,d=0,p=r.length-1,v=r[0],h=r[p],m=i.length-1,y=i[0],_=i[m],$=!a;f<=p&&d<=m;)e(v)?v=r[++f]:e(h)?h=r[--p]:Wt(v,y)?(x(v,y,o),v=r[++f],y=i[++d]):Wt(h,_)?(x(h,_,o),h=r[--p],_=i[--m]):Wt(v,_)?(x(v,_,o),$&&j.insertBefore(n,v.elm,j.nextSibling(h.elm)),v=r[++f],_=i[--m]):Wt(h,y)?(x(h,y,o),$&&j.insertBefore(n,h.elm,v.elm),h=r[--p],y=i[++d]):(e(s)&&(s=Zt(r,f,p)),e(u=t(y.key)?s[y.key]:w(y,r,f,p))?c(y,o,n,v.elm):Wt(l=r[u],y)?(x(l,y,o),r[u]=void 0,$&&j.insertBefore(n,l.elm,v.elm)):c(y,o,n,v.elm),y=i[++d]);f>p?g(n,e(i[m+1])?null:i[m+1].elm,i,d,m,o):d>m&&b(n,r,f,p)}function w(e,n,r,i){for(var o=r;o<i;o++){var a=n[o];if(t(a)&&Wt(e,a))return o}}function x(r,i,o,a){if(r!==i){var s=i.elm=r.elm;if(n(r.isAsyncPlaceholder))t(i.asyncFactory.resolved)?A(r.elm,i,o):i.isAsyncPlaceholder=!0;else if(n(i.isStatic)&&n(r.isStatic)&&i.key===r.key&&(n(i.isCloned)||n(i.isOnce)))i.componentInstance=r.componentInstance;else{var c,u=i.data;t(u)&&t(c=u.hook)&&t(c=c.prepatch)&&c(r,i);var l=r.children,f=i.children;if(t(u)&&h(i)){for(c=0;c<T.update.length;++c)T.update[c](r,i);t(c=u.hook)&&t(c=c.update)&&c(r,i)}e(i.text)?t(l)&&t(f)?l!==f&&C(s,l,f,o,a):t(f)?(t(r.text)&&j.setTextContent(s,""),g(s,null,f,0,f.length-1,o)):t(l)?b(s,l,0,l.length-1):t(r.text)&&j.setTextContent(s,""):r.text!==i.text&&j.setTextContent(s,i.text),t(u)&&t(c=u.hook)&&t(c=c.postpatch)&&c(r,i)}}}function k(e,r,i){if(n(i)&&t(e.parent))e.parent.data.pendingInsert=r;else for(var o=0;o<r.length;++o)r[o].data.hook.insert(r[o])}function A(e,r,i){if(n(r.isComment)&&t(r.asyncFactory))return r.elm=e,r.isAsyncPlaceholder=!0,!0;r.elm=e;var o=r.tag,a=r.data,s=r.children;if(t(a)&&(t(O=a.hook)&&t(O=O.init)&&O(r,!0),t(O=r.componentInstance)))return l(r,i),!0;if(t(o)){if(t(s))if(e.hasChildNodes())if(t(O=a)&&t(O=O.domProps)&&t(O=O.innerHTML)){if(O!==e.innerHTML)return!1}else{for(var c=!0,u=e.firstChild,f=0;f<s.length;f++){if(!u||!A(u,s[f],i)){c=!1;break}u=u.nextSibling}if(!c||u)return!1}else v(r,s,i);if(t(a))for(var d in a)if(!L(d)){m(r,i);break}}else e.data!==r.text&&(e.data=r.text);return!0}var O,S,T={},E=r.modules,j=r.nodeOps;for(O=0;O<$a.length;++O)for(T[$a[O]]=[],S=0;S<E.length;++S)t(E[S][$a[O]])&&T[$a[O]].push(E[S][$a[O]]);var L=f("attrs,style,class,staticClass,staticStyle,key");return function(r,i,a,s,u,l){if(!e(i)){var f=!1,d=[];if(e(r))f=!0,c(i,d,u,l);else{var p=t(r.nodeType);if(!p&&Wt(r,i))x(r,i,d,s);else{if(p){if(1===r.nodeType&&r.hasAttribute(Di)&&(r.removeAttribute(Di),a=!0),n(a)&&A(r,i,d))return k(i,d,!0),r;r=o(r)}var v=r.elm,m=j.parentNode(v);if(c(i,d,v._leaveCb?null:m,j.nextSibling(v)),t(i.parent))for(var y=i.parent,g=h(i);y;){for(var $=0;$<T.destroy.length;++$)T.destroy[$](y);if(y.elm=i.elm,g){for(var C=0;C<T.create.length;++C)T.create[C](ba,y);var w=y.data.hook.insert;if(w.merged)for(var O=1;O<w.fns.length;O++)w.fns[O]()}else qt(y);y=y.parent}t(m)?b(m,[r],0,0):t(r.tag)&&_(r)}}return k(i,d,f),i.elm}t(r)&&_(r)}}({nodeOps:ga,modules:[ka,Aa,Ea,ja,Ra,zi?{create:tr,activate:tr,remove:function(e,t){!0!==e.data.show?Qn(e,t):t()}}:{}].concat(xa)});qi&&document.addEventListener("selectionchange",function(){var e=document.activeElement;e&&e.vmodel&&cr(e,"input")});var Za={model:{inserted:function(e,t,n){"select"===n.tag?(nr(e,t,n.context),e._vOptions=[].map.call(e.options,or)):("textarea"===n.tag||ya(e.type))&&(e._vModifiers=t.modifiers,t.modifiers.lazy||(e.addEventListener("change",sr),Gi||(e.addEventListener("compositionstart",ar),e.addEventListener("compositionend",sr)),qi&&(e.vmodel=!0)))},componentUpdated:function(e,t,n){if("select"===n.tag){nr(e,t,n.context);var r=e._vOptions,i=e._vOptions=[].map.call(e.options,or);i.some(function(e,t){return!b(e,r[t])})&&(e.multiple?t.value.some(function(e){return ir(e,i)}):t.value!==t.oldValue&&ir(t.value,i))&&cr(e,"change")}}},show:{bind:function(e,t,n){var r=t.value,i=(n=ur(n)).data&&n.data.transition,o=e.__vOriginalDisplay="none"===e.style.display?"":e.style.display;r&&i?(n.data.show=!0,Yn(n,function(){e.style.display=o})):e.style.display=r?o:"none"},update:function(e,t,n){var r=t.value;r!==t.oldValue&&((n=ur(n)).data&&n.data.transition?(n.data.show=!0,r?Yn(n,function(){e.style.display=e.__vOriginalDisplay}):Qn(n,function(){e.style.display="none"})):e.style.display=r?e.__vOriginalDisplay:"none")},unbind:function(e,t,n,r,i){i||(e.style.display=e.__vOriginalDisplay)}}},Ya={name:String,appear:Boolean,css:Boolean,mode:String,type:String,enterClass:String,leaveClass:String,enterToClass:String,leaveToClass:String,enterActiveClass:String,leaveActiveClass:String,appearClass:String,appearActiveClass:String,appearToClass:String,duration:[Number,String,Object]},Qa={name:"transition",props:Ya,abstract:!0,render:function(e){var t=this,n=this.$options._renderChildren;if(n&&(n=n.filter(function(e){return e.tag||me(e)})).length){var r=this.mode,o=n[0];if(pr(this.$vnode))return o;var a=lr(o);if(!a)return o;if(this._leaving)return dr(e,o);var s="__transition-"+this._uid+"-";a.key=null==a.key?a.isComment?s+"comment":s+a.tag:i(a.key)?0===String(a.key).indexOf(s)?a.key:s+a.key:a.key;var c=(a.data||(a.data={})).transition=fr(this),u=this._vnode,l=lr(u);if(a.data.directives&&a.data.directives.some(function(e){return"show"===e.name})&&(a.data.show=!0),l&&l.data&&!vr(a,l)&&!me(l)){var f=l.data.transition=y({},c);if("out-in"===r)return this._leaving=!0,ae(f,"afterLeave",function(){t._leaving=!1,t.$forceUpdate()}),dr(e,o);if("in-out"===r){if(me(a))return u;var d,p=function(){d()};ae(c,"afterEnter",p),ae(c,"enterCancelled",p),ae(f,"delayLeave",function(e){d=e})}}return o}}},Xa=y({tag:String,moveClass:String},Ya);delete Xa.mode;var es={Transition:Qa,TransitionGroup:{props:Xa,render:function(e){for(var t=this.tag||this.$vnode.data.tag||"span",n=Object.create(null),r=this.prevChildren=this.children,i=this.$slots.default||[],o=this.children=[],a=fr(this),s=0;s<i.length;s++){var c=i[s];c.tag&&null!=c.key&&0!==String(c.key).indexOf("__vlist")&&(o.push(c),n[c.key]=c,(c.data||(c.data={})).transition=a)}if(r){for(var u=[],l=[],f=0;f<r.length;f++){var d=r[f];d.data.transition=a,d.data.pos=d.elm.getBoundingClientRect(),n[d.key]?u.push(d):l.push(d)}this.kept=e(t,null,u),this.removed=l}return e(t,null,o)},beforeUpdate:function(){this.__patch__(this._vnode,this.kept,!1,!0),this._vnode=this.kept},updated:function(){var e=this.prevChildren,t=this.moveClass||(this.name||"v")+"-move";e.length&&this.hasMove(e[0].elm,t)&&(e.forEach(hr),e.forEach(mr),e.forEach(yr),this._reflow=document.body.offsetHeight,e.forEach(function(e){if(e.data.moved){var n=e.elm,r=n.style;Kn(n,t),r.transform=r.WebkitTransform=r.transitionDuration="",n.addEventListener(za,n._moveCb=function e(r){r&&!/transform$/.test(r.propertyName)||(n.removeEventListener(za,e),n._moveCb=null,Jn(n,t))})}}))},methods:{hasMove:function(e,t){if(!Ha)return!1;if(this._hasMove)return this._hasMove;var n=e.cloneNode();e._transitionClasses&&e._transitionClasses.forEach(function(e){Un(n,e)}),Bn(n,t),n.style.display="none",this.$el.appendChild(n);var r=Wn(n);return this.$el.removeChild(n),this._hasMove=r.hasTransform}}}};Ot.config.mustUseProp=oa,Ot.config.isReservedTag=ha,Ot.config.isReservedAttr=ra,Ot.config.getTagNamespace=Kt,Ot.config.isUnknownElement=function(e){if(!zi)return!0;if(ha(e))return!1;if(e=e.toLowerCase(),null!=ma[e])return ma[e];var t=document.createElement(e);return e.indexOf("-")>-1?ma[e]=t.constructor===window.HTMLUnknownElement||t.constructor===window.HTMLElement:ma[e]=/HTMLUnknownElement/.test(t.toString())},y(Ot.options.directives,Za),y(Ot.options.components,es),Ot.prototype.__patch__=zi?Ga:_,Ot.prototype.$mount=function(e,t){return e=e&&zi?Jt(e):void 0,Ae(this,e,t)},Ot.nextTick(function(){Hi.devtools&&ro&&ro.emit("init",Ot)},0);var ts,ns=!!zi&&function(e,t){var n=document.createElement("div");return n.innerHTML='<div a="'+e+'"/>',n.innerHTML.indexOf(t)>0}("\n"," "),rs=/\{\{((?:.|\n)+?)\}\}/g,is=/[-.*+?^${}()|[\]\/\\]/g,os=v(function(e){var t=e[0].replace(is,"\\$&"),n=e[1].replace(is,"\\$&");return new RegExp(t+"((?:.|\\n)+?)"+n,"g")}),as={staticKeys:["staticClass"],transformNode:function(e,t){t.warn;var n=hn(e,"class");n&&(e.staticClass=JSON.stringify(n));var r=vn(e,"class",!1);r&&(e.classBinding=r)},genData:function(e){var t="";return e.staticClass&&(t+="staticClass:"+e.staticClass+","),e.classBinding&&(t+="class:"+e.classBinding+","),t}},ss={staticKeys:["staticStyle"],transformNode:function(e,t){var n=hn(e,"style");n&&(e.staticStyle=JSON.stringify(La(n)));var r=vn(e,"style",!1);r&&(e.styleBinding=r)},genData:function(e){var t="";return e.staticStyle&&(t+="staticStyle:"+e.staticStyle+","),e.styleBinding&&(t+="style:("+e.styleBinding+"),"),t}},cs={decode:function(e){return ts=ts||document.createElement("div"),ts.innerHTML=e,ts.textContent}},us=f("area,base,br,col,embed,frame,hr,img,input,isindex,keygen,link,meta,param,source,track,wbr"),ls=f("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source"),fs=f("address,article,aside,base,blockquote,body,caption,col,colgroup,dd,details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,title,tr,track"),ds=/^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/,ps="[a-zA-Z_][\\w\\-\\.]*",vs="((?:"+ps+"\\:)?"+ps+")",hs=new RegExp("^<"+vs),ms=/^\s*(\/?)>/,ys=new RegExp("^<\\/"+vs+"[^>]*>"),gs=/^<!DOCTYPE [^>]+>/i,_s=/^<!--/,bs=/^<!\[/,$s=!1;"x".replace(/x(.)?/g,function(e,t){$s=""===t});var Cs,ws,xs,ks,As,Os,Ss,Ts,Es,js,Ls=f("script,style,textarea",!0),Ns={},Is={"<":"<",">":">",""":'"',"&":"&"," ":"\n"},Ms=/&(?:lt|gt|quot|amp);/g,Ps=/&(?:lt|gt|quot|amp|#10);/g,Ds=f("pre,textarea",!0),Rs=function(e,t){return e&&Ds(e)&&"\n"===t[0]},Fs=/^@|^v-on:/,Hs=/^v-|^@|^:/,Bs=/(.*?)\s+(?:in|of)\s+(.*)/,Us=/\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/,Vs=/:(.*)$/,zs=/^:|^v-bind:/,Ks=/\.[^.]+/g,Js=v(cs.decode),qs=/^xmlns:NS\d+/,Ws=/^NS\d+:/,Gs=[as,ss,{preTransformNode:function(e,t){if("input"===e.tag){var n=e.attrsMap;if(n["v-model"]&&(n["v-bind:type"]||n[":type"])){var r=vn(e,"type"),i=hn(e,"v-if",!0),o=i?"&&("+i+")":"",a=Vr(e);Sr(a),zr(a,"type","checkbox"),kr(a,t),a.processed=!0,a.if="("+r+")==='checkbox'"+o,Lr(a,{exp:a.if,block:a});var s=Vr(e);hn(s,"v-for",!0),zr(s,"type","radio"),kr(s,t),Lr(a,{exp:"("+r+")==='radio'"+o,block:s});var c=Vr(e);return hn(c,"v-for",!0),zr(c,":type",r),kr(c,t),Lr(a,{exp:i,block:c}),a}}}}],Zs={expectHTML:!0,modules:Gs,directives:{model:function(e,t,n){var r=t.value,i=t.modifiers,o=e.tag,a=e.attrsMap.type;if(e.component)return mn(e,r,i),!1;if("select"===o)An(e,r,i);else if("input"===o&&"checkbox"===a)xn(e,r,i);else if("input"===o&&"radio"===a)kn(e,r,i);else if("input"===o||"textarea"===o)On(e,r,i);else if(!Hi.isReservedTag(o))return mn(e,r,i),!1;return!0},text:function(e,t){t.value&&ln(e,"textContent","_s("+t.value+")")},html:function(e,t){t.value&&ln(e,"innerHTML","_s("+t.value+")")}},isPreTag:function(e){return"pre"===e},isUnaryTag:us,mustUseProp:oa,canBeLeftOpenTag:ls,isReservedTag:ha,getTagNamespace:Kt,staticKeys:function(e){return e.reduce(function(e,t){return e.concat(t.staticKeys||[])},[]).join(",")}(Gs)},Ys=v(function(e){return f("type,tag,attrsList,attrsMap,plain,parent,children,attrs"+(e?","+e:""))}),Qs=/^\s*([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/,Xs=/^\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?']|\[".*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*\s*$/,ec={esc:27,tab:9,enter:13,space:32,up:38,left:37,right:39,down:40,delete:[8,46]},tc=function(e){return"if("+e+")return null;"},nc={stop:"$event.stopPropagation();",prevent:"$event.preventDefault();",self:tc("$event.target !== $event.currentTarget"),ctrl:tc("!$event.ctrlKey"),shift:tc("!$event.shiftKey"),alt:tc("!$event.altKey"),meta:tc("!$event.metaKey"),left:tc("'button' in $event && $event.button !== 0"),middle:tc("'button' in $event && $event.button !== 1"),right:tc("'button' in $event && $event.button !== 2")},rc={on:function(e,t){e.wrapListeners=function(e){return"_g("+e+","+t.value+")"}},bind:function(e,t){e.wrapData=function(n){return"_b("+n+",'"+e.tag+"',"+t.value+","+(t.modifiers&&t.modifiers.prop?"true":"false")+(t.modifiers&&t.modifiers.sync?",true":"")+")"}},cloak:_},ic=function(e){this.options=e,this.warn=e.warn||cn,this.transforms=un(e.modules,"transformCode"),this.dataGenFns=un(e.modules,"genData"),this.directives=y(y({},rc),e.directives);var t=e.isReservedTag||Mi;this.maybeComponent=function(e){return!t(e.tag)},this.onceId=0,this.staticRenderFns=[]},oc=(new RegExp("\\b"+"do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,super,throw,while,yield,delete,export,import,return,switch,default,extends,finally,continue,debugger,function,arguments".split(",").join("\\b|\\b")+"\\b"),new RegExp("\\b"+"delete,typeof,void".split(",").join("\\s*\\([^\\)]*\\)|\\b")+"\\s*\\([^\\)]*\\)"),function(e){return function(t){function n(n,r){var i=Object.create(t),o=[],a=[];if(i.warn=function(e,t){(t?a:o).push(e)},r){r.modules&&(i.modules=(t.modules||[]).concat(r.modules)),r.directives&&(i.directives=y(Object.create(t.directives),r.directives));for(var s in r)"modules"!==s&&"directives"!==s&&(i[s]=r[s])}var c=e(n,i);return c.errors=o,c.tips=a,c}return{compile:n,compileToFunctions:xi(n)}}}(function(e,t){var n=Cr(e.trim(),t);Kr(n,t);var r=ei(n,t);return{ast:n,render:r.render,staticRenderFns:r.staticRenderFns}})(Zs).compileToFunctions),ac=v(function(e){var t=Jt(e);return t&&t.innerHTML}),sc=Ot.prototype.$mount;return Ot.prototype.$mount=function(e,t){if((e=e&&Jt(e))===document.body||e===document.documentElement)return this;var n=this.$options;if(!n.render){var r=n.template;if(r)if("string"==typeof r)"#"===r.charAt(0)&&(r=ac(r));else{if(!r.nodeType)return this;r=r.innerHTML}else e&&(r=ki(e));if(r){var i=oc(r,{shouldDecodeNewlines:ns,delimiters:n.delimiters,comments:n.comments},this),o=i.render,a=i.staticRenderFns;n.render=o,n.staticRenderFns=a}}return sc.call(this,e,t)},Ot.compile=oc,Ot}); | dist/vue.min.js | 0 | https://github.com/vuejs/vue/commit/cfd73c2386623341fdbb3ac636c4baf84ea89c2c | [
0.00016763371240813285,
0.00016763371240813285,
0.00016763371240813285,
0.00016763371240813285,
0
] |
{
"id": 0,
"code_window": [
" \"dev-expression\",\n",
" \"transform-class-properties\",\n",
" [\"transform-object-rest-spread\", { \"useBuiltIns\": true }],\n",
" \"transform-export-default\"\n",
" ]\n",
" },\n",
" \"build-esm\": {\n",
" \"presets\": [[\"env\", { \"loose\": true, \"modules\": false }], \"react\"],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"transform-export-default\",\n",
" [\n",
" \"transform-imports\",\n",
" {\n",
" \"react-router\": {\n",
" \"transform\": \"react-router/${member}\"\n",
" }\n",
" }\n",
" ]\n"
],
"file_path": "packages/react-router-config/modules/.babelrc",
"type": "replace",
"edit_start_line_idx": 8
} | {
"env": {
"build-cjs": {
"presets": [["env", { "loose": true }], "react"],
"plugins": [
"dev-expression",
"transform-class-properties",
["transform-object-rest-spread", { "useBuiltIns": true }],
"transform-export-default"
]
},
"build-esm": {
"presets": [["env", { "loose": true, "modules": false }], "react"],
"plugins": [
"dev-expression",
"transform-class-properties",
["transform-object-rest-spread", { "useBuiltIns": true }],
"transform-export-default"
]
},
"test": {
"presets": [["env", { "loose": true }], "react"],
"plugins": [
"dev-expression",
"transform-class-properties",
["transform-object-rest-spread", { "useBuiltIns": true }],
"transform-export-default",
[
"transform-imports",
{
"react-router": {
"transform": "react-router/modules/${member}"
}
}
]
]
}
}
}
| packages/react-router-config/modules/.babelrc | 1 | https://github.com/remix-run/react-router/commit/afebe674caff9751ce821de9c0bae544eaac8bf2 | [
0.9934509992599487,
0.4564974009990692,
0.00016658731328789145,
0.4161860942840576,
0.3817475438117981
] |
{
"id": 0,
"code_window": [
" \"dev-expression\",\n",
" \"transform-class-properties\",\n",
" [\"transform-object-rest-spread\", { \"useBuiltIns\": true }],\n",
" \"transform-export-default\"\n",
" ]\n",
" },\n",
" \"build-esm\": {\n",
" \"presets\": [[\"env\", { \"loose\": true, \"modules\": false }], \"react\"],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"transform-export-default\",\n",
" [\n",
" \"transform-imports\",\n",
" {\n",
" \"react-router\": {\n",
" \"transform\": \"react-router/${member}\"\n",
" }\n",
" }\n",
" ]\n"
],
"file_path": "packages/react-router-config/modules/.babelrc",
"type": "replace",
"edit_start_line_idx": 8
} | # Philosophy
This guide's purpose is to explain the mental model to have when using React Router. We call it "Dynamic Routing", which is quite different from the "Static Routing" you're probably more familiar with.
## Static Routing
If you've used Rails, Express, Ember, Angular etc. you've used static routing. In these frameworks, you declare your routes as part of your app's initialization before any rendering takes place. React Router pre-v4 was also static (mostly). Let's take a look at how to configure routes in express:
```js
app.get('/', handleIndex)
app.get('/invoices', handleInvoices)
app.get('/invoices/:id', handleInvoice)
app.get('/invoices/:id/edit', handleInvoiceEdit)
app.listen()
```
Note how the routes are declared before the app listens. The client side routers we've used are similar. In Angular you declare your routes up front and then import them to the top-level `AppModule` before rendering:
```js
const appRoutes: Routes = [
{ path: 'crisis-center',
component: CrisisListComponent
},
{ path: 'hero/:id',
component: HeroDetailComponent
},
{ path: 'heroes',
component: HeroListComponent,
data: { title: 'Heroes List' }
},
{ path: '',
redirectTo: '/heroes',
pathMatch: 'full'
},
{ path: '**',
component: PageNotFoundComponent
}
];
@NgModule({
imports: [
RouterModule.forRoot(appRoutes)
]
})
export class AppModule { }
```
Ember has a conventional `routes.js` file that the build reads and
imports into the application for you. Again, this happens before
your app renders.
```js
Router.map(function() {
this.route('about');
this.route('contact');
this.route('rentals', function() {
this.route('show', { path: '/:rental_id' });
});
});
export default Router
```
Though the APIs are different, they all share the model of "static routes". React Router also followed that lead up until v4.
To be successful with React Router, you need to forget all that! :O
## Backstory
To be candid, we were pretty frustrated with the direction we'd taken React Router by v2. We (Michael and Ryan) felt limited by the API, recognized we were reimplementing parts of React (lifecycles, and more), and it just didn't match the mental model React has given us for composing UI.
We were walking through the hallway of a hotel just before a workshop discussing what to do about it. We asked each other: "What would it look like if we built the router using the patterns we teach in our workshops?"
It was only a matter of hours into development that we had a proof-of-concept that we knew was the future we wanted for routing. We ended up with API that wasn't "outside" of React, an API that composed, or naturally fell into place, with the rest of React. We think you'll love it.
## Dynamic Routing
When we say dynamic routing, we mean routing that takes place **as your app is rendering**, not in a configuration or convention outside of a running app. That means almost everything is a component in React Router. Here's a 60 second review of the API to see how it works:
First, grab yourself a `Router` component for the environment you're targeting and render it at the top of your app.
```jsx
// react-native
import { NativeRouter } from 'react-router-native'
// react-dom (what we'll use here)
import { BrowserRouter } from 'react-router-dom'
ReactDOM.render((
<BrowserRouter>
<App/>
</BrowserRouter>
), el)
```
Next, grab the link component to link to a new location:
```jsx
const App = () => (
<div>
<nav>
<Link to="/dashboard">Dashboard</Link>
</nav>
</div>
)
```
Finally, render a `Route` to show some UI when the user visits
`/dashboard`.
```jsx
const App = () => (
<div>
<nav>
<Link to="/dashboard">Dashboard</Link>
</nav>
<div>
<Route path="/dashboard" component={Dashboard}/>
</div>
</div>
)
```
The `Route` will render `<Dashboard {...props}/>` where `props` are some router specific things that look like `{ match, location, history }`. If the user is **not** at `/dashboard` then the `Route` will render `null`. That's pretty much all there is to it.
## Nested Routes
Lots of routers have some concept of "nested routes". If you've used versions of React Router previous to v4, you'll know it did too! When you move from a static route configuration to dynamic, rendered routes, how do you "nest routes"? Well, how do you nest a `div`?
```jsx
const App = () => (
<BrowserRouter>
{/* here's a div */}
<div>
{/* here's a Route */}
<Route path="/tacos" component={Tacos}/>
</div>
</BrowserRouter>
)
// when the url matches `/tacos` this component renders
const Tacos = ({ match }) => (
// here's a nested div
<div>
{/* here's a nested Route,
match.url helps us make a relative path */}
<Route
path={match.url + '/carnitas'}
component={Carnitas}
/>
</div>
)
```
See how the router has no "nesting" API? `Route` is just a component, just like `div`. So to nest a `Route` or a `div`, you just ... do it.
Let's get trickier.
## Responsive Routes
Consider a user navigates to `/invoices`. Your app is adaptive to different screen sizes, they have a narrow viewport, and so you only show them the list of invoices and a link to the invoice dashboard. They can navigate deeper from there.
```asciidoc
Small Screen
url: /invoices
+----------------------+
| |
| Dashboard |
| |
+----------------------+
| |
| Invoice 01 |
| |
+----------------------+
| |
| Invoice 02 |
| |
+----------------------+
| |
| Invoice 03 |
| |
+----------------------+
| |
| Invoice 04 |
| |
+----------------------+
```
On a larger screen we'd like to show a master-detail view where the navigation is on the left and the dashboard or specific invoices show up on the right.
```asciidoc
Large Screen
url: /invoices/dashboard
+----------------------+---------------------------+
| | |
| Dashboard | |
| | Unpaid: 5 |
+----------------------+ |
| | Balance: $53,543.00 |
| Invoice 01 | |
| | Past Due: 2 |
+----------------------+ |
| | |
| Invoice 02 | |
| | +-------------------+ |
+----------------------+ | | |
| | | + + + | |
| Invoice 03 | | | + | | | |
| | | | | | + | + | |
+----------------------+ | | | | | | | | |
| | +--+-+--+--+--+--+--+ |
| Invoice 04 | |
| | |
+----------------------+---------------------------+
```
Now pause for a minute and think about the `/invoices` url for both screen sizes. Is it even a valid route for a large screen? What should we put on the right side?
```asciidoc
Large Screen
url: /invoices
+----------------------+---------------------------+
| | |
| Dashboard | |
| | |
+----------------------+ |
| | |
| Invoice 01 | |
| | |
+----------------------+ |
| | |
| Invoice 02 | ??? |
| | |
+----------------------+ |
| | |
| Invoice 03 | |
| | |
+----------------------+ |
| | |
| Invoice 04 | |
| | |
+----------------------+---------------------------+
```
On a large screen, `/invoices` isn't a valid route, but on a small screen it is! To make things more interesting, consider somebody with a giant phone. They could be looking at `/invoices` in portrait orientation and then rotate their phone to landscape. Suddenly, we have enough room to show the master-detail UI, so you ought to redirect right then!
React Router's previous versions' static routes didn't really have a composable answer for this. When routing is dynamic, however, you can declaratively compose this functionality. If you start thinking about routing as UI, not as static configuration, your intuition will lead you to the following code:
```js
const App = () => (
<AppLayout>
<Route path="/invoices" component={Invoices}/>
</AppLayout>
)
const Invoices = () => (
<Layout>
{/* always show the nav */}
<InvoicesNav/>
<Media query={PRETTY_SMALL}>
{screenIsSmall => screenIsSmall
// small screen has no redirect
? <Switch>
<Route exact path="/invoices/dashboard" component={Dashboard}/>
<Route path="/invoices/:id" component={Invoice}/>
</Switch>
// large screen does!
: <Switch>
<Route exact path="/invoices/dashboard" component={Dashboard}/>
<Route path="/invoices/:id" component={Invoice}/>
<Redirect from="/invoices" to="/invoices/dashboard"/>
</Switch>
}
</Media>
</Layout>
)
```
As the user rotates their phone from portrait to landscape, this code will automatically redirect them to the dashboard. *The set of valid routes change depending on the dynamic nature of a mobile device in a user's hands*.
This is just one example. There are many others we could discuss but we'll sum it up with this advice: To get your intuition in line with React Router's, think about components, not static routes. Think about how to solve the problem with React's declarative composability because nearly every "React Router question" is probably a "React question".
| packages/react-router/docs/guides/philosophy.md | 0 | https://github.com/remix-run/react-router/commit/afebe674caff9751ce821de9c0bae544eaac8bf2 | [
0.0008947012247517705,
0.00019554309255909175,
0.00016223519924096763,
0.00016831410175655037,
0.00013247890456113964
] |
{
"id": 0,
"code_window": [
" \"dev-expression\",\n",
" \"transform-class-properties\",\n",
" [\"transform-object-rest-spread\", { \"useBuiltIns\": true }],\n",
" \"transform-export-default\"\n",
" ]\n",
" },\n",
" \"build-esm\": {\n",
" \"presets\": [[\"env\", { \"loose\": true, \"modules\": false }], \"react\"],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"transform-export-default\",\n",
" [\n",
" \"transform-imports\",\n",
" {\n",
" \"react-router\": {\n",
" \"transform\": \"react-router/${member}\"\n",
" }\n",
" }\n",
" ]\n"
],
"file_path": "packages/react-router-config/modules/.babelrc",
"type": "replace",
"edit_start_line_idx": 8
} | import React from "react";
import ReactDOM from "react-dom";
import MemoryRouter from "../MemoryRouter";
import StaticRouter from "../StaticRouter";
import Route from "../Route";
import withRouter from "../withRouter";
describe("withRouter", () => {
const node = document.createElement("div");
afterEach(() => {
ReactDOM.unmountComponentAtNode(node);
});
it("provides { match, location, history } props", () => {
let props;
const PropsChecker = withRouter(p => {
props = p;
return null;
});
ReactDOM.render(
<MemoryRouter>
<PropsChecker />
</MemoryRouter>,
node
);
expect(typeof props).toBe("object");
expect(typeof props.match).toBe("object");
expect(typeof props.location).toBe("object");
expect(typeof props.history).toBe("object");
});
it("provides the parent match as a prop to the wrapped component", () => {
let parentMatch, props;
const PropsChecker = withRouter(p => {
props = p;
return null;
});
ReactDOM.render(
<MemoryRouter initialEntries={["/bubblegum"]}>
<Route
path="/:flavor"
render={({ match }) => {
parentMatch = match;
return <PropsChecker />;
}}
/>
</MemoryRouter>,
node
);
expect(typeof parentMatch).toBe("object");
expect(typeof props).toBe("object");
expect(props.match).toBe(parentMatch);
});
it("works when parent match is null", () => {
let parentMatch, props;
const PropChecker = withRouter(p => {
props = p;
return null;
});
ReactDOM.render(
<MemoryRouter initialEntries={["/somepath"]}>
<Route
path="/no-match"
children={({ match }) => {
parentMatch = match;
return <PropChecker />;
}}
/>
</MemoryRouter>,
node
);
expect(parentMatch).toBe(null);
expect(typeof props).toBe("object");
expect(props.match).toBe(null);
});
describe("inside a <StaticRouter>", () => {
it("provides the staticContext prop", () => {
let props;
const PropsChecker = withRouter(p => {
props = p;
return null;
});
const context = {};
ReactDOM.render(
<StaticRouter context={context}>
<Route component={PropsChecker} />
</StaticRouter>,
node
);
expect(typeof props).toBe("object");
expect(typeof props.staticContext).toBe("object");
expect(props.staticContext).toBe(context);
});
});
it("exposes the wrapped component as WrappedComponent", () => {
const Component = () => <div />;
const decorated = withRouter(Component);
expect(decorated.WrappedComponent).toBe(Component);
});
it("exposes the instance of the wrapped component via wrappedComponentRef", () => {
class WrappedComponent extends React.Component {
render() {
return null;
}
}
const Component = withRouter(WrappedComponent);
let ref;
ReactDOM.render(
<MemoryRouter initialEntries={["/bubblegum"]}>
<Route
path="/bubblegum"
render={() => <Component wrappedComponentRef={r => (ref = r)} />}
/>
</MemoryRouter>,
node
);
expect(ref instanceof WrappedComponent).toBe(true);
});
it("hoists non-react statics from the wrapped component", () => {
class Component extends React.Component {
static foo() {
return "bar";
}
render() {
return null;
}
}
Component.hello = "world";
const decorated = withRouter(Component);
expect(decorated.hello).toBe("world");
expect(typeof decorated.foo).toBe("function");
expect(decorated.foo()).toBe("bar");
});
});
| packages/react-router/modules/__tests__/withRouter-test.js | 0 | https://github.com/remix-run/react-router/commit/afebe674caff9751ce821de9c0bae544eaac8bf2 | [
0.0001735904806992039,
0.0001705529575701803,
0.00016795193369034678,
0.00017013915930874646,
0.000001786391749192262
] |
{
"id": 0,
"code_window": [
" \"dev-expression\",\n",
" \"transform-class-properties\",\n",
" [\"transform-object-rest-spread\", { \"useBuiltIns\": true }],\n",
" \"transform-export-default\"\n",
" ]\n",
" },\n",
" \"build-esm\": {\n",
" \"presets\": [[\"env\", { \"loose\": true, \"modules\": false }], \"react\"],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"transform-export-default\",\n",
" [\n",
" \"transform-imports\",\n",
" {\n",
" \"react-router\": {\n",
" \"transform\": \"react-router/${member}\"\n",
" }\n",
" }\n",
" ]\n"
],
"file_path": "packages/react-router-config/modules/.babelrc",
"type": "replace",
"edit_start_line_idx": 8
} | import { matchPath, Router } from "react-router";
function matchRoutes(routes, pathname, /*not public API*/ branch = []) {
routes.some(route => {
const match = route.path
? matchPath(pathname, route)
: branch.length
? branch[branch.length - 1].match // use parent match
: Router.computeRootMatch(pathname); // use default "root" match
if (match) {
branch.push({ route, match });
if (route.routes) {
matchRoutes(route.routes, pathname, branch);
}
}
return match;
});
return branch;
}
export default matchRoutes;
| packages/react-router-config/modules/matchRoutes.js | 0 | https://github.com/remix-run/react-router/commit/afebe674caff9751ce821de9c0bae544eaac8bf2 | [
0.00017236189160030335,
0.0001694734237389639,
0.00016763947496656328,
0.00016841893375385553,
0.0000020670884168794146
] |
{
"id": 1,
"code_window": [
" \"dev-expression\",\n",
" \"transform-class-properties\",\n",
" [\"transform-object-rest-spread\", { \"useBuiltIns\": true }],\n",
" \"transform-export-default\"\n",
" ]\n",
" },\n",
" \"test\": {\n",
" \"presets\": [[\"env\", { \"loose\": true }], \"react\"],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"transform-export-default\",\n",
" [\n",
" \"transform-imports\",\n",
" {\n",
" \"react-router\": {\n",
" \"transform\": \"react-router/es/${member}\"\n",
" }\n",
" }\n",
" ]\n"
],
"file_path": "packages/react-router-config/modules/.babelrc",
"type": "replace",
"edit_start_line_idx": 17
} | {
"env": {
"build-cjs": {
"presets": [["env", { "loose": true }], "react"],
"plugins": [
"dev-expression",
"transform-class-properties",
["transform-object-rest-spread", { "useBuiltIns": true }],
"transform-export-default"
]
},
"build-esm": {
"presets": [["env", { "loose": true, "modules": false }], "react"],
"plugins": [
"dev-expression",
"transform-class-properties",
["transform-object-rest-spread", { "useBuiltIns": true }],
"transform-export-default",
[
"transform-imports",
{
"react-router": {
"transform": "react-router/modules/${member}"
}
}
]
]
},
"test": {
"presets": [["env", { "loose": true }], "react"],
"plugins": [
"dev-expression",
"transform-class-properties",
["transform-object-rest-spread", { "useBuiltIns": true }],
"transform-export-default",
[
"transform-imports",
{
"react-router": {
"transform": "react-router/modules/${member}"
}
}
]
]
}
}
}
| packages/react-router-dom/modules/.babelrc | 1 | https://github.com/remix-run/react-router/commit/afebe674caff9751ce821de9c0bae544eaac8bf2 | [
0.9611210823059082,
0.4420534074306488,
0.00016971227887552232,
0.5443806052207947,
0.38417404890060425
] |
{
"id": 1,
"code_window": [
" \"dev-expression\",\n",
" \"transform-class-properties\",\n",
" [\"transform-object-rest-spread\", { \"useBuiltIns\": true }],\n",
" \"transform-export-default\"\n",
" ]\n",
" },\n",
" \"test\": {\n",
" \"presets\": [[\"env\", { \"loose\": true }], \"react\"],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"transform-export-default\",\n",
" [\n",
" \"transform-imports\",\n",
" {\n",
" \"react-router\": {\n",
" \"transform\": \"react-router/es/${member}\"\n",
" }\n",
" }\n",
" ]\n"
],
"file_path": "packages/react-router-config/modules/.babelrc",
"type": "replace",
"edit_start_line_idx": 17
} | <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.reactrouternative"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="22" />
<application
android:name=".MainApplication"
android:allowBackup="true"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="router"
android:host="router" />
</intent-filter>
</activity>
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
</application>
</manifest>
| packages/react-router-native/android/app/src/main/AndroidManifest.xml | 0 | https://github.com/remix-run/react-router/commit/afebe674caff9751ce821de9c0bae544eaac8bf2 | [
0.00017046106222551316,
0.0001698740670690313,
0.00016929415869526565,
0.00016987050184980035,
4.950926495439489e-7
] |
{
"id": 1,
"code_window": [
" \"dev-expression\",\n",
" \"transform-class-properties\",\n",
" [\"transform-object-rest-spread\", { \"useBuiltIns\": true }],\n",
" \"transform-export-default\"\n",
" ]\n",
" },\n",
" \"test\": {\n",
" \"presets\": [[\"env\", { \"loose\": true }], \"react\"],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"transform-export-default\",\n",
" [\n",
" \"transform-imports\",\n",
" {\n",
" \"react-router\": {\n",
" \"transform\": \"react-router/es/${member}\"\n",
" }\n",
" }\n",
" ]\n"
],
"file_path": "packages/react-router-config/modules/.babelrc",
"type": "replace",
"edit_start_line_idx": 17
} | import React from "react";
// don't want the shimmed one
// eslint-disable-next-line
import BrowserRouter from "../../../packages/react-router-dom/BrowserRouter";
// this stuff is shimmed, see ReactRouterDOMShim.js for more details
import { Switch, Route } from "react-router-dom";
import DelegateMarkdownLinks from "./DelegateMarkdownLinks";
import Home from "./Home";
import Environment from "./Environment";
const base = document.querySelector("base");
const baseHref = base ? base.getAttribute("href") : "/";
const App = () => (
<BrowserRouter basename={baseHref.replace(/\/$/, "")}>
<DelegateMarkdownLinks>
<Switch>
<Route path="/" exact={true} component={Home} />
<Route path="/:environment" component={Environment} />
</Switch>
</DelegateMarkdownLinks>
</BrowserRouter>
);
export default App;
| website/modules/components/App.js | 0 | https://github.com/remix-run/react-router/commit/afebe674caff9751ce821de9c0bae544eaac8bf2 | [
0.00022891817206982523,
0.00018863577861338854,
0.00016809822409413755,
0.0001688909251242876,
0.000028485796065069735
] |
{
"id": 1,
"code_window": [
" \"dev-expression\",\n",
" \"transform-class-properties\",\n",
" [\"transform-object-rest-spread\", { \"useBuiltIns\": true }],\n",
" \"transform-export-default\"\n",
" ]\n",
" },\n",
" \"test\": {\n",
" \"presets\": [[\"env\", { \"loose\": true }], \"react\"],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"transform-export-default\",\n",
" [\n",
" \"transform-imports\",\n",
" {\n",
" \"react-router\": {\n",
" \"transform\": \"react-router/es/${member}\"\n",
" }\n",
" }\n",
" ]\n"
],
"file_path": "packages/react-router-config/modules/.babelrc",
"type": "replace",
"edit_start_line_idx": 17
} | # <Router>
The common low-level interface for all router components. Typically apps will use one of the high-level routers instead:
- [`<BrowserRouter>`](../../../react-router-dom/docs/api/BrowserRouter.md)
- [`<HashRouter>`](../../../react-router-dom/docs/api/HashRouter.md)
- [`<MemoryRouter>`](./MemoryRouter.md)
- [`<NativeRouter>`](../../../react-router-native/docs/api/NativeRouter.md)
- [`<StaticRouter>`](./StaticRouter.md)
The most common use-case for using the low-level `<Router>` is to
synchronize a custom history with a state management lib like Redux or Mobx. Note that this is not required to use state management libs alongside React Router, it's only for deep integration.
```jsx
import { Router } from 'react-router'
import createBrowserHistory from 'history/createBrowserHistory'
const history = createBrowserHistory()
<Router history={history}>
<App/>
</Router>
```
## history: object
A [`history`](https://github.com/ReactTraining/history) object to use for navigation.
```jsx
import createBrowserHistory from 'history/createBrowserHistory'
const customHistory = createBrowserHistory()
<Router history={customHistory}/>
```
## children: node
A [single child element](https://facebook.github.io/react/docs/react-api.html#react.children.only) to render.
```jsx
<Router>
<App/>
</Router>
```
| packages/react-router/docs/api/Router.md | 0 | https://github.com/remix-run/react-router/commit/afebe674caff9751ce821de9c0bae544eaac8bf2 | [
0.00016787700587883592,
0.0001664759183768183,
0.00016381952445954084,
0.00016691215569153428,
0.000001384329266329587
] |
{
"id": 2,
"code_window": [
" \"plugins\": [\n",
" \"dev-expression\",\n",
" \"transform-class-properties\",\n",
" [\"transform-object-rest-spread\", { \"useBuiltIns\": true }],\n",
" \"transform-export-default\"\n",
" ]\n",
" },\n",
" \"build-esm\": {\n",
" \"presets\": [[\"env\", { \"loose\": true, \"modules\": false }], \"react\"],\n",
" \"plugins\": [\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"transform-export-default\",\n",
" [\n",
" \"transform-imports\",\n",
" {\n",
" \"react-router\": {\n",
" \"transform\": \"react-router/${member}\"\n",
" }\n",
" }\n",
" ]\n"
],
"file_path": "packages/react-router-dom/modules/.babelrc",
"type": "replace",
"edit_start_line_idx": 8
} | {
"env": {
"build-cjs": {
"presets": [["env", { "loose": true }], "react"],
"plugins": [
"dev-expression",
"transform-class-properties",
["transform-object-rest-spread", { "useBuiltIns": true }],
"transform-export-default"
]
},
"build-esm": {
"presets": [["env", { "loose": true, "modules": false }], "react"],
"plugins": [
"dev-expression",
"transform-class-properties",
["transform-object-rest-spread", { "useBuiltIns": true }],
"transform-export-default"
]
},
"test": {
"presets": [["env", { "loose": true }], "react"],
"plugins": [
"dev-expression",
"transform-class-properties",
["transform-object-rest-spread", { "useBuiltIns": true }],
"transform-export-default",
[
"transform-imports",
{
"react-router": {
"transform": "react-router/modules/${member}"
}
}
]
]
}
}
}
| packages/react-router-config/modules/.babelrc | 1 | https://github.com/remix-run/react-router/commit/afebe674caff9751ce821de9c0bae544eaac8bf2 | [
0.9964249730110168,
0.6206053495407104,
0.00016631513426546007,
0.7429150342941284,
0.4090607464313507
] |
{
"id": 2,
"code_window": [
" \"plugins\": [\n",
" \"dev-expression\",\n",
" \"transform-class-properties\",\n",
" [\"transform-object-rest-spread\", { \"useBuiltIns\": true }],\n",
" \"transform-export-default\"\n",
" ]\n",
" },\n",
" \"build-esm\": {\n",
" \"presets\": [[\"env\", { \"loose\": true, \"modules\": false }], \"react\"],\n",
" \"plugins\": [\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"transform-export-default\",\n",
" [\n",
" \"transform-imports\",\n",
" {\n",
" \"react-router\": {\n",
" \"transform\": \"react-router/${member}\"\n",
" }\n",
" }\n",
" ]\n"
],
"file_path": "packages/react-router-dom/modules/.babelrc",
"type": "replace",
"edit_start_line_idx": 8
} | # matchPath
Re-exported from core [`matchPath`](../../../react-router/docs/api/matchPath.md)
| packages/react-router-native/docs/api/matchPath.md | 0 | https://github.com/remix-run/react-router/commit/afebe674caff9751ce821de9c0bae544eaac8bf2 | [
0.00016759982099756598,
0.00016759982099756598,
0.00016759982099756598,
0.00016759982099756598,
0
] |
{
"id": 2,
"code_window": [
" \"plugins\": [\n",
" \"dev-expression\",\n",
" \"transform-class-properties\",\n",
" [\"transform-object-rest-spread\", { \"useBuiltIns\": true }],\n",
" \"transform-export-default\"\n",
" ]\n",
" },\n",
" \"build-esm\": {\n",
" \"presets\": [[\"env\", { \"loose\": true, \"modules\": false }], \"react\"],\n",
" \"plugins\": [\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"transform-export-default\",\n",
" [\n",
" \"transform-imports\",\n",
" {\n",
" \"react-router\": {\n",
" \"transform\": \"react-router/${member}\"\n",
" }\n",
" }\n",
" ]\n"
],
"file_path": "packages/react-router-dom/modules/.babelrc",
"type": "replace",
"edit_start_line_idx": 8
} | import React from "react";
import {
BrowserRouter as Router,
Route,
Link,
Redirect,
withRouter
} from "react-router-dom";
////////////////////////////////////////////////////////////
// 1. Click the public page
// 2. Click the protected page
// 3. Log in
// 4. Click the back button, note the URL each time
const AuthExample = () => (
<Router>
<div>
<AuthButton />
<ul>
<li>
<Link to="/public">Public Page</Link>
</li>
<li>
<Link to="/protected">Protected Page</Link>
</li>
</ul>
<Route path="/public" component={Public} />
<Route path="/login" component={Login} />
<PrivateRoute path="/protected" component={Protected} />
</div>
</Router>
);
const fakeAuth = {
isAuthenticated: false,
authenticate(cb) {
this.isAuthenticated = true;
setTimeout(cb, 100); // fake async
},
signout(cb) {
this.isAuthenticated = false;
setTimeout(cb, 100);
}
};
const AuthButton = withRouter(
({ history }) =>
fakeAuth.isAuthenticated ? (
<p>
Welcome!{" "}
<button
onClick={() => {
fakeAuth.signout(() => history.push("/"));
}}
>
Sign out
</button>
</p>
) : (
<p>You are not logged in.</p>
)
);
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={props =>
fakeAuth.isAuthenticated ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/login",
state: { from: props.location }
}}
/>
)
}
/>
);
const Public = () => <h3>Public</h3>;
const Protected = () => <h3>Protected</h3>;
class Login extends React.Component {
state = {
redirectToReferrer: false
};
login = () => {
fakeAuth.authenticate(() => {
this.setState({ redirectToReferrer: true });
});
};
render() {
const { from } = this.props.location.state || { from: { pathname: "/" } };
const { redirectToReferrer } = this.state;
if (redirectToReferrer) {
return <Redirect to={from} />;
}
return (
<div>
<p>You must log in to view the page at {from.pathname}</p>
<button onClick={this.login}>Log in</button>
</div>
);
}
}
export default AuthExample;
| website/modules/examples/Auth.js | 0 | https://github.com/remix-run/react-router/commit/afebe674caff9751ce821de9c0bae544eaac8bf2 | [
0.00017233099788427353,
0.00016822652833070606,
0.00016321877774316818,
0.00016901048365980387,
0.000002654030367921223
] |
{
"id": 2,
"code_window": [
" \"plugins\": [\n",
" \"dev-expression\",\n",
" \"transform-class-properties\",\n",
" [\"transform-object-rest-spread\", { \"useBuiltIns\": true }],\n",
" \"transform-export-default\"\n",
" ]\n",
" },\n",
" \"build-esm\": {\n",
" \"presets\": [[\"env\", { \"loose\": true, \"modules\": false }], \"react\"],\n",
" \"plugins\": [\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"transform-export-default\",\n",
" [\n",
" \"transform-imports\",\n",
" {\n",
" \"react-router\": {\n",
" \"transform\": \"react-router/${member}\"\n",
" }\n",
" }\n",
" ]\n"
],
"file_path": "packages/react-router-dom/modules/.babelrc",
"type": "replace",
"edit_start_line_idx": 8
} | MIT License
Copyright (c) React Training 2016-2018
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
| LICENSE | 0 | https://github.com/remix-run/react-router/commit/afebe674caff9751ce821de9c0bae544eaac8bf2 | [
0.00017275776190217584,
0.00016978247731458396,
0.00016808442887850106,
0.00016850519750732929,
0.000002110855348291807
] |
{
"id": 3,
"code_window": [
" [\n",
" \"transform-imports\",\n",
" {\n",
" \"react-router\": {\n",
" \"transform\": \"react-router/modules/${member}\"\n",
" }\n",
" }\n",
" ]\n",
" ]\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"transform\": \"react-router/es/${member}\"\n"
],
"file_path": "packages/react-router-dom/modules/.babelrc",
"type": "replace",
"edit_start_line_idx": 22
} | {
"env": {
"build-cjs": {
"presets": [["env", { "loose": true }], "react"],
"plugins": [
"dev-expression",
"transform-class-properties",
["transform-object-rest-spread", { "useBuiltIns": true }],
"transform-export-default"
]
},
"build-esm": {
"presets": [["env", { "loose": true, "modules": false }], "react"],
"plugins": [
"dev-expression",
"transform-class-properties",
["transform-object-rest-spread", { "useBuiltIns": true }],
"transform-export-default"
]
},
"test": {
"presets": [["env", { "loose": true }], "react"],
"plugins": [
"dev-expression",
"transform-class-properties",
["transform-object-rest-spread", { "useBuiltIns": true }],
"transform-export-default",
[
"transform-imports",
{
"react-router": {
"transform": "react-router/modules/${member}"
}
}
]
]
}
}
}
| packages/react-router-config/modules/.babelrc | 1 | https://github.com/remix-run/react-router/commit/afebe674caff9751ce821de9c0bae544eaac8bf2 | [
0.4329244792461395,
0.1084151566028595,
0.0001683184236753732,
0.000283917470369488,
0.18735554814338684
] |
{
"id": 3,
"code_window": [
" [\n",
" \"transform-imports\",\n",
" {\n",
" \"react-router\": {\n",
" \"transform\": \"react-router/modules/${member}\"\n",
" }\n",
" }\n",
" ]\n",
" ]\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"transform\": \"react-router/es/${member}\"\n"
],
"file_path": "packages/react-router-dom/modules/.babelrc",
"type": "replace",
"edit_start_line_idx": 22
} | /**
* https://github.com/gre/bezier-easing
* BezierEasing - use bezier curve for transition easing function
* by Gaëtan Renaudeau 2014 - 2015 – MIT License
* @nolint
*/
// These values are established by empiricism with tests (tradeoff: performance VS precision)
var NEWTON_ITERATIONS = 4;
var NEWTON_MIN_SLOPE = 0.001;
var SUBDIVISION_PRECISION = 0.0000001;
var SUBDIVISION_MAX_ITERATIONS = 10;
var kSplineTableSize = 11;
var kSampleStepSize = 1.0 / (kSplineTableSize - 1.0);
var float32ArraySupported = typeof Float32Array === "function";
function A(aA1, aA2) {
return 1.0 - 3.0 * aA2 + 3.0 * aA1;
}
function B(aA1, aA2) {
return 3.0 * aA2 - 6.0 * aA1;
}
function C(aA1) {
return 3.0 * aA1;
}
// Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2.
function calcBezier(aT, aA1, aA2) {
return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;
}
// Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2.
function getSlope(aT, aA1, aA2) {
return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
}
function binarySubdivide(aX, aA, aB, mX1, mX2) {
var currentX,
currentT,
i = 0;
do {
currentT = aA + (aB - aA) / 2.0;
currentX = calcBezier(currentT, mX1, mX2) - aX;
if (currentX > 0.0) {
aB = currentT;
} else {
aA = currentT;
}
} while (
Math.abs(currentX) > SUBDIVISION_PRECISION &&
++i < SUBDIVISION_MAX_ITERATIONS
);
return currentT;
}
function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) {
for (var i = 0; i < NEWTON_ITERATIONS; ++i) {
var currentSlope = getSlope(aGuessT, mX1, mX2);
if (currentSlope === 0.0) {
return aGuessT;
}
var currentX = calcBezier(aGuessT, mX1, mX2) - aX;
aGuessT -= currentX / currentSlope;
}
return aGuessT;
}
module.exports = function bezier(mX1, mY1, mX2, mY2) {
if (!(0 <= mX1 && mX1 <= 1 && 0 <= mX2 && mX2 <= 1)) {
// eslint-disable-line yoda
throw new Error("bezier x values must be in [0, 1] range");
}
// Precompute samples table
var sampleValues = float32ArraySupported
? new Float32Array(kSplineTableSize)
: new Array(kSplineTableSize);
if (mX1 !== mY1 || mX2 !== mY2) {
for (var i = 0; i < kSplineTableSize; ++i) {
sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
}
}
function getTForX(aX) {
var intervalStart = 0.0;
var currentSample = 1;
var lastSample = kSplineTableSize - 1;
for (
;
currentSample !== lastSample && sampleValues[currentSample] <= aX;
++currentSample
) {
intervalStart += kSampleStepSize;
}
--currentSample;
// Interpolate to provide an initial guess for t
var dist =
(aX - sampleValues[currentSample]) /
(sampleValues[currentSample + 1] - sampleValues[currentSample]);
var guessForT = intervalStart + dist * kSampleStepSize;
var initialSlope = getSlope(guessForT, mX1, mX2);
if (initialSlope >= NEWTON_MIN_SLOPE) {
return newtonRaphsonIterate(aX, guessForT, mX1, mX2);
} else if (initialSlope === 0.0) {
return guessForT;
} else {
return binarySubdivide(
aX,
intervalStart,
intervalStart + kSampleStepSize,
mX1,
mX2
);
}
}
return function BezierEasing(x) {
if (mX1 === mY1 && mX2 === mY2) {
return x; // linear
}
// Because JavaScript number are imprecise, we should guarantee the extremes are right.
if (x === 0) {
return 0;
}
if (x === 1) {
return 1;
}
return calcBezier(getTForX(x), mY1, mY2);
};
};
| website/modules/animated/bezier.js | 0 | https://github.com/remix-run/react-router/commit/afebe674caff9751ce821de9c0bae544eaac8bf2 | [
0.0002903994172811508,
0.00018306532001588494,
0.00016489192785229534,
0.00017236506391782314,
0.000032982010452542454
] |
{
"id": 3,
"code_window": [
" [\n",
" \"transform-imports\",\n",
" {\n",
" \"react-router\": {\n",
" \"transform\": \"react-router/modules/${member}\"\n",
" }\n",
" }\n",
" ]\n",
" ]\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"transform\": \"react-router/es/${member}\"\n"
],
"file_path": "packages/react-router-dom/modules/.babelrc",
"type": "replace",
"edit_start_line_idx": 22
} | import React from "react";
import ReactDOM from "react-dom";
import MemoryRouter from "../MemoryRouter";
import Redirect from "../Redirect";
import Route from "../Route";
import Switch from "../Switch";
describe("A <Redirect>", () => {
const node = document.createElement("div");
afterEach(() => {
ReactDOM.unmountComponentAtNode(node);
});
describe("inside a <Switch>", () => {
it("automatically interpolates params", () => {
let params;
ReactDOM.render(
<MemoryRouter initialEntries={["/users/mjackson/messages/123"]}>
<Switch>
<Redirect
from="/users/:username/messages/:messageId"
to="/:username/messages/:messageId"
/>
<Route
path="/:username/messages/:messageId"
render={({ match }) => {
params = match.params;
return null;
}}
/>
</Switch>
</MemoryRouter>,
node
);
expect(params).toMatchObject({
username: "mjackson",
messageId: "123"
});
});
});
});
| packages/react-router/modules/__tests__/Redirect-test.js | 0 | https://github.com/remix-run/react-router/commit/afebe674caff9751ce821de9c0bae544eaac8bf2 | [
0.00017379435303155333,
0.00017009172006510198,
0.00016794985276646912,
0.00016966421389952302,
0.0000020251607111276826
] |
{
"id": 3,
"code_window": [
" [\n",
" \"transform-imports\",\n",
" {\n",
" \"react-router\": {\n",
" \"transform\": \"react-router/modules/${member}\"\n",
" }\n",
" }\n",
" ]\n",
" ]\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"transform\": \"react-router/es/${member}\"\n"
],
"file_path": "packages/react-router-dom/modules/.babelrc",
"type": "replace",
"edit_start_line_idx": 22
} | import babel from "rollup-plugin-babel";
import uglify from "rollup-plugin-uglify";
const config = {
output: {
format: "umd",
name: "ReactRouterRedux",
globals: {
react: "React",
"prop-types": "PropTypes",
"react-router": "ReactRouter"
}
},
external: ["react", "prop-types", "react-router"],
plugins: [
babel({
exclude: "node_modules/**",
plugins: ["external-helpers"]
})
]
};
if (process.env.NODE_ENV === "production") {
config.plugins.push(
uglify({
compress: {
pure_getters: true,
unsafe: true,
unsafe_comps: true,
warnings: false
}
})
);
}
export default config;
| packages/react-router-redux/rollup.config.js | 0 | https://github.com/remix-run/react-router/commit/afebe674caff9751ce821de9c0bae544eaac8bf2 | [
0.00020964627037756145,
0.00017900089733302593,
0.00016391905955970287,
0.00017121911514550447,
0.00001794281524780672
] |
{
"id": 0,
"code_window": [
"\t}, cell: ICell) {\n",
"\t\tlet result: { content: string; mode: ILanguageSelection } | undefined = undefined;\n",
"\n",
"\t\tconst mode = this._languageService.createById('json');\n",
"\t\tconst op = cell.outputs.find(op => op.outputId === data.outputId);\n",
"\t\tconst streamOutputData = this.parseStreamOutput(op);\n",
"\t\tif (streamOutputData) {\n",
"\t\t\tresult = streamOutputData;\n",
"\t\t\treturn result;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst op = cell.outputs.find(op => op.outputId === data.outputId || op.alternativeOutputId === data.outputId);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/notebook.contribution.ts",
"type": "replace",
"edit_start_line_idx": 457
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Schemas } from 'vs/base/common/network';
import { IDisposable, Disposable, DisposableStore, dispose } from 'vs/base/common/lifecycle';
import { parse } from 'vs/base/common/marshalling';
import { extname, isEqual } from 'vs/base/common/resources';
import { assertType } from 'vs/base/common/types';
import { URI } from 'vs/base/common/uri';
import { toFormattedString } from 'vs/base/common/jsonFormatter';
import { ITextModel, ITextBufferFactory, DefaultEndOfLine, ITextBuffer } from 'vs/editor/common/model';
import { IModelService } from 'vs/editor/common/services/model';
import { ILanguageSelection, ILanguageService } from 'vs/editor/common/languages/language';
import { ITextModelContentProvider, ITextModelService } from 'vs/editor/common/services/resolverService';
import * as nls from 'vs/nls';
import { Extensions, IConfigurationPropertySchema, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { Registry } from 'vs/platform/registry/common/platform';
import { EditorPaneDescriptor, IEditorPaneRegistry } from 'vs/workbench/browser/editor';
import { Extensions as WorkbenchExtensions, IWorkbenchContribution, IWorkbenchContributionsRegistry } from 'vs/workbench/common/contributions';
import { IEditorSerializer, IEditorFactoryRegistry, EditorExtensions } from 'vs/workbench/common/editor';
import { EditorInput } from 'vs/workbench/common/editor/editorInput';
import { NotebookEditor } from 'vs/workbench/contrib/notebook/browser/notebookEditor';
import { NotebookEditorInput, NotebookEditorInputOptions } from 'vs/workbench/contrib/notebook/common/notebookEditorInput';
import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';
import { NotebookService } from 'vs/workbench/contrib/notebook/browser/services/notebookServiceImpl';
import { CellKind, CellUri, IResolvedNotebookEditorModel, NotebookWorkingCopyTypeIdentifier, NotebookSetting, ICellOutput, ICell } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IUndoRedoService } from 'vs/platform/undoRedo/common/undoRedo';
import { INotebookEditorModelResolverService } from 'vs/workbench/contrib/notebook/common/notebookEditorModelResolverService';
import { NotebookDiffEditorInput } from 'vs/workbench/contrib/notebook/common/notebookDiffEditorInput';
import { NotebookTextDiffEditor } from 'vs/workbench/contrib/notebook/browser/diff/notebookDiffEditor';
import { INotebookEditorWorkerService } from 'vs/workbench/contrib/notebook/common/services/notebookWorkerService';
import { NotebookEditorWorkerServiceImpl } from 'vs/workbench/contrib/notebook/browser/services/notebookWorkerServiceImpl';
import { INotebookCellStatusBarService } from 'vs/workbench/contrib/notebook/common/notebookCellStatusBarService';
import { NotebookCellStatusBarService } from 'vs/workbench/contrib/notebook/browser/services/notebookCellStatusBarServiceImpl';
import { INotebookEditorService } from 'vs/workbench/contrib/notebook/browser/services/notebookEditorService';
import { NotebookEditorWidgetService } from 'vs/workbench/contrib/notebook/browser/services/notebookEditorServiceImpl';
import { IJSONContributionRegistry, Extensions as JSONExtensions } from 'vs/platform/jsonschemas/common/jsonContributionRegistry';
import { IJSONSchema, IJSONSchemaMap } from 'vs/base/common/jsonSchema';
import { Event } from 'vs/base/common/event';
import { getFormattedMetadataJSON, getStreamOutputData } from 'vs/workbench/contrib/notebook/browser/diff/diffElementViewModel';
import { NotebookModelResolverServiceImpl } from 'vs/workbench/contrib/notebook/common/notebookEditorModelResolverServiceImpl';
import { INotebookKernelHistoryService, INotebookKernelService } from 'vs/workbench/contrib/notebook/common/notebookKernelService';
import { NotebookKernelService } from 'vs/workbench/contrib/notebook/browser/services/notebookKernelServiceImpl';
import { IWorkingCopyIdentifier } from 'vs/workbench/services/workingCopy/common/workingCopy';
import { IResourceEditorInput } from 'vs/platform/editor/common/editor';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IWorkingCopyEditorHandler, IWorkingCopyEditorService } from 'vs/workbench/services/workingCopy/common/workingCopyEditorService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ILabelService } from 'vs/platform/label/common/label';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { NotebookRendererMessagingService } from 'vs/workbench/contrib/notebook/browser/services/notebookRendererMessagingServiceImpl';
import { INotebookRendererMessagingService } from 'vs/workbench/contrib/notebook/common/notebookRendererMessagingService';
// Editor Controller
import 'vs/workbench/contrib/notebook/browser/controller/coreActions';
import 'vs/workbench/contrib/notebook/browser/controller/insertCellActions';
import 'vs/workbench/contrib/notebook/browser/controller/executeActions';
import 'vs/workbench/contrib/notebook/browser/controller/layoutActions';
import 'vs/workbench/contrib/notebook/browser/controller/editActions';
import 'vs/workbench/contrib/notebook/browser/controller/cellOutputActions';
import 'vs/workbench/contrib/notebook/browser/controller/apiActions';
import 'vs/workbench/contrib/notebook/browser/controller/foldingController';
// Editor Contribution
import 'vs/workbench/contrib/notebook/browser/contrib/clipboard/notebookClipboard';
import 'vs/workbench/contrib/notebook/browser/contrib/find/notebookFind';
import 'vs/workbench/contrib/notebook/browser/contrib/format/formatting';
import 'vs/workbench/contrib/notebook/browser/contrib/saveParticipants/saveParticipants';
import 'vs/workbench/contrib/notebook/browser/contrib/gettingStarted/notebookGettingStarted';
import 'vs/workbench/contrib/notebook/browser/contrib/layout/layoutActions';
import 'vs/workbench/contrib/notebook/browser/contrib/marker/markerProvider';
import 'vs/workbench/contrib/notebook/browser/contrib/navigation/arrow';
import 'vs/workbench/contrib/notebook/browser/contrib/outline/notebookOutline';
import 'vs/workbench/contrib/notebook/browser/contrib/profile/notebookProfile';
import 'vs/workbench/contrib/notebook/browser/contrib/cellStatusBar/statusBarProviders';
import 'vs/workbench/contrib/notebook/browser/contrib/cellStatusBar/contributedStatusBarItemController';
import 'vs/workbench/contrib/notebook/browser/contrib/cellStatusBar/executionStatusBarItemController';
import 'vs/workbench/contrib/notebook/browser/contrib/editorStatusBar/editorStatusBar';
import 'vs/workbench/contrib/notebook/browser/contrib/undoRedo/notebookUndoRedo';
import 'vs/workbench/contrib/notebook/browser/contrib/cellCommands/cellCommands';
import 'vs/workbench/contrib/notebook/browser/contrib/viewportWarmup/viewportWarmup';
import 'vs/workbench/contrib/notebook/browser/contrib/troubleshoot/layout';
import 'vs/workbench/contrib/notebook/browser/contrib/debug/notebookBreakpoints';
import 'vs/workbench/contrib/notebook/browser/contrib/debug/notebookCellPausing';
import 'vs/workbench/contrib/notebook/browser/contrib/debug/notebookDebugDecorations';
import 'vs/workbench/contrib/notebook/browser/contrib/execute/executionEditorProgress';
import 'vs/workbench/contrib/notebook/browser/contrib/kernelDetection/notebookKernelDetection';
// Diff Editor Contribution
import 'vs/workbench/contrib/notebook/browser/diff/notebookDiffActions';
// Services
import { editorOptionsRegistry } from 'vs/editor/common/config/editorOptions';
import { NotebookExecutionStateService } from 'vs/workbench/contrib/notebook/browser/services/notebookExecutionStateServiceImpl';
import { NotebookExecutionService } from 'vs/workbench/contrib/notebook/browser/services/notebookExecutionServiceImpl';
import { INotebookExecutionService } from 'vs/workbench/contrib/notebook/common/notebookExecutionService';
import { INotebookKeymapService } from 'vs/workbench/contrib/notebook/common/notebookKeymapService';
import { NotebookKeymapService } from 'vs/workbench/contrib/notebook/browser/services/notebookKeymapServiceImpl';
import { PLAINTEXT_LANGUAGE_ID } from 'vs/editor/common/languages/modesRegistry';
import { INotebookExecutionStateService } from 'vs/workbench/contrib/notebook/common/notebookExecutionStateService';
import { ILanguageFeaturesService } from 'vs/editor/common/services/languageFeatures';
import { NotebookInfo } from 'vs/editor/common/languageFeatureRegistry';
import { COMMENTEDITOR_DECORATION_KEY } from 'vs/workbench/contrib/comments/browser/commentReply';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import { NotebookKernelHistoryService } from 'vs/workbench/contrib/notebook/browser/services/notebookKernelHistoryServiceImpl';
import { INotebookLoggingService } from 'vs/workbench/contrib/notebook/common/notebookLoggingService';
import { NotebookLoggingService } from 'vs/workbench/contrib/notebook/browser/services/notebookLoggingServiceImpl';
import product from 'vs/platform/product/common/product';
import { NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_OUTPUT_FOCUSED } from 'vs/workbench/contrib/notebook/common/notebookContextKeys';
import { runAccessibilityHelpAction, showAccessibleOutput } from 'vs/workbench/contrib/notebook/browser/notebookAccessibility';
import { IAccessibleViewService } from 'vs/workbench/contrib/accessibility/browser/accessibleView';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { AccessibilityHelpAction, AccessibleViewAction } from 'vs/workbench/contrib/accessibility/browser/accessibleViewActions';
/*--------------------------------------------------------------------------------------------- */
Registry.as<IEditorPaneRegistry>(EditorExtensions.EditorPane).registerEditorPane(
EditorPaneDescriptor.create(
NotebookEditor,
NotebookEditor.ID,
'Notebook Editor'
),
[
new SyncDescriptor(NotebookEditorInput)
]
);
Registry.as<IEditorPaneRegistry>(EditorExtensions.EditorPane).registerEditorPane(
EditorPaneDescriptor.create(
NotebookTextDiffEditor,
NotebookTextDiffEditor.ID,
'Notebook Diff Editor'
),
[
new SyncDescriptor(NotebookDiffEditorInput)
]
);
class NotebookDiffEditorSerializer implements IEditorSerializer {
canSerialize(): boolean {
return true;
}
serialize(input: EditorInput): string {
assertType(input instanceof NotebookDiffEditorInput);
return JSON.stringify({
resource: input.resource,
originalResource: input.original.resource,
name: input.getName(),
originalName: input.original.getName(),
textDiffName: input.getName(),
viewType: input.viewType,
});
}
deserialize(instantiationService: IInstantiationService, raw: string) {
type Data = { resource: URI; originalResource: URI; name: string; originalName: string; viewType: string; textDiffName: string | undefined; group: number };
const data = <Data>parse(raw);
if (!data) {
return undefined;
}
const { resource, originalResource, name, viewType } = data;
if (!data || !URI.isUri(resource) || !URI.isUri(originalResource) || typeof name !== 'string' || typeof viewType !== 'string') {
return undefined;
}
const input = NotebookDiffEditorInput.create(instantiationService, resource, name, undefined, originalResource, viewType);
return input;
}
static canResolveBackup(editorInput: EditorInput, backupResource: URI): boolean {
return false;
}
}
type SerializedNotebookEditorData = { resource: URI; viewType: string; options?: NotebookEditorInputOptions };
class NotebookEditorSerializer implements IEditorSerializer {
canSerialize(): boolean {
return true;
}
serialize(input: EditorInput): string {
assertType(input instanceof NotebookEditorInput);
const data: SerializedNotebookEditorData = {
resource: input.resource,
viewType: input.viewType,
options: input.options
};
return JSON.stringify(data);
}
deserialize(instantiationService: IInstantiationService, raw: string) {
const data = <SerializedNotebookEditorData>parse(raw);
if (!data) {
return undefined;
}
const { resource, viewType, options } = data;
if (!data || !URI.isUri(resource) || typeof viewType !== 'string') {
return undefined;
}
const input = NotebookEditorInput.create(instantiationService, resource, viewType, options);
return input;
}
}
Registry.as<IEditorFactoryRegistry>(EditorExtensions.EditorFactory).registerEditorSerializer(
NotebookEditorInput.ID,
NotebookEditorSerializer
);
Registry.as<IEditorFactoryRegistry>(EditorExtensions.EditorFactory).registerEditorSerializer(
NotebookDiffEditorInput.ID,
NotebookDiffEditorSerializer
);
export class NotebookContribution extends Disposable implements IWorkbenchContribution {
private _uriComparisonKeyComputer?: IDisposable;
constructor(
@IUndoRedoService undoRedoService: IUndoRedoService,
@IConfigurationService configurationService: IConfigurationService,
@ICodeEditorService private readonly codeEditorService: ICodeEditorService,
) {
super();
this.updateCellUndoRedoComparisonKey(configurationService, undoRedoService);
// Watch for changes to undoRedoPerCell setting
this._register(configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration(NotebookSetting.undoRedoPerCell)) {
this.updateCellUndoRedoComparisonKey(configurationService, undoRedoService);
}
}));
// register comment decoration
this.codeEditorService.registerDecorationType('comment-controller', COMMENTEDITOR_DECORATION_KEY, {});
}
// Add or remove the cell undo redo comparison key based on the user setting
private updateCellUndoRedoComparisonKey(configurationService: IConfigurationService, undoRedoService: IUndoRedoService) {
const undoRedoPerCell = configurationService.getValue<boolean>(NotebookSetting.undoRedoPerCell);
if (!undoRedoPerCell) {
// Add comparison key to map cell => main document
if (!this._uriComparisonKeyComputer) {
this._uriComparisonKeyComputer = undoRedoService.registerUriComparisonKeyComputer(CellUri.scheme, {
getComparisonKey: (uri: URI): string => {
if (undoRedoPerCell) {
return uri.toString();
}
return NotebookContribution._getCellUndoRedoComparisonKey(uri);
}
});
}
} else {
// Dispose comparison key
this._uriComparisonKeyComputer?.dispose();
this._uriComparisonKeyComputer = undefined;
}
}
private static _getCellUndoRedoComparisonKey(uri: URI) {
const data = CellUri.parse(uri);
if (!data) {
return uri.toString();
}
return data.notebook.toString();
}
override dispose(): void {
super.dispose();
this._uriComparisonKeyComputer?.dispose();
}
}
class CellContentProvider implements ITextModelContentProvider {
private readonly _registration: IDisposable;
constructor(
@ITextModelService textModelService: ITextModelService,
@IModelService private readonly _modelService: IModelService,
@ILanguageService private readonly _languageService: ILanguageService,
@INotebookEditorModelResolverService private readonly _notebookModelResolverService: INotebookEditorModelResolverService,
) {
this._registration = textModelService.registerTextModelContentProvider(CellUri.scheme, this);
}
dispose(): void {
this._registration.dispose();
}
async provideTextContent(resource: URI): Promise<ITextModel | null> {
const existing = this._modelService.getModel(resource);
if (existing) {
return existing;
}
const data = CellUri.parse(resource);
// const data = parseCellUri(resource);
if (!data) {
return null;
}
const ref = await this._notebookModelResolverService.resolve(data.notebook);
let result: ITextModel | null = null;
if (!ref.object.isResolved()) {
return null;
}
for (const cell of ref.object.notebook.cells) {
if (cell.uri.toString() === resource.toString()) {
const bufferFactory: ITextBufferFactory = {
create: (defaultEOL) => {
const newEOL = (defaultEOL === DefaultEndOfLine.CRLF ? '\r\n' : '\n');
(cell.textBuffer as ITextBuffer).setEOL(newEOL);
return { textBuffer: cell.textBuffer as ITextBuffer, disposable: Disposable.None };
},
getFirstLineText: (limit: number) => {
return cell.textBuffer.getLineContent(1).substring(0, limit);
}
};
const languageId = this._languageService.getLanguageIdByLanguageName(cell.language);
const languageSelection = languageId ? this._languageService.createById(languageId) : (cell.cellKind === CellKind.Markup ? this._languageService.createById('markdown') : this._languageService.createByFilepathOrFirstLine(resource, cell.textBuffer.getLineContent(1)));
result = this._modelService.createModel(
bufferFactory,
languageSelection,
resource
);
break;
}
}
if (!result) {
ref.dispose();
return null;
}
const once = Event.any(result.onWillDispose, ref.object.notebook.onWillDispose)(() => {
once.dispose();
ref.dispose();
});
return result;
}
}
class CellInfoContentProvider {
private readonly _disposables: IDisposable[] = [];
constructor(
@ITextModelService textModelService: ITextModelService,
@IModelService private readonly _modelService: IModelService,
@ILanguageService private readonly _languageService: ILanguageService,
@ILabelService private readonly _labelService: ILabelService,
@INotebookEditorModelResolverService private readonly _notebookModelResolverService: INotebookEditorModelResolverService,
) {
this._disposables.push(textModelService.registerTextModelContentProvider(Schemas.vscodeNotebookCellMetadata, {
provideTextContent: this.provideMetadataTextContent.bind(this)
}));
this._disposables.push(textModelService.registerTextModelContentProvider(Schemas.vscodeNotebookCellOutput, {
provideTextContent: this.provideOutputTextContent.bind(this)
}));
this._disposables.push(this._labelService.registerFormatter({
scheme: Schemas.vscodeNotebookCellMetadata,
formatting: {
label: '${path} (metadata)',
separator: '/'
}
}));
this._disposables.push(this._labelService.registerFormatter({
scheme: Schemas.vscodeNotebookCellOutput,
formatting: {
label: '${path} (output)',
separator: '/'
}
}));
}
dispose(): void {
dispose(this._disposables);
}
async provideMetadataTextContent(resource: URI): Promise<ITextModel | null> {
const existing = this._modelService.getModel(resource);
if (existing) {
return existing;
}
const data = CellUri.parseCellPropertyUri(resource, Schemas.vscodeNotebookCellMetadata);
if (!data) {
return null;
}
const ref = await this._notebookModelResolverService.resolve(data.notebook);
let result: ITextModel | null = null;
const mode = this._languageService.createById('json');
for (const cell of ref.object.notebook.cells) {
if (cell.handle === data.handle) {
const metadataSource = getFormattedMetadataJSON(ref.object.notebook, cell.metadata, cell.language);
result = this._modelService.createModel(
metadataSource,
mode,
resource
);
break;
}
}
if (!result) {
ref.dispose();
return null;
}
const once = result.onWillDispose(() => {
once.dispose();
ref.dispose();
});
return result;
}
private parseStreamOutput(op?: ICellOutput): { content: string; mode: ILanguageSelection } | undefined {
if (!op) {
return;
}
const streamOutputData = getStreamOutputData(op.outputs);
if (streamOutputData) {
return {
content: streamOutputData,
mode: this._languageService.createById(PLAINTEXT_LANGUAGE_ID)
};
}
return;
}
private _getResult(data: {
notebook: URI;
outputId?: string | undefined;
}, cell: ICell) {
let result: { content: string; mode: ILanguageSelection } | undefined = undefined;
const mode = this._languageService.createById('json');
const op = cell.outputs.find(op => op.outputId === data.outputId);
const streamOutputData = this.parseStreamOutput(op);
if (streamOutputData) {
result = streamOutputData;
return result;
}
const obj = cell.outputs.map(output => ({
metadata: output.metadata,
outputItems: output.outputs.map(opit => ({
mimeType: opit.mime,
data: opit.data.toString()
}))
}));
const outputSource = toFormattedString(obj, {});
result = {
content: outputSource,
mode
};
return result;
}
async provideOutputTextContent(resource: URI): Promise<ITextModel | null> {
const existing = this._modelService.getModel(resource);
if (existing) {
return existing;
}
const data = CellUri.parseCellOutputUri(resource);
if (!data) {
return null;
}
const ref = await this._notebookModelResolverService.resolve(data.notebook);
const cell = ref.object.notebook.cells.find(cell => !!cell.outputs.find(op => op.outputId === data.outputId));
if (!cell) {
ref.dispose();
return null;
}
const result = this._getResult(data, cell);
if (!result) {
ref.dispose();
return null;
}
const model = this._modelService.createModel(result.content, result.mode, resource);
const cellModelListener = Event.any(cell.onDidChangeOutputs ?? Event.None, cell.onDidChangeOutputItems ?? Event.None)(() => {
const newResult = this._getResult(data, cell);
if (!newResult) {
return;
}
model.setValue(newResult.content);
model.setLanguage(newResult.mode.languageId);
});
const once = model.onWillDispose(() => {
once.dispose();
cellModelListener.dispose();
ref.dispose();
});
return model;
}
}
class RegisterSchemasContribution extends Disposable implements IWorkbenchContribution {
constructor() {
super();
this.registerMetadataSchemas();
}
private registerMetadataSchemas(): void {
const jsonRegistry = Registry.as<IJSONContributionRegistry>(JSONExtensions.JSONContribution);
const metadataSchema: IJSONSchema = {
properties: {
['language']: {
type: 'string',
description: 'The language for the cell'
}
},
// patternProperties: allSettings.patternProperties,
additionalProperties: true,
allowTrailingCommas: true,
allowComments: true
};
jsonRegistry.registerSchema('vscode://schemas/notebook/cellmetadata', metadataSchema);
}
}
class NotebookEditorManager implements IWorkbenchContribution {
private readonly _disposables = new DisposableStore();
constructor(
@IEditorService private readonly _editorService: IEditorService,
@INotebookEditorModelResolverService private readonly _notebookEditorModelService: INotebookEditorModelResolverService,
@IEditorGroupsService editorGroups: IEditorGroupsService
) {
// OPEN notebook editor for models that have turned dirty without being visible in an editor
type E = IResolvedNotebookEditorModel;
this._disposables.add(Event.debounce<E, E[]>(
this._notebookEditorModelService.onDidChangeDirty,
(last, current) => !last ? [current] : [...last, current],
100
)(this._openMissingDirtyNotebookEditors, this));
// CLOSE editors when we are about to open conflicting notebooks
this._disposables.add(_notebookEditorModelService.onWillFailWithConflict(e => {
for (const group of editorGroups.groups) {
const conflictInputs = group.editors.filter(input => input instanceof NotebookEditorInput && input.viewType !== e.viewType && isEqual(input.resource, e.resource));
const p = group.closeEditors(conflictInputs);
e.waitUntil(p);
}
}));
}
dispose(): void {
this._disposables.dispose();
}
private _openMissingDirtyNotebookEditors(models: IResolvedNotebookEditorModel[]): void {
const result: IResourceEditorInput[] = [];
for (const model of models) {
if (model.isDirty() && !this._editorService.isOpened({ resource: model.resource, typeId: NotebookEditorInput.ID, editorId: model.viewType }) && extname(model.resource) !== '.interactive') {
result.push({
resource: model.resource,
options: { inactive: true, preserveFocus: true, pinned: true, override: model.viewType }
});
}
}
if (result.length > 0) {
this._editorService.openEditors(result);
}
}
}
class SimpleNotebookWorkingCopyEditorHandler extends Disposable implements IWorkbenchContribution, IWorkingCopyEditorHandler {
constructor(
@IInstantiationService private readonly _instantiationService: IInstantiationService,
@IWorkingCopyEditorService private readonly _workingCopyEditorService: IWorkingCopyEditorService,
@IExtensionService private readonly _extensionService: IExtensionService,
@INotebookService private readonly _notebookService: INotebookService
) {
super();
this._installHandler();
}
async handles(workingCopy: IWorkingCopyIdentifier): Promise<boolean> {
const viewType = this.handlesSync(workingCopy);
if (!viewType) {
return false;
}
return this._notebookService.canResolve(viewType);
}
private handlesSync(workingCopy: IWorkingCopyIdentifier): string /* viewType */ | undefined {
const viewType = this._getViewType(workingCopy);
if (!viewType || viewType === 'interactive') {
return undefined;
}
return viewType;
}
isOpen(workingCopy: IWorkingCopyIdentifier, editor: EditorInput): boolean {
if (!this.handlesSync(workingCopy)) {
return false;
}
return editor instanceof NotebookEditorInput && editor.viewType === this._getViewType(workingCopy) && isEqual(workingCopy.resource, editor.resource);
}
createEditor(workingCopy: IWorkingCopyIdentifier): EditorInput {
return NotebookEditorInput.create(this._instantiationService, workingCopy.resource, this._getViewType(workingCopy)!);
}
private async _installHandler(): Promise<void> {
await this._extensionService.whenInstalledExtensionsRegistered();
this._register(this._workingCopyEditorService.registerHandler(this));
}
private _getViewType(workingCopy: IWorkingCopyIdentifier): string | undefined {
return NotebookWorkingCopyTypeIdentifier.parse(workingCopy.typeId);
}
}
class NotebookLanguageSelectorScoreRefine {
constructor(
@INotebookService private readonly _notebookService: INotebookService,
@ILanguageFeaturesService languageFeaturesService: ILanguageFeaturesService,
) {
languageFeaturesService.setNotebookTypeResolver(this._getNotebookInfo.bind(this));
}
private _getNotebookInfo(uri: URI): NotebookInfo | undefined {
const cellUri = CellUri.parse(uri);
if (!cellUri) {
return undefined;
}
const notebook = this._notebookService.getNotebookTextModel(cellUri.notebook);
if (!notebook) {
return undefined;
}
return {
uri: notebook.uri,
type: notebook.viewType
};
}
}
class NotebookAccessibilityHelpContribution extends Disposable {
static ID: 'notebookAccessibilityHelpContribution';
constructor() {
super();
this._register(AccessibilityHelpAction.addImplementation(105, 'notebook', async accessor => {
const codeEditor = accessor.get(ICodeEditorService).getActiveCodeEditor() || accessor.get(ICodeEditorService).getFocusedCodeEditor();
if (!codeEditor) {
return;
}
runAccessibilityHelpAction(accessor, codeEditor);
}, NOTEBOOK_IS_ACTIVE_EDITOR));
}
}
class NotebookAccessibleViewContribution extends Disposable {
static ID: 'chatAccessibleViewContribution';
constructor() {
super();
this._register(AccessibleViewAction.addImplementation(100, 'notebook', accessor => {
const accessibleViewService = accessor.get(IAccessibleViewService);
const editorService = accessor.get(IEditorService);
return showAccessibleOutput(accessibleViewService, editorService);
},
ContextKeyExpr.and(NOTEBOOK_OUTPUT_FOCUSED, ContextKeyExpr.equals('resourceExtname', '.ipynb'))
));
}
}
const workbenchContributionsRegistry = Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench);
workbenchContributionsRegistry.registerWorkbenchContribution(NotebookContribution, LifecyclePhase.Starting);
workbenchContributionsRegistry.registerWorkbenchContribution(CellContentProvider, LifecyclePhase.Starting);
workbenchContributionsRegistry.registerWorkbenchContribution(CellInfoContentProvider, LifecyclePhase.Starting);
workbenchContributionsRegistry.registerWorkbenchContribution(RegisterSchemasContribution, LifecyclePhase.Starting);
workbenchContributionsRegistry.registerWorkbenchContribution(NotebookEditorManager, LifecyclePhase.Ready);
workbenchContributionsRegistry.registerWorkbenchContribution(NotebookLanguageSelectorScoreRefine, LifecyclePhase.Ready);
workbenchContributionsRegistry.registerWorkbenchContribution(SimpleNotebookWorkingCopyEditorHandler, LifecyclePhase.Ready);
workbenchContributionsRegistry.registerWorkbenchContribution(NotebookAccessibilityHelpContribution, LifecyclePhase.Eventually);
workbenchContributionsRegistry.registerWorkbenchContribution(NotebookAccessibleViewContribution, LifecyclePhase.Eventually);
registerSingleton(INotebookService, NotebookService, InstantiationType.Delayed);
registerSingleton(INotebookEditorWorkerService, NotebookEditorWorkerServiceImpl, InstantiationType.Delayed);
registerSingleton(INotebookEditorModelResolverService, NotebookModelResolverServiceImpl, InstantiationType.Delayed);
registerSingleton(INotebookCellStatusBarService, NotebookCellStatusBarService, InstantiationType.Delayed);
registerSingleton(INotebookEditorService, NotebookEditorWidgetService, InstantiationType.Delayed);
registerSingleton(INotebookKernelService, NotebookKernelService, InstantiationType.Delayed);
registerSingleton(INotebookKernelHistoryService, NotebookKernelHistoryService, InstantiationType.Delayed);
registerSingleton(INotebookExecutionService, NotebookExecutionService, InstantiationType.Delayed);
registerSingleton(INotebookExecutionStateService, NotebookExecutionStateService, InstantiationType.Delayed);
registerSingleton(INotebookRendererMessagingService, NotebookRendererMessagingService, InstantiationType.Delayed);
registerSingleton(INotebookKeymapService, NotebookKeymapService, InstantiationType.Delayed);
registerSingleton(INotebookLoggingService, NotebookLoggingService, InstantiationType.Delayed);
const schemas: IJSONSchemaMap = {};
function isConfigurationPropertySchema(x: IConfigurationPropertySchema | { [path: string]: IConfigurationPropertySchema }): x is IConfigurationPropertySchema {
return (typeof x.type !== 'undefined' || typeof x.anyOf !== 'undefined');
}
for (const editorOption of editorOptionsRegistry) {
const schema = editorOption.schema;
if (schema) {
if (isConfigurationPropertySchema(schema)) {
schemas[`editor.${editorOption.name}`] = schema;
} else {
for (const key in schema) {
if (Object.hasOwnProperty.call(schema, key)) {
schemas[key] = schema[key];
}
}
}
}
}
const editorOptionsCustomizationSchema: IConfigurationPropertySchema = {
description: nls.localize('notebook.editorOptions.experimentalCustomization', 'Settings for code editors used in notebooks. This can be used to customize most editor.* settings.'),
default: {},
allOf: [
{
properties: schemas,
}
// , {
// patternProperties: {
// '^\\[.*\\]$': {
// type: 'object',
// default: {},
// properties: schemas
// }
// }
// }
],
tags: ['notebookLayout']
};
const configurationRegistry = Registry.as<IConfigurationRegistry>(Extensions.Configuration);
configurationRegistry.registerConfiguration({
id: 'notebook',
order: 100,
title: nls.localize('notebookConfigurationTitle', "Notebook"),
type: 'object',
properties: {
[NotebookSetting.displayOrder]: {
description: nls.localize('notebook.displayOrder.description', "Priority list for output mime types"),
type: 'array',
items: {
type: 'string'
},
default: []
},
[NotebookSetting.cellToolbarLocation]: {
description: nls.localize('notebook.cellToolbarLocation.description', "Where the cell toolbar should be shown, or whether it should be hidden."),
type: 'object',
additionalProperties: {
markdownDescription: nls.localize('notebook.cellToolbarLocation.viewType', "Configure the cell toolbar position for for specific file types"),
type: 'string',
enum: ['left', 'right', 'hidden']
},
default: {
'default': 'right'
},
tags: ['notebookLayout']
},
[NotebookSetting.showCellStatusBar]: {
description: nls.localize('notebook.showCellStatusbar.description', "Whether the cell status bar should be shown."),
type: 'string',
enum: ['hidden', 'visible', 'visibleAfterExecute'],
enumDescriptions: [
nls.localize('notebook.showCellStatusbar.hidden.description', "The cell Status bar is always hidden."),
nls.localize('notebook.showCellStatusbar.visible.description', "The cell Status bar is always visible."),
nls.localize('notebook.showCellStatusbar.visibleAfterExecute.description', "The cell Status bar is hidden until the cell has executed. Then it becomes visible to show the execution status.")],
default: 'visible',
tags: ['notebookLayout']
},
[NotebookSetting.textDiffEditorPreview]: {
description: nls.localize('notebook.diff.enablePreview.description', "Whether to use the enhanced text diff editor for notebook."),
type: 'boolean',
default: true,
tags: ['notebookLayout']
},
[NotebookSetting.diffOverviewRuler]: {
description: nls.localize('notebook.diff.enableOverviewRuler.description', "Whether to render the overview ruler in the diff editor for notebook."),
type: 'boolean',
default: false,
tags: ['notebookLayout']
},
[NotebookSetting.cellToolbarVisibility]: {
markdownDescription: nls.localize('notebook.cellToolbarVisibility.description', "Whether the cell toolbar should appear on hover or click."),
type: 'string',
enum: ['hover', 'click'],
default: 'click',
tags: ['notebookLayout']
},
[NotebookSetting.undoRedoPerCell]: {
description: nls.localize('notebook.undoRedoPerCell.description', "Whether to use separate undo/redo stack for each cell."),
type: 'boolean',
default: true,
tags: ['notebookLayout']
},
[NotebookSetting.compactView]: {
description: nls.localize('notebook.compactView.description', "Control whether the notebook editor should be rendered in a compact form. For example, when turned on, it will decrease the left margin width."),
type: 'boolean',
default: true,
tags: ['notebookLayout']
},
[NotebookSetting.focusIndicator]: {
description: nls.localize('notebook.focusIndicator.description', "Controls where the focus indicator is rendered, either along the cell borders or on the left gutter."),
type: 'string',
enum: ['border', 'gutter'],
default: 'gutter',
tags: ['notebookLayout']
},
[NotebookSetting.insertToolbarLocation]: {
description: nls.localize('notebook.insertToolbarPosition.description', "Control where the insert cell actions should appear."),
type: 'string',
enum: ['betweenCells', 'notebookToolbar', 'both', 'hidden'],
enumDescriptions: [
nls.localize('insertToolbarLocation.betweenCells', "A toolbar that appears on hover between cells."),
nls.localize('insertToolbarLocation.notebookToolbar', "The toolbar at the top of the notebook editor."),
nls.localize('insertToolbarLocation.both', "Both toolbars."),
nls.localize('insertToolbarLocation.hidden', "The insert actions don't appear anywhere."),
],
default: 'both',
tags: ['notebookLayout']
},
[NotebookSetting.globalToolbar]: {
description: nls.localize('notebook.globalToolbar.description', "Control whether to render a global toolbar inside the notebook editor."),
type: 'boolean',
default: true,
tags: ['notebookLayout']
},
[NotebookSetting.stickyScroll]: {
description: nls.localize('notebook.stickyScroll.description', "Experimental. Control whether to render notebook Sticky Scroll headers in the notebook editor."),
type: 'boolean',
default: false,
tags: ['notebookLayout']
},
[NotebookSetting.consolidatedOutputButton]: {
description: nls.localize('notebook.consolidatedOutputButton.description', "Control whether outputs action should be rendered in the output toolbar."),
type: 'boolean',
default: true,
tags: ['notebookLayout']
},
[NotebookSetting.showFoldingControls]: {
description: nls.localize('notebook.showFoldingControls.description', "Controls when the Markdown header folding arrow is shown."),
type: 'string',
enum: ['always', 'never', 'mouseover'],
enumDescriptions: [
nls.localize('showFoldingControls.always', "The folding controls are always visible."),
nls.localize('showFoldingControls.never', "Never show the folding controls and reduce the gutter size."),
nls.localize('showFoldingControls.mouseover', "The folding controls are visible only on mouseover."),
],
default: 'mouseover',
tags: ['notebookLayout']
},
[NotebookSetting.dragAndDropEnabled]: {
description: nls.localize('notebook.dragAndDrop.description', "Control whether the notebook editor should allow moving cells through drag and drop."),
type: 'boolean',
default: true,
tags: ['notebookLayout']
},
[NotebookSetting.consolidatedRunButton]: {
description: nls.localize('notebook.consolidatedRunButton.description', "Control whether extra actions are shown in a dropdown next to the run button."),
type: 'boolean',
default: false,
tags: ['notebookLayout']
},
[NotebookSetting.globalToolbarShowLabel]: {
description: nls.localize('notebook.globalToolbarShowLabel', "Control whether the actions on the notebook toolbar should render label or not."),
type: 'string',
enum: ['always', 'never', 'dynamic'],
default: 'always',
tags: ['notebookLayout']
},
[NotebookSetting.textOutputLineLimit]: {
markdownDescription: nls.localize('notebook.textOutputLineLimit', "Controls how many lines of text are displayed in a text output. If {0} is enabled, this setting is used to determine the scroll height of the output.", '`#notebook.output.scrolling#`'),
type: 'number',
default: 30,
tags: ['notebookLayout', 'notebookOutputLayout']
},
[NotebookSetting.markupFontSize]: {
markdownDescription: nls.localize('notebook.markup.fontSize', "Controls the font size in pixels of rendered markup in notebooks. When set to {0}, 120% of {1} is used.", '`0`', '`#editor.fontSize#`'),
type: 'number',
default: 0,
tags: ['notebookLayout']
},
[NotebookSetting.cellEditorOptionsCustomizations]: editorOptionsCustomizationSchema,
[NotebookSetting.interactiveWindowCollapseCodeCells]: {
markdownDescription: nls.localize('notebook.interactiveWindow.collapseCodeCells', "Controls whether code cells in the interactive window are collapsed by default."),
type: 'string',
enum: ['always', 'never', 'fromEditor'],
default: 'fromEditor'
},
[NotebookSetting.outputLineHeight]: {
markdownDescription: nls.localize('notebook.outputLineHeight', "Line height of the output text within notebook cells.\n - When set to 0, editor line height is used.\n - Values between 0 and 8 will be used as a multiplier with the font size.\n - Values greater than or equal to 8 will be used as effective values."),
type: 'number',
default: 0,
tags: ['notebookLayout', 'notebookOutputLayout']
},
[NotebookSetting.outputFontSize]: {
markdownDescription: nls.localize('notebook.outputFontSize', "Font size for the output text within notebook cells. When set to 0, {0} is used.", '`#editor.fontSize#`'),
type: 'number',
default: 0,
tags: ['notebookLayout', 'notebookOutputLayout']
},
[NotebookSetting.outputFontFamily]: {
markdownDescription: nls.localize('notebook.outputFontFamily', "The font family of the output text within notebook cells. When set to empty, the {0} is used.", '`#editor.fontFamily#`'),
type: 'string',
tags: ['notebookLayout', 'notebookOutputLayout']
},
[NotebookSetting.outputScrolling]: {
markdownDescription: nls.localize('notebook.outputScrolling', "Initially render notebook outputs in a scrollable region when longer than the limit"),
type: 'boolean',
tags: ['notebookLayout', 'notebookOutputLayout'],
default: typeof product.quality === 'string' && product.quality !== 'stable' // only enable as default in insiders
},
[NotebookSetting.outputWordWrap]: {
markdownDescription: nls.localize('notebook.outputWordWrap', "Controls whether the lines in output should wrap."),
type: 'boolean',
tags: ['notebookLayout', 'notebookOutputLayout'],
default: false
},
[NotebookSetting.formatOnSave]: {
markdownDescription: nls.localize('notebook.formatOnSave', "Format a notebook on save. A formatter must be available, the file must not be saved after delay, and the editor must not be shutting down."),
type: 'boolean',
tags: ['notebookLayout'],
default: false
},
[NotebookSetting.codeActionsOnSave]: {
markdownDescription: nls.localize('notebook.codeActionsOnSave', "Experimental. Run a series of CodeActions for a notebook on save. CodeActions must be specified, the file must not be saved after delay, and the editor must not be shutting down. Example: `source.fixAll: true`"),
type: 'object',
additionalProperties: {
type: 'boolean'
},
default: {}
},
[NotebookSetting.formatOnCellExecution]: {
markdownDescription: nls.localize('notebook.formatOnCellExecution', "Format a notebook cell upon execution. A formatter must be available."),
type: 'boolean',
default: false
},
[NotebookSetting.confirmDeleteRunningCell]: {
markdownDescription: nls.localize('notebook.confirmDeleteRunningCell', "Control whether a confirmation prompt is required to delete a running cell."),
type: 'boolean',
default: true
},
[NotebookSetting.findScope]: {
markdownDescription: nls.localize('notebook.findScope', "Customize the Find Widget behavior for searching within notebook cells. When both markup source and markup preview are enabled, the Find Widget will search either the source code or preview based on the current state of the cell."),
type: 'object',
properties: {
markupSource: {
type: 'boolean',
default: true
},
markupPreview: {
type: 'boolean',
default: true
},
codeSource: {
type: 'boolean',
default: true
},
codeOutput: {
type: 'boolean',
default: true
}
},
default: {
markupSource: true,
markupPreview: true,
codeSource: true,
codeOutput: true
},
tags: ['notebookLayout']
},
[NotebookSetting.remoteSaving]: {
markdownDescription: nls.localize('notebook.remoteSaving', "Enables the incremental saving of notebooks in Remote environment. When enabled, only the changes to the notebook are sent to the extension host, improving performance for large notebooks and slow network connections."),
type: 'boolean',
default: typeof product.quality === 'string' && product.quality !== 'stable' // only enable as default in insiders
}
}
});
| src/vs/workbench/contrib/notebook/browser/notebook.contribution.ts | 1 | https://github.com/microsoft/vscode/commit/94956b4c3fb38badce912cae3d5a531502669885 | [
0.9990008473396301,
0.0905490592122078,
0.00016143062384799123,
0.00017486717842984945,
0.2755736708641052
] |
{
"id": 0,
"code_window": [
"\t}, cell: ICell) {\n",
"\t\tlet result: { content: string; mode: ILanguageSelection } | undefined = undefined;\n",
"\n",
"\t\tconst mode = this._languageService.createById('json');\n",
"\t\tconst op = cell.outputs.find(op => op.outputId === data.outputId);\n",
"\t\tconst streamOutputData = this.parseStreamOutput(op);\n",
"\t\tif (streamOutputData) {\n",
"\t\t\tresult = streamOutputData;\n",
"\t\t\treturn result;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst op = cell.outputs.find(op => op.outputId === data.outputId || op.alternativeOutputId === data.outputId);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/notebook.contribution.ts",
"type": "replace",
"edit_start_line_idx": 457
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { FileAccess } from 'vs/base/common/network';
import * as path from 'vs/base/common/path';
import { URI } from 'vs/base/common/uri';
import { flakySuite } from 'vs/base/test/node/testUtils';
import { IFileQuery, IFolderQuery, ISerializedSearchProgressItem, isProgressMessage, QueryType } from 'vs/workbench/services/search/common/search';
import { SearchService } from 'vs/workbench/services/search/node/rawSearchService';
const TEST_FIXTURES = path.normalize(FileAccess.asFileUri('vs/workbench/services/search/test/node/fixtures').fsPath);
const TEST_FIXTURES2 = path.normalize(FileAccess.asFileUri('vs/workbench/services/search/test/node/fixtures2').fsPath);
const EXAMPLES_FIXTURES = path.join(TEST_FIXTURES, 'examples');
const MORE_FIXTURES = path.join(TEST_FIXTURES, 'more');
const TEST_ROOT_FOLDER: IFolderQuery = { folder: URI.file(TEST_FIXTURES) };
const ROOT_FOLDER_QUERY: IFolderQuery[] = [
TEST_ROOT_FOLDER
];
const MULTIROOT_QUERIES: IFolderQuery[] = [
{ folder: URI.file(EXAMPLES_FIXTURES), folderName: 'examples_folder' },
{ folder: URI.file(MORE_FIXTURES) }
];
async function doSearchTest(query: IFileQuery, expectedResultCount: number | Function): Promise<void> {
const svc = new SearchService();
const results: ISerializedSearchProgressItem[] = [];
await svc.doFileSearch(query, e => {
if (!isProgressMessage(e)) {
if (Array.isArray(e)) {
results.push(...e);
} else {
results.push(e);
}
}
});
assert.strictEqual(results.length, expectedResultCount, `rg ${results.length} !== ${expectedResultCount}`);
}
flakySuite('FileSearch-integration', function () {
test('File - simple', () => {
const config: IFileQuery = {
type: QueryType.File,
folderQueries: ROOT_FOLDER_QUERY
};
return doSearchTest(config, 14);
});
test('File - filepattern', () => {
const config: IFileQuery = {
type: QueryType.File,
folderQueries: ROOT_FOLDER_QUERY,
filePattern: 'anotherfile'
};
return doSearchTest(config, 1);
});
test('File - exclude', () => {
const config: IFileQuery = {
type: QueryType.File,
folderQueries: ROOT_FOLDER_QUERY,
filePattern: 'file',
excludePattern: { '**/anotherfolder/**': true }
};
return doSearchTest(config, 2);
});
test('File - multiroot', () => {
const config: IFileQuery = {
type: QueryType.File,
folderQueries: MULTIROOT_QUERIES,
filePattern: 'file',
excludePattern: { '**/anotherfolder/**': true }
};
return doSearchTest(config, 2);
});
test('File - multiroot with folder name', () => {
const config: IFileQuery = {
type: QueryType.File,
folderQueries: MULTIROOT_QUERIES,
filePattern: 'examples_folder anotherfile'
};
return doSearchTest(config, 1);
});
test('File - multiroot with folder name and sibling exclude', () => {
const config: IFileQuery = {
type: QueryType.File,
folderQueries: [
{ folder: URI.file(TEST_FIXTURES), folderName: 'folder1' },
{ folder: URI.file(TEST_FIXTURES2) }
],
filePattern: 'folder1 site',
excludePattern: { '*.css': { when: '$(basename).less' } }
};
return doSearchTest(config, 1);
});
});
| src/vs/workbench/services/search/test/node/fileSearch.integrationTest.ts | 0 | https://github.com/microsoft/vscode/commit/94956b4c3fb38badce912cae3d5a531502669885 | [
0.00028081698110327125,
0.00018405138689558953,
0.00017153553199023008,
0.00017555715749040246,
0.00002923987813119311
] |
{
"id": 0,
"code_window": [
"\t}, cell: ICell) {\n",
"\t\tlet result: { content: string; mode: ILanguageSelection } | undefined = undefined;\n",
"\n",
"\t\tconst mode = this._languageService.createById('json');\n",
"\t\tconst op = cell.outputs.find(op => op.outputId === data.outputId);\n",
"\t\tconst streamOutputData = this.parseStreamOutput(op);\n",
"\t\tif (streamOutputData) {\n",
"\t\t\tresult = streamOutputData;\n",
"\t\t\treturn result;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst op = cell.outputs.find(op => op.outputId === data.outputId || op.alternativeOutputId === data.outputId);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/notebook.contribution.ts",
"type": "replace",
"edit_start_line_idx": 457
} | {
"original": {
"content": "import { Link, List, Separator, Stack } from '@fluentui/react';\nimport { View } from '../../layout/layout';\n\nexport const OtherToolsView = () => {\n\treturn (\n\t\t<View title='Other Tools'>\n\t\t\t<Stack grow={true} verticalFill={true}>\n\t\t\t\t<Stack.Item>\n\t\t\t\t\t<List\n\t\t\t\t\t\titems={[\n\t\t\t\t\t\t\t{ name: 'VS Code Standup (Redomond)', href: 'https://vscode-standup.azurewebsites.net' },\n\t\t\t\t\t\t\t{ name: 'VS Code Standup (Zurich)', href: 'http://stand.azurewebsites.net/' },\n\t\t\t\t\t\t\t{},\n\t\t\t\t\t\t\t{ name: 'VS Code Errors', href: 'https://vscode-errors.azurewebsites.net' },\n\t\t\t\t\t\t\t{ name: 'VS Code GDPR', href: 'https://github.com/microsoft/vscode-gdpr-tooling' },\n\t\t\t\t\t\t]}\n\t\t\t\t\t\tonRenderCell={(item) => {\n\t\t\t\t\t\t\tif (!item?.name) {\n\t\t\t\t\t\t\t\treturn <Separator></Separator>\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn <div style={{ marginBottom: 12 }}><Link href={item!.href} target='_blank'>{item!.name}</Link></div>\n\t\t\t\t\t\t}}\n\t\t\t\t\t>\n\t\t\t\t\t</List>\n\t\t\t\t</Stack.Item>\n\t\t\t</Stack>\n\t\t</View>\n\t);\n}",
"fileName": "./1.tst"
},
"modified": {
"content": "",
"fileName": "./2.tst"
},
"diffs": [
{
"originalRange": "[1,30)",
"modifiedRange": "[1,2)",
"innerChanges": [
{
"originalRange": "[1,1 -> 29,64]",
"modifiedRange": "[1,1 -> 1,1]"
}
]
}
]
} | src/vs/editor/test/node/diffing/fixtures/deletion/advanced.expected.diff.json | 0 | https://github.com/microsoft/vscode/commit/94956b4c3fb38badce912cae3d5a531502669885 | [
0.00017571289208717644,
0.00017271672550123185,
0.00016699476691428572,
0.00017544253205414861,
0.0000040475442801835015
] |
{
"id": 0,
"code_window": [
"\t}, cell: ICell) {\n",
"\t\tlet result: { content: string; mode: ILanguageSelection } | undefined = undefined;\n",
"\n",
"\t\tconst mode = this._languageService.createById('json');\n",
"\t\tconst op = cell.outputs.find(op => op.outputId === data.outputId);\n",
"\t\tconst streamOutputData = this.parseStreamOutput(op);\n",
"\t\tif (streamOutputData) {\n",
"\t\t\tresult = streamOutputData;\n",
"\t\t\treturn result;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst op = cell.outputs.find(op => op.outputId === data.outputId || op.alternativeOutputId === data.outputId);\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/notebook.contribution.ts",
"type": "replace",
"edit_start_line_idx": 457
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { isCancellationError, isSigPipeError, onUnexpectedError, setUnexpectedErrorHandler } from 'vs/base/common/errors';
import BaseErrorTelemetry from 'vs/platform/telemetry/common/errorTelemetry';
export default class ErrorTelemetry extends BaseErrorTelemetry {
protected override installErrorListeners(): void {
setUnexpectedErrorHandler(err => console.error(err));
// Print a console message when rejection isn't handled within N seconds. For details:
// see https://nodejs.org/api/process.html#process_event_unhandledrejection
// and https://nodejs.org/api/process.html#process_event_rejectionhandled
const unhandledPromises: Promise<any>[] = [];
process.on('unhandledRejection', (reason: any, promise: Promise<any>) => {
unhandledPromises.push(promise);
setTimeout(() => {
const idx = unhandledPromises.indexOf(promise);
if (idx >= 0) {
promise.catch(e => {
unhandledPromises.splice(idx, 1);
if (!isCancellationError(e)) {
console.warn(`rejected promise not handled within 1 second: ${e}`);
if (e.stack) {
console.warn(`stack trace: ${e.stack}`);
}
if (reason) {
onUnexpectedError(reason);
}
}
});
}
}, 1000);
});
process.on('rejectionHandled', (promise: Promise<any>) => {
const idx = unhandledPromises.indexOf(promise);
if (idx >= 0) {
unhandledPromises.splice(idx, 1);
}
});
// Print a console message when an exception isn't handled.
process.on('uncaughtException', (err: Error | NodeJS.ErrnoException) => {
if (isSigPipeError(err)) {
return;
}
onUnexpectedError(err);
});
}
}
| src/vs/platform/telemetry/node/errorTelemetry.ts | 0 | https://github.com/microsoft/vscode/commit/94956b4c3fb38badce912cae3d5a531502669885 | [
0.00017802856746129692,
0.0001729015348246321,
0.00016894568398129195,
0.00017255518469028175,
0.0000027138164568896173
] |
{
"id": 1,
"code_window": [
"\t\tif (!data) {\n",
"\t\t\treturn null;\n",
"\t\t}\n",
"\n",
"\t\tconst ref = await this._notebookModelResolverService.resolve(data.notebook);\n",
"\t\tconst cell = ref.object.notebook.cells.find(cell => !!cell.outputs.find(op => op.outputId === data.outputId));\n",
"\n",
"\t\tif (!cell) {\n",
"\t\t\tref.dispose();\n",
"\t\t\treturn null;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst cell = ref.object.notebook.cells.find(cell => !!cell.outputs.find(op => op.outputId === data.outputId || op.alternativeOutputId === data.outputId));\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/notebook.contribution.ts",
"type": "replace",
"edit_start_line_idx": 493
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Schemas } from 'vs/base/common/network';
import { IDisposable, Disposable, DisposableStore, dispose } from 'vs/base/common/lifecycle';
import { parse } from 'vs/base/common/marshalling';
import { extname, isEqual } from 'vs/base/common/resources';
import { assertType } from 'vs/base/common/types';
import { URI } from 'vs/base/common/uri';
import { toFormattedString } from 'vs/base/common/jsonFormatter';
import { ITextModel, ITextBufferFactory, DefaultEndOfLine, ITextBuffer } from 'vs/editor/common/model';
import { IModelService } from 'vs/editor/common/services/model';
import { ILanguageSelection, ILanguageService } from 'vs/editor/common/languages/language';
import { ITextModelContentProvider, ITextModelService } from 'vs/editor/common/services/resolverService';
import * as nls from 'vs/nls';
import { Extensions, IConfigurationPropertySchema, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { Registry } from 'vs/platform/registry/common/platform';
import { EditorPaneDescriptor, IEditorPaneRegistry } from 'vs/workbench/browser/editor';
import { Extensions as WorkbenchExtensions, IWorkbenchContribution, IWorkbenchContributionsRegistry } from 'vs/workbench/common/contributions';
import { IEditorSerializer, IEditorFactoryRegistry, EditorExtensions } from 'vs/workbench/common/editor';
import { EditorInput } from 'vs/workbench/common/editor/editorInput';
import { NotebookEditor } from 'vs/workbench/contrib/notebook/browser/notebookEditor';
import { NotebookEditorInput, NotebookEditorInputOptions } from 'vs/workbench/contrib/notebook/common/notebookEditorInput';
import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';
import { NotebookService } from 'vs/workbench/contrib/notebook/browser/services/notebookServiceImpl';
import { CellKind, CellUri, IResolvedNotebookEditorModel, NotebookWorkingCopyTypeIdentifier, NotebookSetting, ICellOutput, ICell } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IUndoRedoService } from 'vs/platform/undoRedo/common/undoRedo';
import { INotebookEditorModelResolverService } from 'vs/workbench/contrib/notebook/common/notebookEditorModelResolverService';
import { NotebookDiffEditorInput } from 'vs/workbench/contrib/notebook/common/notebookDiffEditorInput';
import { NotebookTextDiffEditor } from 'vs/workbench/contrib/notebook/browser/diff/notebookDiffEditor';
import { INotebookEditorWorkerService } from 'vs/workbench/contrib/notebook/common/services/notebookWorkerService';
import { NotebookEditorWorkerServiceImpl } from 'vs/workbench/contrib/notebook/browser/services/notebookWorkerServiceImpl';
import { INotebookCellStatusBarService } from 'vs/workbench/contrib/notebook/common/notebookCellStatusBarService';
import { NotebookCellStatusBarService } from 'vs/workbench/contrib/notebook/browser/services/notebookCellStatusBarServiceImpl';
import { INotebookEditorService } from 'vs/workbench/contrib/notebook/browser/services/notebookEditorService';
import { NotebookEditorWidgetService } from 'vs/workbench/contrib/notebook/browser/services/notebookEditorServiceImpl';
import { IJSONContributionRegistry, Extensions as JSONExtensions } from 'vs/platform/jsonschemas/common/jsonContributionRegistry';
import { IJSONSchema, IJSONSchemaMap } from 'vs/base/common/jsonSchema';
import { Event } from 'vs/base/common/event';
import { getFormattedMetadataJSON, getStreamOutputData } from 'vs/workbench/contrib/notebook/browser/diff/diffElementViewModel';
import { NotebookModelResolverServiceImpl } from 'vs/workbench/contrib/notebook/common/notebookEditorModelResolverServiceImpl';
import { INotebookKernelHistoryService, INotebookKernelService } from 'vs/workbench/contrib/notebook/common/notebookKernelService';
import { NotebookKernelService } from 'vs/workbench/contrib/notebook/browser/services/notebookKernelServiceImpl';
import { IWorkingCopyIdentifier } from 'vs/workbench/services/workingCopy/common/workingCopy';
import { IResourceEditorInput } from 'vs/platform/editor/common/editor';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IWorkingCopyEditorHandler, IWorkingCopyEditorService } from 'vs/workbench/services/workingCopy/common/workingCopyEditorService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ILabelService } from 'vs/platform/label/common/label';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { NotebookRendererMessagingService } from 'vs/workbench/contrib/notebook/browser/services/notebookRendererMessagingServiceImpl';
import { INotebookRendererMessagingService } from 'vs/workbench/contrib/notebook/common/notebookRendererMessagingService';
// Editor Controller
import 'vs/workbench/contrib/notebook/browser/controller/coreActions';
import 'vs/workbench/contrib/notebook/browser/controller/insertCellActions';
import 'vs/workbench/contrib/notebook/browser/controller/executeActions';
import 'vs/workbench/contrib/notebook/browser/controller/layoutActions';
import 'vs/workbench/contrib/notebook/browser/controller/editActions';
import 'vs/workbench/contrib/notebook/browser/controller/cellOutputActions';
import 'vs/workbench/contrib/notebook/browser/controller/apiActions';
import 'vs/workbench/contrib/notebook/browser/controller/foldingController';
// Editor Contribution
import 'vs/workbench/contrib/notebook/browser/contrib/clipboard/notebookClipboard';
import 'vs/workbench/contrib/notebook/browser/contrib/find/notebookFind';
import 'vs/workbench/contrib/notebook/browser/contrib/format/formatting';
import 'vs/workbench/contrib/notebook/browser/contrib/saveParticipants/saveParticipants';
import 'vs/workbench/contrib/notebook/browser/contrib/gettingStarted/notebookGettingStarted';
import 'vs/workbench/contrib/notebook/browser/contrib/layout/layoutActions';
import 'vs/workbench/contrib/notebook/browser/contrib/marker/markerProvider';
import 'vs/workbench/contrib/notebook/browser/contrib/navigation/arrow';
import 'vs/workbench/contrib/notebook/browser/contrib/outline/notebookOutline';
import 'vs/workbench/contrib/notebook/browser/contrib/profile/notebookProfile';
import 'vs/workbench/contrib/notebook/browser/contrib/cellStatusBar/statusBarProviders';
import 'vs/workbench/contrib/notebook/browser/contrib/cellStatusBar/contributedStatusBarItemController';
import 'vs/workbench/contrib/notebook/browser/contrib/cellStatusBar/executionStatusBarItemController';
import 'vs/workbench/contrib/notebook/browser/contrib/editorStatusBar/editorStatusBar';
import 'vs/workbench/contrib/notebook/browser/contrib/undoRedo/notebookUndoRedo';
import 'vs/workbench/contrib/notebook/browser/contrib/cellCommands/cellCommands';
import 'vs/workbench/contrib/notebook/browser/contrib/viewportWarmup/viewportWarmup';
import 'vs/workbench/contrib/notebook/browser/contrib/troubleshoot/layout';
import 'vs/workbench/contrib/notebook/browser/contrib/debug/notebookBreakpoints';
import 'vs/workbench/contrib/notebook/browser/contrib/debug/notebookCellPausing';
import 'vs/workbench/contrib/notebook/browser/contrib/debug/notebookDebugDecorations';
import 'vs/workbench/contrib/notebook/browser/contrib/execute/executionEditorProgress';
import 'vs/workbench/contrib/notebook/browser/contrib/kernelDetection/notebookKernelDetection';
// Diff Editor Contribution
import 'vs/workbench/contrib/notebook/browser/diff/notebookDiffActions';
// Services
import { editorOptionsRegistry } from 'vs/editor/common/config/editorOptions';
import { NotebookExecutionStateService } from 'vs/workbench/contrib/notebook/browser/services/notebookExecutionStateServiceImpl';
import { NotebookExecutionService } from 'vs/workbench/contrib/notebook/browser/services/notebookExecutionServiceImpl';
import { INotebookExecutionService } from 'vs/workbench/contrib/notebook/common/notebookExecutionService';
import { INotebookKeymapService } from 'vs/workbench/contrib/notebook/common/notebookKeymapService';
import { NotebookKeymapService } from 'vs/workbench/contrib/notebook/browser/services/notebookKeymapServiceImpl';
import { PLAINTEXT_LANGUAGE_ID } from 'vs/editor/common/languages/modesRegistry';
import { INotebookExecutionStateService } from 'vs/workbench/contrib/notebook/common/notebookExecutionStateService';
import { ILanguageFeaturesService } from 'vs/editor/common/services/languageFeatures';
import { NotebookInfo } from 'vs/editor/common/languageFeatureRegistry';
import { COMMENTEDITOR_DECORATION_KEY } from 'vs/workbench/contrib/comments/browser/commentReply';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import { NotebookKernelHistoryService } from 'vs/workbench/contrib/notebook/browser/services/notebookKernelHistoryServiceImpl';
import { INotebookLoggingService } from 'vs/workbench/contrib/notebook/common/notebookLoggingService';
import { NotebookLoggingService } from 'vs/workbench/contrib/notebook/browser/services/notebookLoggingServiceImpl';
import product from 'vs/platform/product/common/product';
import { NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_OUTPUT_FOCUSED } from 'vs/workbench/contrib/notebook/common/notebookContextKeys';
import { runAccessibilityHelpAction, showAccessibleOutput } from 'vs/workbench/contrib/notebook/browser/notebookAccessibility';
import { IAccessibleViewService } from 'vs/workbench/contrib/accessibility/browser/accessibleView';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { AccessibilityHelpAction, AccessibleViewAction } from 'vs/workbench/contrib/accessibility/browser/accessibleViewActions';
/*--------------------------------------------------------------------------------------------- */
Registry.as<IEditorPaneRegistry>(EditorExtensions.EditorPane).registerEditorPane(
EditorPaneDescriptor.create(
NotebookEditor,
NotebookEditor.ID,
'Notebook Editor'
),
[
new SyncDescriptor(NotebookEditorInput)
]
);
Registry.as<IEditorPaneRegistry>(EditorExtensions.EditorPane).registerEditorPane(
EditorPaneDescriptor.create(
NotebookTextDiffEditor,
NotebookTextDiffEditor.ID,
'Notebook Diff Editor'
),
[
new SyncDescriptor(NotebookDiffEditorInput)
]
);
class NotebookDiffEditorSerializer implements IEditorSerializer {
canSerialize(): boolean {
return true;
}
serialize(input: EditorInput): string {
assertType(input instanceof NotebookDiffEditorInput);
return JSON.stringify({
resource: input.resource,
originalResource: input.original.resource,
name: input.getName(),
originalName: input.original.getName(),
textDiffName: input.getName(),
viewType: input.viewType,
});
}
deserialize(instantiationService: IInstantiationService, raw: string) {
type Data = { resource: URI; originalResource: URI; name: string; originalName: string; viewType: string; textDiffName: string | undefined; group: number };
const data = <Data>parse(raw);
if (!data) {
return undefined;
}
const { resource, originalResource, name, viewType } = data;
if (!data || !URI.isUri(resource) || !URI.isUri(originalResource) || typeof name !== 'string' || typeof viewType !== 'string') {
return undefined;
}
const input = NotebookDiffEditorInput.create(instantiationService, resource, name, undefined, originalResource, viewType);
return input;
}
static canResolveBackup(editorInput: EditorInput, backupResource: URI): boolean {
return false;
}
}
type SerializedNotebookEditorData = { resource: URI; viewType: string; options?: NotebookEditorInputOptions };
class NotebookEditorSerializer implements IEditorSerializer {
canSerialize(): boolean {
return true;
}
serialize(input: EditorInput): string {
assertType(input instanceof NotebookEditorInput);
const data: SerializedNotebookEditorData = {
resource: input.resource,
viewType: input.viewType,
options: input.options
};
return JSON.stringify(data);
}
deserialize(instantiationService: IInstantiationService, raw: string) {
const data = <SerializedNotebookEditorData>parse(raw);
if (!data) {
return undefined;
}
const { resource, viewType, options } = data;
if (!data || !URI.isUri(resource) || typeof viewType !== 'string') {
return undefined;
}
const input = NotebookEditorInput.create(instantiationService, resource, viewType, options);
return input;
}
}
Registry.as<IEditorFactoryRegistry>(EditorExtensions.EditorFactory).registerEditorSerializer(
NotebookEditorInput.ID,
NotebookEditorSerializer
);
Registry.as<IEditorFactoryRegistry>(EditorExtensions.EditorFactory).registerEditorSerializer(
NotebookDiffEditorInput.ID,
NotebookDiffEditorSerializer
);
export class NotebookContribution extends Disposable implements IWorkbenchContribution {
private _uriComparisonKeyComputer?: IDisposable;
constructor(
@IUndoRedoService undoRedoService: IUndoRedoService,
@IConfigurationService configurationService: IConfigurationService,
@ICodeEditorService private readonly codeEditorService: ICodeEditorService,
) {
super();
this.updateCellUndoRedoComparisonKey(configurationService, undoRedoService);
// Watch for changes to undoRedoPerCell setting
this._register(configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration(NotebookSetting.undoRedoPerCell)) {
this.updateCellUndoRedoComparisonKey(configurationService, undoRedoService);
}
}));
// register comment decoration
this.codeEditorService.registerDecorationType('comment-controller', COMMENTEDITOR_DECORATION_KEY, {});
}
// Add or remove the cell undo redo comparison key based on the user setting
private updateCellUndoRedoComparisonKey(configurationService: IConfigurationService, undoRedoService: IUndoRedoService) {
const undoRedoPerCell = configurationService.getValue<boolean>(NotebookSetting.undoRedoPerCell);
if (!undoRedoPerCell) {
// Add comparison key to map cell => main document
if (!this._uriComparisonKeyComputer) {
this._uriComparisonKeyComputer = undoRedoService.registerUriComparisonKeyComputer(CellUri.scheme, {
getComparisonKey: (uri: URI): string => {
if (undoRedoPerCell) {
return uri.toString();
}
return NotebookContribution._getCellUndoRedoComparisonKey(uri);
}
});
}
} else {
// Dispose comparison key
this._uriComparisonKeyComputer?.dispose();
this._uriComparisonKeyComputer = undefined;
}
}
private static _getCellUndoRedoComparisonKey(uri: URI) {
const data = CellUri.parse(uri);
if (!data) {
return uri.toString();
}
return data.notebook.toString();
}
override dispose(): void {
super.dispose();
this._uriComparisonKeyComputer?.dispose();
}
}
class CellContentProvider implements ITextModelContentProvider {
private readonly _registration: IDisposable;
constructor(
@ITextModelService textModelService: ITextModelService,
@IModelService private readonly _modelService: IModelService,
@ILanguageService private readonly _languageService: ILanguageService,
@INotebookEditorModelResolverService private readonly _notebookModelResolverService: INotebookEditorModelResolverService,
) {
this._registration = textModelService.registerTextModelContentProvider(CellUri.scheme, this);
}
dispose(): void {
this._registration.dispose();
}
async provideTextContent(resource: URI): Promise<ITextModel | null> {
const existing = this._modelService.getModel(resource);
if (existing) {
return existing;
}
const data = CellUri.parse(resource);
// const data = parseCellUri(resource);
if (!data) {
return null;
}
const ref = await this._notebookModelResolverService.resolve(data.notebook);
let result: ITextModel | null = null;
if (!ref.object.isResolved()) {
return null;
}
for (const cell of ref.object.notebook.cells) {
if (cell.uri.toString() === resource.toString()) {
const bufferFactory: ITextBufferFactory = {
create: (defaultEOL) => {
const newEOL = (defaultEOL === DefaultEndOfLine.CRLF ? '\r\n' : '\n');
(cell.textBuffer as ITextBuffer).setEOL(newEOL);
return { textBuffer: cell.textBuffer as ITextBuffer, disposable: Disposable.None };
},
getFirstLineText: (limit: number) => {
return cell.textBuffer.getLineContent(1).substring(0, limit);
}
};
const languageId = this._languageService.getLanguageIdByLanguageName(cell.language);
const languageSelection = languageId ? this._languageService.createById(languageId) : (cell.cellKind === CellKind.Markup ? this._languageService.createById('markdown') : this._languageService.createByFilepathOrFirstLine(resource, cell.textBuffer.getLineContent(1)));
result = this._modelService.createModel(
bufferFactory,
languageSelection,
resource
);
break;
}
}
if (!result) {
ref.dispose();
return null;
}
const once = Event.any(result.onWillDispose, ref.object.notebook.onWillDispose)(() => {
once.dispose();
ref.dispose();
});
return result;
}
}
class CellInfoContentProvider {
private readonly _disposables: IDisposable[] = [];
constructor(
@ITextModelService textModelService: ITextModelService,
@IModelService private readonly _modelService: IModelService,
@ILanguageService private readonly _languageService: ILanguageService,
@ILabelService private readonly _labelService: ILabelService,
@INotebookEditorModelResolverService private readonly _notebookModelResolverService: INotebookEditorModelResolverService,
) {
this._disposables.push(textModelService.registerTextModelContentProvider(Schemas.vscodeNotebookCellMetadata, {
provideTextContent: this.provideMetadataTextContent.bind(this)
}));
this._disposables.push(textModelService.registerTextModelContentProvider(Schemas.vscodeNotebookCellOutput, {
provideTextContent: this.provideOutputTextContent.bind(this)
}));
this._disposables.push(this._labelService.registerFormatter({
scheme: Schemas.vscodeNotebookCellMetadata,
formatting: {
label: '${path} (metadata)',
separator: '/'
}
}));
this._disposables.push(this._labelService.registerFormatter({
scheme: Schemas.vscodeNotebookCellOutput,
formatting: {
label: '${path} (output)',
separator: '/'
}
}));
}
dispose(): void {
dispose(this._disposables);
}
async provideMetadataTextContent(resource: URI): Promise<ITextModel | null> {
const existing = this._modelService.getModel(resource);
if (existing) {
return existing;
}
const data = CellUri.parseCellPropertyUri(resource, Schemas.vscodeNotebookCellMetadata);
if (!data) {
return null;
}
const ref = await this._notebookModelResolverService.resolve(data.notebook);
let result: ITextModel | null = null;
const mode = this._languageService.createById('json');
for (const cell of ref.object.notebook.cells) {
if (cell.handle === data.handle) {
const metadataSource = getFormattedMetadataJSON(ref.object.notebook, cell.metadata, cell.language);
result = this._modelService.createModel(
metadataSource,
mode,
resource
);
break;
}
}
if (!result) {
ref.dispose();
return null;
}
const once = result.onWillDispose(() => {
once.dispose();
ref.dispose();
});
return result;
}
private parseStreamOutput(op?: ICellOutput): { content: string; mode: ILanguageSelection } | undefined {
if (!op) {
return;
}
const streamOutputData = getStreamOutputData(op.outputs);
if (streamOutputData) {
return {
content: streamOutputData,
mode: this._languageService.createById(PLAINTEXT_LANGUAGE_ID)
};
}
return;
}
private _getResult(data: {
notebook: URI;
outputId?: string | undefined;
}, cell: ICell) {
let result: { content: string; mode: ILanguageSelection } | undefined = undefined;
const mode = this._languageService.createById('json');
const op = cell.outputs.find(op => op.outputId === data.outputId);
const streamOutputData = this.parseStreamOutput(op);
if (streamOutputData) {
result = streamOutputData;
return result;
}
const obj = cell.outputs.map(output => ({
metadata: output.metadata,
outputItems: output.outputs.map(opit => ({
mimeType: opit.mime,
data: opit.data.toString()
}))
}));
const outputSource = toFormattedString(obj, {});
result = {
content: outputSource,
mode
};
return result;
}
async provideOutputTextContent(resource: URI): Promise<ITextModel | null> {
const existing = this._modelService.getModel(resource);
if (existing) {
return existing;
}
const data = CellUri.parseCellOutputUri(resource);
if (!data) {
return null;
}
const ref = await this._notebookModelResolverService.resolve(data.notebook);
const cell = ref.object.notebook.cells.find(cell => !!cell.outputs.find(op => op.outputId === data.outputId));
if (!cell) {
ref.dispose();
return null;
}
const result = this._getResult(data, cell);
if (!result) {
ref.dispose();
return null;
}
const model = this._modelService.createModel(result.content, result.mode, resource);
const cellModelListener = Event.any(cell.onDidChangeOutputs ?? Event.None, cell.onDidChangeOutputItems ?? Event.None)(() => {
const newResult = this._getResult(data, cell);
if (!newResult) {
return;
}
model.setValue(newResult.content);
model.setLanguage(newResult.mode.languageId);
});
const once = model.onWillDispose(() => {
once.dispose();
cellModelListener.dispose();
ref.dispose();
});
return model;
}
}
class RegisterSchemasContribution extends Disposable implements IWorkbenchContribution {
constructor() {
super();
this.registerMetadataSchemas();
}
private registerMetadataSchemas(): void {
const jsonRegistry = Registry.as<IJSONContributionRegistry>(JSONExtensions.JSONContribution);
const metadataSchema: IJSONSchema = {
properties: {
['language']: {
type: 'string',
description: 'The language for the cell'
}
},
// patternProperties: allSettings.patternProperties,
additionalProperties: true,
allowTrailingCommas: true,
allowComments: true
};
jsonRegistry.registerSchema('vscode://schemas/notebook/cellmetadata', metadataSchema);
}
}
class NotebookEditorManager implements IWorkbenchContribution {
private readonly _disposables = new DisposableStore();
constructor(
@IEditorService private readonly _editorService: IEditorService,
@INotebookEditorModelResolverService private readonly _notebookEditorModelService: INotebookEditorModelResolverService,
@IEditorGroupsService editorGroups: IEditorGroupsService
) {
// OPEN notebook editor for models that have turned dirty without being visible in an editor
type E = IResolvedNotebookEditorModel;
this._disposables.add(Event.debounce<E, E[]>(
this._notebookEditorModelService.onDidChangeDirty,
(last, current) => !last ? [current] : [...last, current],
100
)(this._openMissingDirtyNotebookEditors, this));
// CLOSE editors when we are about to open conflicting notebooks
this._disposables.add(_notebookEditorModelService.onWillFailWithConflict(e => {
for (const group of editorGroups.groups) {
const conflictInputs = group.editors.filter(input => input instanceof NotebookEditorInput && input.viewType !== e.viewType && isEqual(input.resource, e.resource));
const p = group.closeEditors(conflictInputs);
e.waitUntil(p);
}
}));
}
dispose(): void {
this._disposables.dispose();
}
private _openMissingDirtyNotebookEditors(models: IResolvedNotebookEditorModel[]): void {
const result: IResourceEditorInput[] = [];
for (const model of models) {
if (model.isDirty() && !this._editorService.isOpened({ resource: model.resource, typeId: NotebookEditorInput.ID, editorId: model.viewType }) && extname(model.resource) !== '.interactive') {
result.push({
resource: model.resource,
options: { inactive: true, preserveFocus: true, pinned: true, override: model.viewType }
});
}
}
if (result.length > 0) {
this._editorService.openEditors(result);
}
}
}
class SimpleNotebookWorkingCopyEditorHandler extends Disposable implements IWorkbenchContribution, IWorkingCopyEditorHandler {
constructor(
@IInstantiationService private readonly _instantiationService: IInstantiationService,
@IWorkingCopyEditorService private readonly _workingCopyEditorService: IWorkingCopyEditorService,
@IExtensionService private readonly _extensionService: IExtensionService,
@INotebookService private readonly _notebookService: INotebookService
) {
super();
this._installHandler();
}
async handles(workingCopy: IWorkingCopyIdentifier): Promise<boolean> {
const viewType = this.handlesSync(workingCopy);
if (!viewType) {
return false;
}
return this._notebookService.canResolve(viewType);
}
private handlesSync(workingCopy: IWorkingCopyIdentifier): string /* viewType */ | undefined {
const viewType = this._getViewType(workingCopy);
if (!viewType || viewType === 'interactive') {
return undefined;
}
return viewType;
}
isOpen(workingCopy: IWorkingCopyIdentifier, editor: EditorInput): boolean {
if (!this.handlesSync(workingCopy)) {
return false;
}
return editor instanceof NotebookEditorInput && editor.viewType === this._getViewType(workingCopy) && isEqual(workingCopy.resource, editor.resource);
}
createEditor(workingCopy: IWorkingCopyIdentifier): EditorInput {
return NotebookEditorInput.create(this._instantiationService, workingCopy.resource, this._getViewType(workingCopy)!);
}
private async _installHandler(): Promise<void> {
await this._extensionService.whenInstalledExtensionsRegistered();
this._register(this._workingCopyEditorService.registerHandler(this));
}
private _getViewType(workingCopy: IWorkingCopyIdentifier): string | undefined {
return NotebookWorkingCopyTypeIdentifier.parse(workingCopy.typeId);
}
}
class NotebookLanguageSelectorScoreRefine {
constructor(
@INotebookService private readonly _notebookService: INotebookService,
@ILanguageFeaturesService languageFeaturesService: ILanguageFeaturesService,
) {
languageFeaturesService.setNotebookTypeResolver(this._getNotebookInfo.bind(this));
}
private _getNotebookInfo(uri: URI): NotebookInfo | undefined {
const cellUri = CellUri.parse(uri);
if (!cellUri) {
return undefined;
}
const notebook = this._notebookService.getNotebookTextModel(cellUri.notebook);
if (!notebook) {
return undefined;
}
return {
uri: notebook.uri,
type: notebook.viewType
};
}
}
class NotebookAccessibilityHelpContribution extends Disposable {
static ID: 'notebookAccessibilityHelpContribution';
constructor() {
super();
this._register(AccessibilityHelpAction.addImplementation(105, 'notebook', async accessor => {
const codeEditor = accessor.get(ICodeEditorService).getActiveCodeEditor() || accessor.get(ICodeEditorService).getFocusedCodeEditor();
if (!codeEditor) {
return;
}
runAccessibilityHelpAction(accessor, codeEditor);
}, NOTEBOOK_IS_ACTIVE_EDITOR));
}
}
class NotebookAccessibleViewContribution extends Disposable {
static ID: 'chatAccessibleViewContribution';
constructor() {
super();
this._register(AccessibleViewAction.addImplementation(100, 'notebook', accessor => {
const accessibleViewService = accessor.get(IAccessibleViewService);
const editorService = accessor.get(IEditorService);
return showAccessibleOutput(accessibleViewService, editorService);
},
ContextKeyExpr.and(NOTEBOOK_OUTPUT_FOCUSED, ContextKeyExpr.equals('resourceExtname', '.ipynb'))
));
}
}
const workbenchContributionsRegistry = Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench);
workbenchContributionsRegistry.registerWorkbenchContribution(NotebookContribution, LifecyclePhase.Starting);
workbenchContributionsRegistry.registerWorkbenchContribution(CellContentProvider, LifecyclePhase.Starting);
workbenchContributionsRegistry.registerWorkbenchContribution(CellInfoContentProvider, LifecyclePhase.Starting);
workbenchContributionsRegistry.registerWorkbenchContribution(RegisterSchemasContribution, LifecyclePhase.Starting);
workbenchContributionsRegistry.registerWorkbenchContribution(NotebookEditorManager, LifecyclePhase.Ready);
workbenchContributionsRegistry.registerWorkbenchContribution(NotebookLanguageSelectorScoreRefine, LifecyclePhase.Ready);
workbenchContributionsRegistry.registerWorkbenchContribution(SimpleNotebookWorkingCopyEditorHandler, LifecyclePhase.Ready);
workbenchContributionsRegistry.registerWorkbenchContribution(NotebookAccessibilityHelpContribution, LifecyclePhase.Eventually);
workbenchContributionsRegistry.registerWorkbenchContribution(NotebookAccessibleViewContribution, LifecyclePhase.Eventually);
registerSingleton(INotebookService, NotebookService, InstantiationType.Delayed);
registerSingleton(INotebookEditorWorkerService, NotebookEditorWorkerServiceImpl, InstantiationType.Delayed);
registerSingleton(INotebookEditorModelResolverService, NotebookModelResolverServiceImpl, InstantiationType.Delayed);
registerSingleton(INotebookCellStatusBarService, NotebookCellStatusBarService, InstantiationType.Delayed);
registerSingleton(INotebookEditorService, NotebookEditorWidgetService, InstantiationType.Delayed);
registerSingleton(INotebookKernelService, NotebookKernelService, InstantiationType.Delayed);
registerSingleton(INotebookKernelHistoryService, NotebookKernelHistoryService, InstantiationType.Delayed);
registerSingleton(INotebookExecutionService, NotebookExecutionService, InstantiationType.Delayed);
registerSingleton(INotebookExecutionStateService, NotebookExecutionStateService, InstantiationType.Delayed);
registerSingleton(INotebookRendererMessagingService, NotebookRendererMessagingService, InstantiationType.Delayed);
registerSingleton(INotebookKeymapService, NotebookKeymapService, InstantiationType.Delayed);
registerSingleton(INotebookLoggingService, NotebookLoggingService, InstantiationType.Delayed);
const schemas: IJSONSchemaMap = {};
function isConfigurationPropertySchema(x: IConfigurationPropertySchema | { [path: string]: IConfigurationPropertySchema }): x is IConfigurationPropertySchema {
return (typeof x.type !== 'undefined' || typeof x.anyOf !== 'undefined');
}
for (const editorOption of editorOptionsRegistry) {
const schema = editorOption.schema;
if (schema) {
if (isConfigurationPropertySchema(schema)) {
schemas[`editor.${editorOption.name}`] = schema;
} else {
for (const key in schema) {
if (Object.hasOwnProperty.call(schema, key)) {
schemas[key] = schema[key];
}
}
}
}
}
const editorOptionsCustomizationSchema: IConfigurationPropertySchema = {
description: nls.localize('notebook.editorOptions.experimentalCustomization', 'Settings for code editors used in notebooks. This can be used to customize most editor.* settings.'),
default: {},
allOf: [
{
properties: schemas,
}
// , {
// patternProperties: {
// '^\\[.*\\]$': {
// type: 'object',
// default: {},
// properties: schemas
// }
// }
// }
],
tags: ['notebookLayout']
};
const configurationRegistry = Registry.as<IConfigurationRegistry>(Extensions.Configuration);
configurationRegistry.registerConfiguration({
id: 'notebook',
order: 100,
title: nls.localize('notebookConfigurationTitle', "Notebook"),
type: 'object',
properties: {
[NotebookSetting.displayOrder]: {
description: nls.localize('notebook.displayOrder.description', "Priority list for output mime types"),
type: 'array',
items: {
type: 'string'
},
default: []
},
[NotebookSetting.cellToolbarLocation]: {
description: nls.localize('notebook.cellToolbarLocation.description', "Where the cell toolbar should be shown, or whether it should be hidden."),
type: 'object',
additionalProperties: {
markdownDescription: nls.localize('notebook.cellToolbarLocation.viewType', "Configure the cell toolbar position for for specific file types"),
type: 'string',
enum: ['left', 'right', 'hidden']
},
default: {
'default': 'right'
},
tags: ['notebookLayout']
},
[NotebookSetting.showCellStatusBar]: {
description: nls.localize('notebook.showCellStatusbar.description', "Whether the cell status bar should be shown."),
type: 'string',
enum: ['hidden', 'visible', 'visibleAfterExecute'],
enumDescriptions: [
nls.localize('notebook.showCellStatusbar.hidden.description', "The cell Status bar is always hidden."),
nls.localize('notebook.showCellStatusbar.visible.description', "The cell Status bar is always visible."),
nls.localize('notebook.showCellStatusbar.visibleAfterExecute.description', "The cell Status bar is hidden until the cell has executed. Then it becomes visible to show the execution status.")],
default: 'visible',
tags: ['notebookLayout']
},
[NotebookSetting.textDiffEditorPreview]: {
description: nls.localize('notebook.diff.enablePreview.description', "Whether to use the enhanced text diff editor for notebook."),
type: 'boolean',
default: true,
tags: ['notebookLayout']
},
[NotebookSetting.diffOverviewRuler]: {
description: nls.localize('notebook.diff.enableOverviewRuler.description', "Whether to render the overview ruler in the diff editor for notebook."),
type: 'boolean',
default: false,
tags: ['notebookLayout']
},
[NotebookSetting.cellToolbarVisibility]: {
markdownDescription: nls.localize('notebook.cellToolbarVisibility.description', "Whether the cell toolbar should appear on hover or click."),
type: 'string',
enum: ['hover', 'click'],
default: 'click',
tags: ['notebookLayout']
},
[NotebookSetting.undoRedoPerCell]: {
description: nls.localize('notebook.undoRedoPerCell.description', "Whether to use separate undo/redo stack for each cell."),
type: 'boolean',
default: true,
tags: ['notebookLayout']
},
[NotebookSetting.compactView]: {
description: nls.localize('notebook.compactView.description', "Control whether the notebook editor should be rendered in a compact form. For example, when turned on, it will decrease the left margin width."),
type: 'boolean',
default: true,
tags: ['notebookLayout']
},
[NotebookSetting.focusIndicator]: {
description: nls.localize('notebook.focusIndicator.description', "Controls where the focus indicator is rendered, either along the cell borders or on the left gutter."),
type: 'string',
enum: ['border', 'gutter'],
default: 'gutter',
tags: ['notebookLayout']
},
[NotebookSetting.insertToolbarLocation]: {
description: nls.localize('notebook.insertToolbarPosition.description', "Control where the insert cell actions should appear."),
type: 'string',
enum: ['betweenCells', 'notebookToolbar', 'both', 'hidden'],
enumDescriptions: [
nls.localize('insertToolbarLocation.betweenCells', "A toolbar that appears on hover between cells."),
nls.localize('insertToolbarLocation.notebookToolbar', "The toolbar at the top of the notebook editor."),
nls.localize('insertToolbarLocation.both', "Both toolbars."),
nls.localize('insertToolbarLocation.hidden', "The insert actions don't appear anywhere."),
],
default: 'both',
tags: ['notebookLayout']
},
[NotebookSetting.globalToolbar]: {
description: nls.localize('notebook.globalToolbar.description', "Control whether to render a global toolbar inside the notebook editor."),
type: 'boolean',
default: true,
tags: ['notebookLayout']
},
[NotebookSetting.stickyScroll]: {
description: nls.localize('notebook.stickyScroll.description', "Experimental. Control whether to render notebook Sticky Scroll headers in the notebook editor."),
type: 'boolean',
default: false,
tags: ['notebookLayout']
},
[NotebookSetting.consolidatedOutputButton]: {
description: nls.localize('notebook.consolidatedOutputButton.description', "Control whether outputs action should be rendered in the output toolbar."),
type: 'boolean',
default: true,
tags: ['notebookLayout']
},
[NotebookSetting.showFoldingControls]: {
description: nls.localize('notebook.showFoldingControls.description', "Controls when the Markdown header folding arrow is shown."),
type: 'string',
enum: ['always', 'never', 'mouseover'],
enumDescriptions: [
nls.localize('showFoldingControls.always', "The folding controls are always visible."),
nls.localize('showFoldingControls.never', "Never show the folding controls and reduce the gutter size."),
nls.localize('showFoldingControls.mouseover', "The folding controls are visible only on mouseover."),
],
default: 'mouseover',
tags: ['notebookLayout']
},
[NotebookSetting.dragAndDropEnabled]: {
description: nls.localize('notebook.dragAndDrop.description', "Control whether the notebook editor should allow moving cells through drag and drop."),
type: 'boolean',
default: true,
tags: ['notebookLayout']
},
[NotebookSetting.consolidatedRunButton]: {
description: nls.localize('notebook.consolidatedRunButton.description', "Control whether extra actions are shown in a dropdown next to the run button."),
type: 'boolean',
default: false,
tags: ['notebookLayout']
},
[NotebookSetting.globalToolbarShowLabel]: {
description: nls.localize('notebook.globalToolbarShowLabel', "Control whether the actions on the notebook toolbar should render label or not."),
type: 'string',
enum: ['always', 'never', 'dynamic'],
default: 'always',
tags: ['notebookLayout']
},
[NotebookSetting.textOutputLineLimit]: {
markdownDescription: nls.localize('notebook.textOutputLineLimit', "Controls how many lines of text are displayed in a text output. If {0} is enabled, this setting is used to determine the scroll height of the output.", '`#notebook.output.scrolling#`'),
type: 'number',
default: 30,
tags: ['notebookLayout', 'notebookOutputLayout']
},
[NotebookSetting.markupFontSize]: {
markdownDescription: nls.localize('notebook.markup.fontSize', "Controls the font size in pixels of rendered markup in notebooks. When set to {0}, 120% of {1} is used.", '`0`', '`#editor.fontSize#`'),
type: 'number',
default: 0,
tags: ['notebookLayout']
},
[NotebookSetting.cellEditorOptionsCustomizations]: editorOptionsCustomizationSchema,
[NotebookSetting.interactiveWindowCollapseCodeCells]: {
markdownDescription: nls.localize('notebook.interactiveWindow.collapseCodeCells', "Controls whether code cells in the interactive window are collapsed by default."),
type: 'string',
enum: ['always', 'never', 'fromEditor'],
default: 'fromEditor'
},
[NotebookSetting.outputLineHeight]: {
markdownDescription: nls.localize('notebook.outputLineHeight', "Line height of the output text within notebook cells.\n - When set to 0, editor line height is used.\n - Values between 0 and 8 will be used as a multiplier with the font size.\n - Values greater than or equal to 8 will be used as effective values."),
type: 'number',
default: 0,
tags: ['notebookLayout', 'notebookOutputLayout']
},
[NotebookSetting.outputFontSize]: {
markdownDescription: nls.localize('notebook.outputFontSize', "Font size for the output text within notebook cells. When set to 0, {0} is used.", '`#editor.fontSize#`'),
type: 'number',
default: 0,
tags: ['notebookLayout', 'notebookOutputLayout']
},
[NotebookSetting.outputFontFamily]: {
markdownDescription: nls.localize('notebook.outputFontFamily', "The font family of the output text within notebook cells. When set to empty, the {0} is used.", '`#editor.fontFamily#`'),
type: 'string',
tags: ['notebookLayout', 'notebookOutputLayout']
},
[NotebookSetting.outputScrolling]: {
markdownDescription: nls.localize('notebook.outputScrolling', "Initially render notebook outputs in a scrollable region when longer than the limit"),
type: 'boolean',
tags: ['notebookLayout', 'notebookOutputLayout'],
default: typeof product.quality === 'string' && product.quality !== 'stable' // only enable as default in insiders
},
[NotebookSetting.outputWordWrap]: {
markdownDescription: nls.localize('notebook.outputWordWrap', "Controls whether the lines in output should wrap."),
type: 'boolean',
tags: ['notebookLayout', 'notebookOutputLayout'],
default: false
},
[NotebookSetting.formatOnSave]: {
markdownDescription: nls.localize('notebook.formatOnSave', "Format a notebook on save. A formatter must be available, the file must not be saved after delay, and the editor must not be shutting down."),
type: 'boolean',
tags: ['notebookLayout'],
default: false
},
[NotebookSetting.codeActionsOnSave]: {
markdownDescription: nls.localize('notebook.codeActionsOnSave', "Experimental. Run a series of CodeActions for a notebook on save. CodeActions must be specified, the file must not be saved after delay, and the editor must not be shutting down. Example: `source.fixAll: true`"),
type: 'object',
additionalProperties: {
type: 'boolean'
},
default: {}
},
[NotebookSetting.formatOnCellExecution]: {
markdownDescription: nls.localize('notebook.formatOnCellExecution', "Format a notebook cell upon execution. A formatter must be available."),
type: 'boolean',
default: false
},
[NotebookSetting.confirmDeleteRunningCell]: {
markdownDescription: nls.localize('notebook.confirmDeleteRunningCell', "Control whether a confirmation prompt is required to delete a running cell."),
type: 'boolean',
default: true
},
[NotebookSetting.findScope]: {
markdownDescription: nls.localize('notebook.findScope', "Customize the Find Widget behavior for searching within notebook cells. When both markup source and markup preview are enabled, the Find Widget will search either the source code or preview based on the current state of the cell."),
type: 'object',
properties: {
markupSource: {
type: 'boolean',
default: true
},
markupPreview: {
type: 'boolean',
default: true
},
codeSource: {
type: 'boolean',
default: true
},
codeOutput: {
type: 'boolean',
default: true
}
},
default: {
markupSource: true,
markupPreview: true,
codeSource: true,
codeOutput: true
},
tags: ['notebookLayout']
},
[NotebookSetting.remoteSaving]: {
markdownDescription: nls.localize('notebook.remoteSaving', "Enables the incremental saving of notebooks in Remote environment. When enabled, only the changes to the notebook are sent to the extension host, improving performance for large notebooks and slow network connections."),
type: 'boolean',
default: typeof product.quality === 'string' && product.quality !== 'stable' // only enable as default in insiders
}
}
});
| src/vs/workbench/contrib/notebook/browser/notebook.contribution.ts | 1 | https://github.com/microsoft/vscode/commit/94956b4c3fb38badce912cae3d5a531502669885 | [
0.9985118508338928,
0.09763599187135696,
0.00016303491429425776,
0.0001742112945066765,
0.2933221757411957
] |
{
"id": 1,
"code_window": [
"\t\tif (!data) {\n",
"\t\t\treturn null;\n",
"\t\t}\n",
"\n",
"\t\tconst ref = await this._notebookModelResolverService.resolve(data.notebook);\n",
"\t\tconst cell = ref.object.notebook.cells.find(cell => !!cell.outputs.find(op => op.outputId === data.outputId));\n",
"\n",
"\t\tif (!cell) {\n",
"\t\t\tref.dispose();\n",
"\t\t\treturn null;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst cell = ref.object.notebook.cells.find(cell => !!cell.outputs.find(op => op.outputId === data.outputId || op.alternativeOutputId === data.outputId));\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/notebook.contribution.ts",
"type": "replace",
"edit_start_line_idx": 493
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Names from https://blog.codinghorror.com/ascii-pronunciation-rules-for-programmers/
/**
* An inlined enum containing useful character codes (to be used with String.charCodeAt).
* Please leave the const keyword such that it gets inlined when compiled to JavaScript!
*/
export const enum CharCode {
Null = 0,
/**
* The `\b` character.
*/
Backspace = 8,
/**
* The `\t` character.
*/
Tab = 9,
/**
* The `\n` character.
*/
LineFeed = 10,
/**
* The `\r` character.
*/
CarriageReturn = 13,
Space = 32,
/**
* The `!` character.
*/
ExclamationMark = 33,
/**
* The `"` character.
*/
DoubleQuote = 34,
/**
* The `#` character.
*/
Hash = 35,
/**
* The `$` character.
*/
DollarSign = 36,
/**
* The `%` character.
*/
PercentSign = 37,
/**
* The `&` character.
*/
Ampersand = 38,
/**
* The `'` character.
*/
SingleQuote = 39,
/**
* The `(` character.
*/
OpenParen = 40,
/**
* The `)` character.
*/
CloseParen = 41,
/**
* The `*` character.
*/
Asterisk = 42,
/**
* The `+` character.
*/
Plus = 43,
/**
* The `,` character.
*/
Comma = 44,
/**
* The `-` character.
*/
Dash = 45,
/**
* The `.` character.
*/
Period = 46,
/**
* The `/` character.
*/
Slash = 47,
Digit0 = 48,
Digit1 = 49,
Digit2 = 50,
Digit3 = 51,
Digit4 = 52,
Digit5 = 53,
Digit6 = 54,
Digit7 = 55,
Digit8 = 56,
Digit9 = 57,
/**
* The `:` character.
*/
Colon = 58,
/**
* The `;` character.
*/
Semicolon = 59,
/**
* The `<` character.
*/
LessThan = 60,
/**
* The `=` character.
*/
Equals = 61,
/**
* The `>` character.
*/
GreaterThan = 62,
/**
* The `?` character.
*/
QuestionMark = 63,
/**
* The `@` character.
*/
AtSign = 64,
A = 65,
B = 66,
C = 67,
D = 68,
E = 69,
F = 70,
G = 71,
H = 72,
I = 73,
J = 74,
K = 75,
L = 76,
M = 77,
N = 78,
O = 79,
P = 80,
Q = 81,
R = 82,
S = 83,
T = 84,
U = 85,
V = 86,
W = 87,
X = 88,
Y = 89,
Z = 90,
/**
* The `[` character.
*/
OpenSquareBracket = 91,
/**
* The `\` character.
*/
Backslash = 92,
/**
* The `]` character.
*/
CloseSquareBracket = 93,
/**
* The `^` character.
*/
Caret = 94,
/**
* The `_` character.
*/
Underline = 95,
/**
* The ``(`)`` character.
*/
BackTick = 96,
a = 97,
b = 98,
c = 99,
d = 100,
e = 101,
f = 102,
g = 103,
h = 104,
i = 105,
j = 106,
k = 107,
l = 108,
m = 109,
n = 110,
o = 111,
p = 112,
q = 113,
r = 114,
s = 115,
t = 116,
u = 117,
v = 118,
w = 119,
x = 120,
y = 121,
z = 122,
/**
* The `{` character.
*/
OpenCurlyBrace = 123,
/**
* The `|` character.
*/
Pipe = 124,
/**
* The `}` character.
*/
CloseCurlyBrace = 125,
/**
* The `~` character.
*/
Tilde = 126,
/**
* The (no-break space) character.
* Unicode Character 'NO-BREAK SPACE' (U+00A0)
*/
NoBreakSpace = 160,
U_Combining_Grave_Accent = 0x0300, // U+0300 Combining Grave Accent
U_Combining_Acute_Accent = 0x0301, // U+0301 Combining Acute Accent
U_Combining_Circumflex_Accent = 0x0302, // U+0302 Combining Circumflex Accent
U_Combining_Tilde = 0x0303, // U+0303 Combining Tilde
U_Combining_Macron = 0x0304, // U+0304 Combining Macron
U_Combining_Overline = 0x0305, // U+0305 Combining Overline
U_Combining_Breve = 0x0306, // U+0306 Combining Breve
U_Combining_Dot_Above = 0x0307, // U+0307 Combining Dot Above
U_Combining_Diaeresis = 0x0308, // U+0308 Combining Diaeresis
U_Combining_Hook_Above = 0x0309, // U+0309 Combining Hook Above
U_Combining_Ring_Above = 0x030A, // U+030A Combining Ring Above
U_Combining_Double_Acute_Accent = 0x030B, // U+030B Combining Double Acute Accent
U_Combining_Caron = 0x030C, // U+030C Combining Caron
U_Combining_Vertical_Line_Above = 0x030D, // U+030D Combining Vertical Line Above
U_Combining_Double_Vertical_Line_Above = 0x030E, // U+030E Combining Double Vertical Line Above
U_Combining_Double_Grave_Accent = 0x030F, // U+030F Combining Double Grave Accent
U_Combining_Candrabindu = 0x0310, // U+0310 Combining Candrabindu
U_Combining_Inverted_Breve = 0x0311, // U+0311 Combining Inverted Breve
U_Combining_Turned_Comma_Above = 0x0312, // U+0312 Combining Turned Comma Above
U_Combining_Comma_Above = 0x0313, // U+0313 Combining Comma Above
U_Combining_Reversed_Comma_Above = 0x0314, // U+0314 Combining Reversed Comma Above
U_Combining_Comma_Above_Right = 0x0315, // U+0315 Combining Comma Above Right
U_Combining_Grave_Accent_Below = 0x0316, // U+0316 Combining Grave Accent Below
U_Combining_Acute_Accent_Below = 0x0317, // U+0317 Combining Acute Accent Below
U_Combining_Left_Tack_Below = 0x0318, // U+0318 Combining Left Tack Below
U_Combining_Right_Tack_Below = 0x0319, // U+0319 Combining Right Tack Below
U_Combining_Left_Angle_Above = 0x031A, // U+031A Combining Left Angle Above
U_Combining_Horn = 0x031B, // U+031B Combining Horn
U_Combining_Left_Half_Ring_Below = 0x031C, // U+031C Combining Left Half Ring Below
U_Combining_Up_Tack_Below = 0x031D, // U+031D Combining Up Tack Below
U_Combining_Down_Tack_Below = 0x031E, // U+031E Combining Down Tack Below
U_Combining_Plus_Sign_Below = 0x031F, // U+031F Combining Plus Sign Below
U_Combining_Minus_Sign_Below = 0x0320, // U+0320 Combining Minus Sign Below
U_Combining_Palatalized_Hook_Below = 0x0321, // U+0321 Combining Palatalized Hook Below
U_Combining_Retroflex_Hook_Below = 0x0322, // U+0322 Combining Retroflex Hook Below
U_Combining_Dot_Below = 0x0323, // U+0323 Combining Dot Below
U_Combining_Diaeresis_Below = 0x0324, // U+0324 Combining Diaeresis Below
U_Combining_Ring_Below = 0x0325, // U+0325 Combining Ring Below
U_Combining_Comma_Below = 0x0326, // U+0326 Combining Comma Below
U_Combining_Cedilla = 0x0327, // U+0327 Combining Cedilla
U_Combining_Ogonek = 0x0328, // U+0328 Combining Ogonek
U_Combining_Vertical_Line_Below = 0x0329, // U+0329 Combining Vertical Line Below
U_Combining_Bridge_Below = 0x032A, // U+032A Combining Bridge Below
U_Combining_Inverted_Double_Arch_Below = 0x032B, // U+032B Combining Inverted Double Arch Below
U_Combining_Caron_Below = 0x032C, // U+032C Combining Caron Below
U_Combining_Circumflex_Accent_Below = 0x032D, // U+032D Combining Circumflex Accent Below
U_Combining_Breve_Below = 0x032E, // U+032E Combining Breve Below
U_Combining_Inverted_Breve_Below = 0x032F, // U+032F Combining Inverted Breve Below
U_Combining_Tilde_Below = 0x0330, // U+0330 Combining Tilde Below
U_Combining_Macron_Below = 0x0331, // U+0331 Combining Macron Below
U_Combining_Low_Line = 0x0332, // U+0332 Combining Low Line
U_Combining_Double_Low_Line = 0x0333, // U+0333 Combining Double Low Line
U_Combining_Tilde_Overlay = 0x0334, // U+0334 Combining Tilde Overlay
U_Combining_Short_Stroke_Overlay = 0x0335, // U+0335 Combining Short Stroke Overlay
U_Combining_Long_Stroke_Overlay = 0x0336, // U+0336 Combining Long Stroke Overlay
U_Combining_Short_Solidus_Overlay = 0x0337, // U+0337 Combining Short Solidus Overlay
U_Combining_Long_Solidus_Overlay = 0x0338, // U+0338 Combining Long Solidus Overlay
U_Combining_Right_Half_Ring_Below = 0x0339, // U+0339 Combining Right Half Ring Below
U_Combining_Inverted_Bridge_Below = 0x033A, // U+033A Combining Inverted Bridge Below
U_Combining_Square_Below = 0x033B, // U+033B Combining Square Below
U_Combining_Seagull_Below = 0x033C, // U+033C Combining Seagull Below
U_Combining_X_Above = 0x033D, // U+033D Combining X Above
U_Combining_Vertical_Tilde = 0x033E, // U+033E Combining Vertical Tilde
U_Combining_Double_Overline = 0x033F, // U+033F Combining Double Overline
U_Combining_Grave_Tone_Mark = 0x0340, // U+0340 Combining Grave Tone Mark
U_Combining_Acute_Tone_Mark = 0x0341, // U+0341 Combining Acute Tone Mark
U_Combining_Greek_Perispomeni = 0x0342, // U+0342 Combining Greek Perispomeni
U_Combining_Greek_Koronis = 0x0343, // U+0343 Combining Greek Koronis
U_Combining_Greek_Dialytika_Tonos = 0x0344, // U+0344 Combining Greek Dialytika Tonos
U_Combining_Greek_Ypogegrammeni = 0x0345, // U+0345 Combining Greek Ypogegrammeni
U_Combining_Bridge_Above = 0x0346, // U+0346 Combining Bridge Above
U_Combining_Equals_Sign_Below = 0x0347, // U+0347 Combining Equals Sign Below
U_Combining_Double_Vertical_Line_Below = 0x0348, // U+0348 Combining Double Vertical Line Below
U_Combining_Left_Angle_Below = 0x0349, // U+0349 Combining Left Angle Below
U_Combining_Not_Tilde_Above = 0x034A, // U+034A Combining Not Tilde Above
U_Combining_Homothetic_Above = 0x034B, // U+034B Combining Homothetic Above
U_Combining_Almost_Equal_To_Above = 0x034C, // U+034C Combining Almost Equal To Above
U_Combining_Left_Right_Arrow_Below = 0x034D, // U+034D Combining Left Right Arrow Below
U_Combining_Upwards_Arrow_Below = 0x034E, // U+034E Combining Upwards Arrow Below
U_Combining_Grapheme_Joiner = 0x034F, // U+034F Combining Grapheme Joiner
U_Combining_Right_Arrowhead_Above = 0x0350, // U+0350 Combining Right Arrowhead Above
U_Combining_Left_Half_Ring_Above = 0x0351, // U+0351 Combining Left Half Ring Above
U_Combining_Fermata = 0x0352, // U+0352 Combining Fermata
U_Combining_X_Below = 0x0353, // U+0353 Combining X Below
U_Combining_Left_Arrowhead_Below = 0x0354, // U+0354 Combining Left Arrowhead Below
U_Combining_Right_Arrowhead_Below = 0x0355, // U+0355 Combining Right Arrowhead Below
U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below = 0x0356, // U+0356 Combining Right Arrowhead And Up Arrowhead Below
U_Combining_Right_Half_Ring_Above = 0x0357, // U+0357 Combining Right Half Ring Above
U_Combining_Dot_Above_Right = 0x0358, // U+0358 Combining Dot Above Right
U_Combining_Asterisk_Below = 0x0359, // U+0359 Combining Asterisk Below
U_Combining_Double_Ring_Below = 0x035A, // U+035A Combining Double Ring Below
U_Combining_Zigzag_Above = 0x035B, // U+035B Combining Zigzag Above
U_Combining_Double_Breve_Below = 0x035C, // U+035C Combining Double Breve Below
U_Combining_Double_Breve = 0x035D, // U+035D Combining Double Breve
U_Combining_Double_Macron = 0x035E, // U+035E Combining Double Macron
U_Combining_Double_Macron_Below = 0x035F, // U+035F Combining Double Macron Below
U_Combining_Double_Tilde = 0x0360, // U+0360 Combining Double Tilde
U_Combining_Double_Inverted_Breve = 0x0361, // U+0361 Combining Double Inverted Breve
U_Combining_Double_Rightwards_Arrow_Below = 0x0362, // U+0362 Combining Double Rightwards Arrow Below
U_Combining_Latin_Small_Letter_A = 0x0363, // U+0363 Combining Latin Small Letter A
U_Combining_Latin_Small_Letter_E = 0x0364, // U+0364 Combining Latin Small Letter E
U_Combining_Latin_Small_Letter_I = 0x0365, // U+0365 Combining Latin Small Letter I
U_Combining_Latin_Small_Letter_O = 0x0366, // U+0366 Combining Latin Small Letter O
U_Combining_Latin_Small_Letter_U = 0x0367, // U+0367 Combining Latin Small Letter U
U_Combining_Latin_Small_Letter_C = 0x0368, // U+0368 Combining Latin Small Letter C
U_Combining_Latin_Small_Letter_D = 0x0369, // U+0369 Combining Latin Small Letter D
U_Combining_Latin_Small_Letter_H = 0x036A, // U+036A Combining Latin Small Letter H
U_Combining_Latin_Small_Letter_M = 0x036B, // U+036B Combining Latin Small Letter M
U_Combining_Latin_Small_Letter_R = 0x036C, // U+036C Combining Latin Small Letter R
U_Combining_Latin_Small_Letter_T = 0x036D, // U+036D Combining Latin Small Letter T
U_Combining_Latin_Small_Letter_V = 0x036E, // U+036E Combining Latin Small Letter V
U_Combining_Latin_Small_Letter_X = 0x036F, // U+036F Combining Latin Small Letter X
/**
* Unicode Character 'LINE SEPARATOR' (U+2028)
* http://www.fileformat.info/info/unicode/char/2028/index.htm
*/
LINE_SEPARATOR = 0x2028,
/**
* Unicode Character 'PARAGRAPH SEPARATOR' (U+2029)
* http://www.fileformat.info/info/unicode/char/2029/index.htm
*/
PARAGRAPH_SEPARATOR = 0x2029,
/**
* Unicode Character 'NEXT LINE' (U+0085)
* http://www.fileformat.info/info/unicode/char/0085/index.htm
*/
NEXT_LINE = 0x0085,
// http://www.fileformat.info/info/unicode/category/Sk/list.htm
U_CIRCUMFLEX = 0x005E, // U+005E CIRCUMFLEX
U_GRAVE_ACCENT = 0x0060, // U+0060 GRAVE ACCENT
U_DIAERESIS = 0x00A8, // U+00A8 DIAERESIS
U_MACRON = 0x00AF, // U+00AF MACRON
U_ACUTE_ACCENT = 0x00B4, // U+00B4 ACUTE ACCENT
U_CEDILLA = 0x00B8, // U+00B8 CEDILLA
U_MODIFIER_LETTER_LEFT_ARROWHEAD = 0x02C2, // U+02C2 MODIFIER LETTER LEFT ARROWHEAD
U_MODIFIER_LETTER_RIGHT_ARROWHEAD = 0x02C3, // U+02C3 MODIFIER LETTER RIGHT ARROWHEAD
U_MODIFIER_LETTER_UP_ARROWHEAD = 0x02C4, // U+02C4 MODIFIER LETTER UP ARROWHEAD
U_MODIFIER_LETTER_DOWN_ARROWHEAD = 0x02C5, // U+02C5 MODIFIER LETTER DOWN ARROWHEAD
U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING = 0x02D2, // U+02D2 MODIFIER LETTER CENTRED RIGHT HALF RING
U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING = 0x02D3, // U+02D3 MODIFIER LETTER CENTRED LEFT HALF RING
U_MODIFIER_LETTER_UP_TACK = 0x02D4, // U+02D4 MODIFIER LETTER UP TACK
U_MODIFIER_LETTER_DOWN_TACK = 0x02D5, // U+02D5 MODIFIER LETTER DOWN TACK
U_MODIFIER_LETTER_PLUS_SIGN = 0x02D6, // U+02D6 MODIFIER LETTER PLUS SIGN
U_MODIFIER_LETTER_MINUS_SIGN = 0x02D7, // U+02D7 MODIFIER LETTER MINUS SIGN
U_BREVE = 0x02D8, // U+02D8 BREVE
U_DOT_ABOVE = 0x02D9, // U+02D9 DOT ABOVE
U_RING_ABOVE = 0x02DA, // U+02DA RING ABOVE
U_OGONEK = 0x02DB, // U+02DB OGONEK
U_SMALL_TILDE = 0x02DC, // U+02DC SMALL TILDE
U_DOUBLE_ACUTE_ACCENT = 0x02DD, // U+02DD DOUBLE ACUTE ACCENT
U_MODIFIER_LETTER_RHOTIC_HOOK = 0x02DE, // U+02DE MODIFIER LETTER RHOTIC HOOK
U_MODIFIER_LETTER_CROSS_ACCENT = 0x02DF, // U+02DF MODIFIER LETTER CROSS ACCENT
U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR = 0x02E5, // U+02E5 MODIFIER LETTER EXTRA-HIGH TONE BAR
U_MODIFIER_LETTER_HIGH_TONE_BAR = 0x02E6, // U+02E6 MODIFIER LETTER HIGH TONE BAR
U_MODIFIER_LETTER_MID_TONE_BAR = 0x02E7, // U+02E7 MODIFIER LETTER MID TONE BAR
U_MODIFIER_LETTER_LOW_TONE_BAR = 0x02E8, // U+02E8 MODIFIER LETTER LOW TONE BAR
U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR = 0x02E9, // U+02E9 MODIFIER LETTER EXTRA-LOW TONE BAR
U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK = 0x02EA, // U+02EA MODIFIER LETTER YIN DEPARTING TONE MARK
U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK = 0x02EB, // U+02EB MODIFIER LETTER YANG DEPARTING TONE MARK
U_MODIFIER_LETTER_UNASPIRATED = 0x02ED, // U+02ED MODIFIER LETTER UNASPIRATED
U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD = 0x02EF, // U+02EF MODIFIER LETTER LOW DOWN ARROWHEAD
U_MODIFIER_LETTER_LOW_UP_ARROWHEAD = 0x02F0, // U+02F0 MODIFIER LETTER LOW UP ARROWHEAD
U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD = 0x02F1, // U+02F1 MODIFIER LETTER LOW LEFT ARROWHEAD
U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD = 0x02F2, // U+02F2 MODIFIER LETTER LOW RIGHT ARROWHEAD
U_MODIFIER_LETTER_LOW_RING = 0x02F3, // U+02F3 MODIFIER LETTER LOW RING
U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT = 0x02F4, // U+02F4 MODIFIER LETTER MIDDLE GRAVE ACCENT
U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT = 0x02F5, // U+02F5 MODIFIER LETTER MIDDLE DOUBLE GRAVE ACCENT
U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT = 0x02F6, // U+02F6 MODIFIER LETTER MIDDLE DOUBLE ACUTE ACCENT
U_MODIFIER_LETTER_LOW_TILDE = 0x02F7, // U+02F7 MODIFIER LETTER LOW TILDE
U_MODIFIER_LETTER_RAISED_COLON = 0x02F8, // U+02F8 MODIFIER LETTER RAISED COLON
U_MODIFIER_LETTER_BEGIN_HIGH_TONE = 0x02F9, // U+02F9 MODIFIER LETTER BEGIN HIGH TONE
U_MODIFIER_LETTER_END_HIGH_TONE = 0x02FA, // U+02FA MODIFIER LETTER END HIGH TONE
U_MODIFIER_LETTER_BEGIN_LOW_TONE = 0x02FB, // U+02FB MODIFIER LETTER BEGIN LOW TONE
U_MODIFIER_LETTER_END_LOW_TONE = 0x02FC, // U+02FC MODIFIER LETTER END LOW TONE
U_MODIFIER_LETTER_SHELF = 0x02FD, // U+02FD MODIFIER LETTER SHELF
U_MODIFIER_LETTER_OPEN_SHELF = 0x02FE, // U+02FE MODIFIER LETTER OPEN SHELF
U_MODIFIER_LETTER_LOW_LEFT_ARROW = 0x02FF, // U+02FF MODIFIER LETTER LOW LEFT ARROW
U_GREEK_LOWER_NUMERAL_SIGN = 0x0375, // U+0375 GREEK LOWER NUMERAL SIGN
U_GREEK_TONOS = 0x0384, // U+0384 GREEK TONOS
U_GREEK_DIALYTIKA_TONOS = 0x0385, // U+0385 GREEK DIALYTIKA TONOS
U_GREEK_KORONIS = 0x1FBD, // U+1FBD GREEK KORONIS
U_GREEK_PSILI = 0x1FBF, // U+1FBF GREEK PSILI
U_GREEK_PERISPOMENI = 0x1FC0, // U+1FC0 GREEK PERISPOMENI
U_GREEK_DIALYTIKA_AND_PERISPOMENI = 0x1FC1, // U+1FC1 GREEK DIALYTIKA AND PERISPOMENI
U_GREEK_PSILI_AND_VARIA = 0x1FCD, // U+1FCD GREEK PSILI AND VARIA
U_GREEK_PSILI_AND_OXIA = 0x1FCE, // U+1FCE GREEK PSILI AND OXIA
U_GREEK_PSILI_AND_PERISPOMENI = 0x1FCF, // U+1FCF GREEK PSILI AND PERISPOMENI
U_GREEK_DASIA_AND_VARIA = 0x1FDD, // U+1FDD GREEK DASIA AND VARIA
U_GREEK_DASIA_AND_OXIA = 0x1FDE, // U+1FDE GREEK DASIA AND OXIA
U_GREEK_DASIA_AND_PERISPOMENI = 0x1FDF, // U+1FDF GREEK DASIA AND PERISPOMENI
U_GREEK_DIALYTIKA_AND_VARIA = 0x1FED, // U+1FED GREEK DIALYTIKA AND VARIA
U_GREEK_DIALYTIKA_AND_OXIA = 0x1FEE, // U+1FEE GREEK DIALYTIKA AND OXIA
U_GREEK_VARIA = 0x1FEF, // U+1FEF GREEK VARIA
U_GREEK_OXIA = 0x1FFD, // U+1FFD GREEK OXIA
U_GREEK_DASIA = 0x1FFE, // U+1FFE GREEK DASIA
U_IDEOGRAPHIC_FULL_STOP = 0x3002, // U+3002 IDEOGRAPHIC FULL STOP
U_LEFT_CORNER_BRACKET = 0x300C, // U+300C LEFT CORNER BRACKET
U_RIGHT_CORNER_BRACKET = 0x300D, // U+300D RIGHT CORNER BRACKET
U_LEFT_BLACK_LENTICULAR_BRACKET = 0x3010, // U+3010 LEFT BLACK LENTICULAR BRACKET
U_RIGHT_BLACK_LENTICULAR_BRACKET = 0x3011, // U+3011 RIGHT BLACK LENTICULAR BRACKET
U_OVERLINE = 0x203E, // Unicode Character 'OVERLINE'
/**
* UTF-8 BOM
* Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF)
* http://www.fileformat.info/info/unicode/char/feff/index.htm
*/
UTF8_BOM = 65279,
U_FULLWIDTH_SEMICOLON = 0xFF1B, // U+FF1B FULLWIDTH SEMICOLON
U_FULLWIDTH_COMMA = 0xFF0C, // U+FF0C FULLWIDTH COMMA
}
| src/vs/base/common/charCode.ts | 0 | https://github.com/microsoft/vscode/commit/94956b4c3fb38badce912cae3d5a531502669885 | [
0.0007194805075414479,
0.0002099163830280304,
0.00016487196262460202,
0.00017571930948179215,
0.00010257515532430261
] |
{
"id": 1,
"code_window": [
"\t\tif (!data) {\n",
"\t\t\treturn null;\n",
"\t\t}\n",
"\n",
"\t\tconst ref = await this._notebookModelResolverService.resolve(data.notebook);\n",
"\t\tconst cell = ref.object.notebook.cells.find(cell => !!cell.outputs.find(op => op.outputId === data.outputId));\n",
"\n",
"\t\tif (!cell) {\n",
"\t\t\tref.dispose();\n",
"\t\t\treturn null;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst cell = ref.object.notebook.cells.find(cell => !!cell.outputs.find(op => op.outputId === data.outputId || op.alternativeOutputId === data.outputId));\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/notebook.contribution.ts",
"type": "replace",
"edit_start_line_idx": 493
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { KeyboardLayoutContribution } from 'vs/workbench/services/keybinding/browser/keyboardLayouts/_.contribution';
KeyboardLayoutContribution.INSTANCE.registerKeyboardLayout({
layout: { name: '00000406', id: '', text: 'Danish' },
secondaryLayouts: [],
mapping: {
Sleep: [],
WakeUp: [],
KeyA: ['a', 'A', '', '', 0, 'VK_A'],
KeyB: ['b', 'B', '', '', 0, 'VK_B'],
KeyC: ['c', 'C', '', '', 0, 'VK_C'],
KeyD: ['d', 'D', '', '', 0, 'VK_D'],
KeyE: ['e', 'E', '€', '', 0, 'VK_E'],
KeyF: ['f', 'F', '', '', 0, 'VK_F'],
KeyG: ['g', 'G', '', '', 0, 'VK_G'],
KeyH: ['h', 'H', '', '', 0, 'VK_H'],
KeyI: ['i', 'I', '', '', 0, 'VK_I'],
KeyJ: ['j', 'J', '', '', 0, 'VK_J'],
KeyK: ['k', 'K', '', '', 0, 'VK_K'],
KeyL: ['l', 'L', '', '', 0, 'VK_L'],
KeyM: ['m', 'M', 'µ', '', 0, 'VK_M'],
KeyN: ['n', 'N', '', '', 0, 'VK_N'],
KeyO: ['o', 'O', '', '', 0, 'VK_O'],
KeyP: ['p', 'P', '', '', 0, 'VK_P'],
KeyQ: ['q', 'Q', '', '', 0, 'VK_Q'],
KeyR: ['r', 'R', '', '', 0, 'VK_R'],
KeyS: ['s', 'S', '', '', 0, 'VK_S'],
KeyT: ['t', 'T', '', '', 0, 'VK_T'],
KeyU: ['u', 'U', '', '', 0, 'VK_U'],
KeyV: ['v', 'V', '', '', 0, 'VK_V'],
KeyW: ['w', 'W', '', '', 0, 'VK_W'],
KeyX: ['x', 'X', '', '', 0, 'VK_X'],
KeyY: ['y', 'Y', '', '', 0, 'VK_Y'],
KeyZ: ['z', 'Z', '', '', 0, 'VK_Z'],
Digit1: ['1', '!', '', '', 0, 'VK_1'],
Digit2: ['2', '"', '@', '', 0, 'VK_2'],
Digit3: ['3', '#', '£', '', 0, 'VK_3'],
Digit4: ['4', '¤', '$', '', 0, 'VK_4'],
Digit5: ['5', '%', '€', '', 0, 'VK_5'],
Digit6: ['6', '&', '', '', 0, 'VK_6'],
Digit7: ['7', '/', '{', '', 0, 'VK_7'],
Digit8: ['8', '(', '[', '', 0, 'VK_8'],
Digit9: ['9', ')', ']', '', 0, 'VK_9'],
Digit0: ['0', '=', '}', '', 0, 'VK_0'],
Enter: [],
Escape: [],
Backspace: [],
Tab: [],
Space: [' ', ' ', '', '', 0, 'VK_SPACE'],
Minus: ['+', '?', '', '', 0, 'VK_OEM_PLUS'],
Equal: ['´', '`', '|', '', 0, 'VK_OEM_4'],
BracketLeft: ['å', 'Å', '', '', 0, 'VK_OEM_6'],
BracketRight: ['¨', '^', '~', '', 0, 'VK_OEM_1'],
Backslash: ['\'', '*', '', '', 0, 'VK_OEM_2'],
Semicolon: ['æ', 'Æ', '', '', 0, 'VK_OEM_3'],
Quote: ['ø', 'Ø', '', '', 0, 'VK_OEM_7'],
Backquote: ['½', '§', '', '', 0, 'VK_OEM_5'],
Comma: [',', ';', '', '', 0, 'VK_OEM_COMMA'],
Period: ['.', ':', '', '', 0, 'VK_OEM_PERIOD'],
Slash: ['-', '_', '', '', 0, 'VK_OEM_MINUS'],
CapsLock: [],
F1: [],
F2: [],
F3: [],
F4: [],
F5: [],
F6: [],
F7: [],
F8: [],
F9: [],
F10: [],
F11: [],
F12: [],
PrintScreen: [],
ScrollLock: [],
Pause: [],
Insert: [],
Home: [],
PageUp: [],
Delete: [],
End: [],
PageDown: [],
ArrowRight: [],
ArrowLeft: [],
ArrowDown: [],
ArrowUp: [],
NumLock: [],
NumpadDivide: ['/', '/', '', '', 0, 'VK_DIVIDE'],
NumpadMultiply: ['*', '*', '', '', 0, 'VK_MULTIPLY'],
NumpadSubtract: ['-', '-', '', '', 0, 'VK_SUBTRACT'],
NumpadAdd: ['+', '+', '', '', 0, 'VK_ADD'],
NumpadEnter: [],
Numpad1: [],
Numpad2: [],
Numpad3: [],
Numpad4: [],
Numpad5: [],
Numpad6: [],
Numpad7: [],
Numpad8: [],
Numpad9: [],
Numpad0: [],
NumpadDecimal: [],
IntlBackslash: ['<', '>', '\\', '', 0, 'VK_OEM_102'],
ContextMenu: [],
Power: [],
NumpadEqual: [],
F13: [],
F14: [],
F15: [],
F16: [],
F17: [],
F18: [],
F19: [],
F20: [],
F21: [],
F22: [],
F23: [],
F24: [],
Help: [],
Undo: [],
Cut: [],
Copy: [],
Paste: [],
AudioVolumeMute: [],
AudioVolumeUp: [],
AudioVolumeDown: [],
NumpadComma: [],
IntlRo: [],
KanaMode: [],
IntlYen: [],
Convert: [],
NonConvert: [],
Lang1: [],
Lang2: [],
Lang3: [],
Lang4: [],
ControlLeft: [],
ShiftLeft: [],
AltLeft: [],
MetaLeft: [],
ControlRight: [],
ShiftRight: [],
AltRight: [],
MetaRight: [],
MediaTrackNext: [],
MediaTrackPrevious: [],
MediaStop: [],
Eject: [],
MediaPlayPause: [],
MediaSelect: [],
LaunchMail: [],
LaunchApp2: [],
LaunchApp1: [],
BrowserSearch: [],
BrowserHome: [],
BrowserBack: [],
BrowserForward: [],
BrowserStop: [],
BrowserRefresh: [],
BrowserFavorites: []
}
}); | src/vs/workbench/services/keybinding/browser/keyboardLayouts/dk.win.ts | 0 | https://github.com/microsoft/vscode/commit/94956b4c3fb38badce912cae3d5a531502669885 | [
0.00017906706489156932,
0.00017510705220047385,
0.00016944886010605842,
0.000175520297489129,
0.0000027521432457433548
] |
{
"id": 1,
"code_window": [
"\t\tif (!data) {\n",
"\t\t\treturn null;\n",
"\t\t}\n",
"\n",
"\t\tconst ref = await this._notebookModelResolverService.resolve(data.notebook);\n",
"\t\tconst cell = ref.object.notebook.cells.find(cell => !!cell.outputs.find(op => op.outputId === data.outputId));\n",
"\n",
"\t\tif (!cell) {\n",
"\t\t\tref.dispose();\n",
"\t\t\treturn null;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst cell = ref.object.notebook.cells.find(cell => !!cell.outputs.find(op => op.outputId === data.outputId || op.alternativeOutputId === data.outputId));\n"
],
"file_path": "src/vs/workbench/contrib/notebook/browser/notebook.contribution.ts",
"type": "replace",
"edit_start_line_idx": 493
} | {
"information_for_contributors": [
"This file has been converted from https://github.com/textmate/diff.tmbundle/blob/master/Syntaxes/Diff.plist",
"If you want to provide a fix or improvement, please create a pull request against the original repository.",
"Once accepted there, we are happy to receive an update request."
],
"version": "https://github.com/textmate/diff.tmbundle/commit/0593bb775eab1824af97ef2172fd38822abd97d7",
"name": "Diff",
"scopeName": "source.diff",
"patterns": [
{
"captures": {
"1": {
"name": "punctuation.definition.separator.diff"
}
},
"match": "^((\\*{15})|(={67})|(-{3}))$\\n?",
"name": "meta.separator.diff"
},
{
"match": "^\\d+(,\\d+)*(a|d|c)\\d+(,\\d+)*$\\n?",
"name": "meta.diff.range.normal"
},
{
"captures": {
"1": {
"name": "punctuation.definition.range.diff"
},
"2": {
"name": "meta.toc-list.line-number.diff"
},
"3": {
"name": "punctuation.definition.range.diff"
}
},
"match": "^(@@)\\s*(.+?)\\s*(@@)($\\n?)?",
"name": "meta.diff.range.unified"
},
{
"captures": {
"3": {
"name": "punctuation.definition.range.diff"
},
"4": {
"name": "punctuation.definition.range.diff"
},
"6": {
"name": "punctuation.definition.range.diff"
},
"7": {
"name": "punctuation.definition.range.diff"
}
},
"match": "^(((\\-{3}) .+ (\\-{4}))|((\\*{3}) .+ (\\*{4})))$\\n?",
"name": "meta.diff.range.context"
},
{
"match": "^diff --git a/.*$\\n?",
"name": "meta.diff.header.git"
},
{
"match": "^diff (-|\\S+\\s+\\S+).*$\\n?",
"name": "meta.diff.header.command"
},
{
"captures": {
"4": {
"name": "punctuation.definition.from-file.diff"
},
"6": {
"name": "punctuation.definition.from-file.diff"
},
"7": {
"name": "punctuation.definition.from-file.diff"
}
},
"match": "(^(((-{3}) .+)|((\\*{3}) .+))$\\n?|^(={4}) .+(?= - ))",
"name": "meta.diff.header.from-file"
},
{
"captures": {
"2": {
"name": "punctuation.definition.to-file.diff"
},
"3": {
"name": "punctuation.definition.to-file.diff"
},
"4": {
"name": "punctuation.definition.to-file.diff"
}
},
"match": "(^(\\+{3}) .+$\\n?| (-) .* (={4})$\\n?)",
"name": "meta.diff.header.to-file"
},
{
"captures": {
"3": {
"name": "punctuation.definition.inserted.diff"
},
"6": {
"name": "punctuation.definition.inserted.diff"
}
},
"match": "^(((>)( .*)?)|((\\+).*))$\\n?",
"name": "markup.inserted.diff"
},
{
"captures": {
"1": {
"name": "punctuation.definition.changed.diff"
}
},
"match": "^(!).*$\\n?",
"name": "markup.changed.diff"
},
{
"captures": {
"3": {
"name": "punctuation.definition.deleted.diff"
},
"6": {
"name": "punctuation.definition.deleted.diff"
}
},
"match": "^(((<)( .*)?)|((-).*))$\\n?",
"name": "markup.deleted.diff"
},
{
"begin": "^(#)",
"captures": {
"1": {
"name": "punctuation.definition.comment.diff"
}
},
"comment": "Git produces unified diffs with embedded comments\"",
"end": "\\n",
"name": "comment.line.number-sign.diff"
},
{
"match": "^index [0-9a-f]{7,40}\\.\\.[0-9a-f]{7,40}.*$\\n?",
"name": "meta.diff.index.git"
},
{
"captures": {
"1": {
"name": "punctuation.separator.key-value.diff"
},
"2": {
"name": "meta.toc-list.file-name.diff"
}
},
"match": "^Index(:) (.+)$\\n?",
"name": "meta.diff.index"
},
{
"match": "^Only in .*: .*$\\n?",
"name": "meta.diff.only-in"
}
]
} | extensions/diff/syntaxes/diff.tmLanguage.json | 0 | https://github.com/microsoft/vscode/commit/94956b4c3fb38badce912cae3d5a531502669885 | [
0.0001788552908692509,
0.00017706792277749628,
0.00017518809181638062,
0.0001769761584000662,
9.298394161305623e-7
] |
{
"id": 2,
"code_window": [
"\t\treturn this._rawOutput.outputId;\n",
"\t}\n",
"\n",
"\tprivate _versionId = 0;\n",
"\n",
"\tget versionId() {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t/**\n",
"\t * Alternative output id that's reused when the output is updated.\n",
"\t */\n",
"\tprivate _alternativeOutputId: string;\n",
"\n",
"\tget alternativeOutputId(): string {\n",
"\t\treturn this._alternativeOutputId;\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/common/model/notebookCellOutputTextModel.ts",
"type": "add",
"edit_start_line_idx": 27
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Schemas } from 'vs/base/common/network';
import { IDisposable, Disposable, DisposableStore, dispose } from 'vs/base/common/lifecycle';
import { parse } from 'vs/base/common/marshalling';
import { extname, isEqual } from 'vs/base/common/resources';
import { assertType } from 'vs/base/common/types';
import { URI } from 'vs/base/common/uri';
import { toFormattedString } from 'vs/base/common/jsonFormatter';
import { ITextModel, ITextBufferFactory, DefaultEndOfLine, ITextBuffer } from 'vs/editor/common/model';
import { IModelService } from 'vs/editor/common/services/model';
import { ILanguageSelection, ILanguageService } from 'vs/editor/common/languages/language';
import { ITextModelContentProvider, ITextModelService } from 'vs/editor/common/services/resolverService';
import * as nls from 'vs/nls';
import { Extensions, IConfigurationPropertySchema, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { Registry } from 'vs/platform/registry/common/platform';
import { EditorPaneDescriptor, IEditorPaneRegistry } from 'vs/workbench/browser/editor';
import { Extensions as WorkbenchExtensions, IWorkbenchContribution, IWorkbenchContributionsRegistry } from 'vs/workbench/common/contributions';
import { IEditorSerializer, IEditorFactoryRegistry, EditorExtensions } from 'vs/workbench/common/editor';
import { EditorInput } from 'vs/workbench/common/editor/editorInput';
import { NotebookEditor } from 'vs/workbench/contrib/notebook/browser/notebookEditor';
import { NotebookEditorInput, NotebookEditorInputOptions } from 'vs/workbench/contrib/notebook/common/notebookEditorInput';
import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';
import { NotebookService } from 'vs/workbench/contrib/notebook/browser/services/notebookServiceImpl';
import { CellKind, CellUri, IResolvedNotebookEditorModel, NotebookWorkingCopyTypeIdentifier, NotebookSetting, ICellOutput, ICell } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IUndoRedoService } from 'vs/platform/undoRedo/common/undoRedo';
import { INotebookEditorModelResolverService } from 'vs/workbench/contrib/notebook/common/notebookEditorModelResolverService';
import { NotebookDiffEditorInput } from 'vs/workbench/contrib/notebook/common/notebookDiffEditorInput';
import { NotebookTextDiffEditor } from 'vs/workbench/contrib/notebook/browser/diff/notebookDiffEditor';
import { INotebookEditorWorkerService } from 'vs/workbench/contrib/notebook/common/services/notebookWorkerService';
import { NotebookEditorWorkerServiceImpl } from 'vs/workbench/contrib/notebook/browser/services/notebookWorkerServiceImpl';
import { INotebookCellStatusBarService } from 'vs/workbench/contrib/notebook/common/notebookCellStatusBarService';
import { NotebookCellStatusBarService } from 'vs/workbench/contrib/notebook/browser/services/notebookCellStatusBarServiceImpl';
import { INotebookEditorService } from 'vs/workbench/contrib/notebook/browser/services/notebookEditorService';
import { NotebookEditorWidgetService } from 'vs/workbench/contrib/notebook/browser/services/notebookEditorServiceImpl';
import { IJSONContributionRegistry, Extensions as JSONExtensions } from 'vs/platform/jsonschemas/common/jsonContributionRegistry';
import { IJSONSchema, IJSONSchemaMap } from 'vs/base/common/jsonSchema';
import { Event } from 'vs/base/common/event';
import { getFormattedMetadataJSON, getStreamOutputData } from 'vs/workbench/contrib/notebook/browser/diff/diffElementViewModel';
import { NotebookModelResolverServiceImpl } from 'vs/workbench/contrib/notebook/common/notebookEditorModelResolverServiceImpl';
import { INotebookKernelHistoryService, INotebookKernelService } from 'vs/workbench/contrib/notebook/common/notebookKernelService';
import { NotebookKernelService } from 'vs/workbench/contrib/notebook/browser/services/notebookKernelServiceImpl';
import { IWorkingCopyIdentifier } from 'vs/workbench/services/workingCopy/common/workingCopy';
import { IResourceEditorInput } from 'vs/platform/editor/common/editor';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IWorkingCopyEditorHandler, IWorkingCopyEditorService } from 'vs/workbench/services/workingCopy/common/workingCopyEditorService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ILabelService } from 'vs/platform/label/common/label';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { NotebookRendererMessagingService } from 'vs/workbench/contrib/notebook/browser/services/notebookRendererMessagingServiceImpl';
import { INotebookRendererMessagingService } from 'vs/workbench/contrib/notebook/common/notebookRendererMessagingService';
// Editor Controller
import 'vs/workbench/contrib/notebook/browser/controller/coreActions';
import 'vs/workbench/contrib/notebook/browser/controller/insertCellActions';
import 'vs/workbench/contrib/notebook/browser/controller/executeActions';
import 'vs/workbench/contrib/notebook/browser/controller/layoutActions';
import 'vs/workbench/contrib/notebook/browser/controller/editActions';
import 'vs/workbench/contrib/notebook/browser/controller/cellOutputActions';
import 'vs/workbench/contrib/notebook/browser/controller/apiActions';
import 'vs/workbench/contrib/notebook/browser/controller/foldingController';
// Editor Contribution
import 'vs/workbench/contrib/notebook/browser/contrib/clipboard/notebookClipboard';
import 'vs/workbench/contrib/notebook/browser/contrib/find/notebookFind';
import 'vs/workbench/contrib/notebook/browser/contrib/format/formatting';
import 'vs/workbench/contrib/notebook/browser/contrib/saveParticipants/saveParticipants';
import 'vs/workbench/contrib/notebook/browser/contrib/gettingStarted/notebookGettingStarted';
import 'vs/workbench/contrib/notebook/browser/contrib/layout/layoutActions';
import 'vs/workbench/contrib/notebook/browser/contrib/marker/markerProvider';
import 'vs/workbench/contrib/notebook/browser/contrib/navigation/arrow';
import 'vs/workbench/contrib/notebook/browser/contrib/outline/notebookOutline';
import 'vs/workbench/contrib/notebook/browser/contrib/profile/notebookProfile';
import 'vs/workbench/contrib/notebook/browser/contrib/cellStatusBar/statusBarProviders';
import 'vs/workbench/contrib/notebook/browser/contrib/cellStatusBar/contributedStatusBarItemController';
import 'vs/workbench/contrib/notebook/browser/contrib/cellStatusBar/executionStatusBarItemController';
import 'vs/workbench/contrib/notebook/browser/contrib/editorStatusBar/editorStatusBar';
import 'vs/workbench/contrib/notebook/browser/contrib/undoRedo/notebookUndoRedo';
import 'vs/workbench/contrib/notebook/browser/contrib/cellCommands/cellCommands';
import 'vs/workbench/contrib/notebook/browser/contrib/viewportWarmup/viewportWarmup';
import 'vs/workbench/contrib/notebook/browser/contrib/troubleshoot/layout';
import 'vs/workbench/contrib/notebook/browser/contrib/debug/notebookBreakpoints';
import 'vs/workbench/contrib/notebook/browser/contrib/debug/notebookCellPausing';
import 'vs/workbench/contrib/notebook/browser/contrib/debug/notebookDebugDecorations';
import 'vs/workbench/contrib/notebook/browser/contrib/execute/executionEditorProgress';
import 'vs/workbench/contrib/notebook/browser/contrib/kernelDetection/notebookKernelDetection';
// Diff Editor Contribution
import 'vs/workbench/contrib/notebook/browser/diff/notebookDiffActions';
// Services
import { editorOptionsRegistry } from 'vs/editor/common/config/editorOptions';
import { NotebookExecutionStateService } from 'vs/workbench/contrib/notebook/browser/services/notebookExecutionStateServiceImpl';
import { NotebookExecutionService } from 'vs/workbench/contrib/notebook/browser/services/notebookExecutionServiceImpl';
import { INotebookExecutionService } from 'vs/workbench/contrib/notebook/common/notebookExecutionService';
import { INotebookKeymapService } from 'vs/workbench/contrib/notebook/common/notebookKeymapService';
import { NotebookKeymapService } from 'vs/workbench/contrib/notebook/browser/services/notebookKeymapServiceImpl';
import { PLAINTEXT_LANGUAGE_ID } from 'vs/editor/common/languages/modesRegistry';
import { INotebookExecutionStateService } from 'vs/workbench/contrib/notebook/common/notebookExecutionStateService';
import { ILanguageFeaturesService } from 'vs/editor/common/services/languageFeatures';
import { NotebookInfo } from 'vs/editor/common/languageFeatureRegistry';
import { COMMENTEDITOR_DECORATION_KEY } from 'vs/workbench/contrib/comments/browser/commentReply';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import { NotebookKernelHistoryService } from 'vs/workbench/contrib/notebook/browser/services/notebookKernelHistoryServiceImpl';
import { INotebookLoggingService } from 'vs/workbench/contrib/notebook/common/notebookLoggingService';
import { NotebookLoggingService } from 'vs/workbench/contrib/notebook/browser/services/notebookLoggingServiceImpl';
import product from 'vs/platform/product/common/product';
import { NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_OUTPUT_FOCUSED } from 'vs/workbench/contrib/notebook/common/notebookContextKeys';
import { runAccessibilityHelpAction, showAccessibleOutput } from 'vs/workbench/contrib/notebook/browser/notebookAccessibility';
import { IAccessibleViewService } from 'vs/workbench/contrib/accessibility/browser/accessibleView';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { AccessibilityHelpAction, AccessibleViewAction } from 'vs/workbench/contrib/accessibility/browser/accessibleViewActions';
/*--------------------------------------------------------------------------------------------- */
Registry.as<IEditorPaneRegistry>(EditorExtensions.EditorPane).registerEditorPane(
EditorPaneDescriptor.create(
NotebookEditor,
NotebookEditor.ID,
'Notebook Editor'
),
[
new SyncDescriptor(NotebookEditorInput)
]
);
Registry.as<IEditorPaneRegistry>(EditorExtensions.EditorPane).registerEditorPane(
EditorPaneDescriptor.create(
NotebookTextDiffEditor,
NotebookTextDiffEditor.ID,
'Notebook Diff Editor'
),
[
new SyncDescriptor(NotebookDiffEditorInput)
]
);
class NotebookDiffEditorSerializer implements IEditorSerializer {
canSerialize(): boolean {
return true;
}
serialize(input: EditorInput): string {
assertType(input instanceof NotebookDiffEditorInput);
return JSON.stringify({
resource: input.resource,
originalResource: input.original.resource,
name: input.getName(),
originalName: input.original.getName(),
textDiffName: input.getName(),
viewType: input.viewType,
});
}
deserialize(instantiationService: IInstantiationService, raw: string) {
type Data = { resource: URI; originalResource: URI; name: string; originalName: string; viewType: string; textDiffName: string | undefined; group: number };
const data = <Data>parse(raw);
if (!data) {
return undefined;
}
const { resource, originalResource, name, viewType } = data;
if (!data || !URI.isUri(resource) || !URI.isUri(originalResource) || typeof name !== 'string' || typeof viewType !== 'string') {
return undefined;
}
const input = NotebookDiffEditorInput.create(instantiationService, resource, name, undefined, originalResource, viewType);
return input;
}
static canResolveBackup(editorInput: EditorInput, backupResource: URI): boolean {
return false;
}
}
type SerializedNotebookEditorData = { resource: URI; viewType: string; options?: NotebookEditorInputOptions };
class NotebookEditorSerializer implements IEditorSerializer {
canSerialize(): boolean {
return true;
}
serialize(input: EditorInput): string {
assertType(input instanceof NotebookEditorInput);
const data: SerializedNotebookEditorData = {
resource: input.resource,
viewType: input.viewType,
options: input.options
};
return JSON.stringify(data);
}
deserialize(instantiationService: IInstantiationService, raw: string) {
const data = <SerializedNotebookEditorData>parse(raw);
if (!data) {
return undefined;
}
const { resource, viewType, options } = data;
if (!data || !URI.isUri(resource) || typeof viewType !== 'string') {
return undefined;
}
const input = NotebookEditorInput.create(instantiationService, resource, viewType, options);
return input;
}
}
Registry.as<IEditorFactoryRegistry>(EditorExtensions.EditorFactory).registerEditorSerializer(
NotebookEditorInput.ID,
NotebookEditorSerializer
);
Registry.as<IEditorFactoryRegistry>(EditorExtensions.EditorFactory).registerEditorSerializer(
NotebookDiffEditorInput.ID,
NotebookDiffEditorSerializer
);
export class NotebookContribution extends Disposable implements IWorkbenchContribution {
private _uriComparisonKeyComputer?: IDisposable;
constructor(
@IUndoRedoService undoRedoService: IUndoRedoService,
@IConfigurationService configurationService: IConfigurationService,
@ICodeEditorService private readonly codeEditorService: ICodeEditorService,
) {
super();
this.updateCellUndoRedoComparisonKey(configurationService, undoRedoService);
// Watch for changes to undoRedoPerCell setting
this._register(configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration(NotebookSetting.undoRedoPerCell)) {
this.updateCellUndoRedoComparisonKey(configurationService, undoRedoService);
}
}));
// register comment decoration
this.codeEditorService.registerDecorationType('comment-controller', COMMENTEDITOR_DECORATION_KEY, {});
}
// Add or remove the cell undo redo comparison key based on the user setting
private updateCellUndoRedoComparisonKey(configurationService: IConfigurationService, undoRedoService: IUndoRedoService) {
const undoRedoPerCell = configurationService.getValue<boolean>(NotebookSetting.undoRedoPerCell);
if (!undoRedoPerCell) {
// Add comparison key to map cell => main document
if (!this._uriComparisonKeyComputer) {
this._uriComparisonKeyComputer = undoRedoService.registerUriComparisonKeyComputer(CellUri.scheme, {
getComparisonKey: (uri: URI): string => {
if (undoRedoPerCell) {
return uri.toString();
}
return NotebookContribution._getCellUndoRedoComparisonKey(uri);
}
});
}
} else {
// Dispose comparison key
this._uriComparisonKeyComputer?.dispose();
this._uriComparisonKeyComputer = undefined;
}
}
private static _getCellUndoRedoComparisonKey(uri: URI) {
const data = CellUri.parse(uri);
if (!data) {
return uri.toString();
}
return data.notebook.toString();
}
override dispose(): void {
super.dispose();
this._uriComparisonKeyComputer?.dispose();
}
}
class CellContentProvider implements ITextModelContentProvider {
private readonly _registration: IDisposable;
constructor(
@ITextModelService textModelService: ITextModelService,
@IModelService private readonly _modelService: IModelService,
@ILanguageService private readonly _languageService: ILanguageService,
@INotebookEditorModelResolverService private readonly _notebookModelResolverService: INotebookEditorModelResolverService,
) {
this._registration = textModelService.registerTextModelContentProvider(CellUri.scheme, this);
}
dispose(): void {
this._registration.dispose();
}
async provideTextContent(resource: URI): Promise<ITextModel | null> {
const existing = this._modelService.getModel(resource);
if (existing) {
return existing;
}
const data = CellUri.parse(resource);
// const data = parseCellUri(resource);
if (!data) {
return null;
}
const ref = await this._notebookModelResolverService.resolve(data.notebook);
let result: ITextModel | null = null;
if (!ref.object.isResolved()) {
return null;
}
for (const cell of ref.object.notebook.cells) {
if (cell.uri.toString() === resource.toString()) {
const bufferFactory: ITextBufferFactory = {
create: (defaultEOL) => {
const newEOL = (defaultEOL === DefaultEndOfLine.CRLF ? '\r\n' : '\n');
(cell.textBuffer as ITextBuffer).setEOL(newEOL);
return { textBuffer: cell.textBuffer as ITextBuffer, disposable: Disposable.None };
},
getFirstLineText: (limit: number) => {
return cell.textBuffer.getLineContent(1).substring(0, limit);
}
};
const languageId = this._languageService.getLanguageIdByLanguageName(cell.language);
const languageSelection = languageId ? this._languageService.createById(languageId) : (cell.cellKind === CellKind.Markup ? this._languageService.createById('markdown') : this._languageService.createByFilepathOrFirstLine(resource, cell.textBuffer.getLineContent(1)));
result = this._modelService.createModel(
bufferFactory,
languageSelection,
resource
);
break;
}
}
if (!result) {
ref.dispose();
return null;
}
const once = Event.any(result.onWillDispose, ref.object.notebook.onWillDispose)(() => {
once.dispose();
ref.dispose();
});
return result;
}
}
class CellInfoContentProvider {
private readonly _disposables: IDisposable[] = [];
constructor(
@ITextModelService textModelService: ITextModelService,
@IModelService private readonly _modelService: IModelService,
@ILanguageService private readonly _languageService: ILanguageService,
@ILabelService private readonly _labelService: ILabelService,
@INotebookEditorModelResolverService private readonly _notebookModelResolverService: INotebookEditorModelResolverService,
) {
this._disposables.push(textModelService.registerTextModelContentProvider(Schemas.vscodeNotebookCellMetadata, {
provideTextContent: this.provideMetadataTextContent.bind(this)
}));
this._disposables.push(textModelService.registerTextModelContentProvider(Schemas.vscodeNotebookCellOutput, {
provideTextContent: this.provideOutputTextContent.bind(this)
}));
this._disposables.push(this._labelService.registerFormatter({
scheme: Schemas.vscodeNotebookCellMetadata,
formatting: {
label: '${path} (metadata)',
separator: '/'
}
}));
this._disposables.push(this._labelService.registerFormatter({
scheme: Schemas.vscodeNotebookCellOutput,
formatting: {
label: '${path} (output)',
separator: '/'
}
}));
}
dispose(): void {
dispose(this._disposables);
}
async provideMetadataTextContent(resource: URI): Promise<ITextModel | null> {
const existing = this._modelService.getModel(resource);
if (existing) {
return existing;
}
const data = CellUri.parseCellPropertyUri(resource, Schemas.vscodeNotebookCellMetadata);
if (!data) {
return null;
}
const ref = await this._notebookModelResolverService.resolve(data.notebook);
let result: ITextModel | null = null;
const mode = this._languageService.createById('json');
for (const cell of ref.object.notebook.cells) {
if (cell.handle === data.handle) {
const metadataSource = getFormattedMetadataJSON(ref.object.notebook, cell.metadata, cell.language);
result = this._modelService.createModel(
metadataSource,
mode,
resource
);
break;
}
}
if (!result) {
ref.dispose();
return null;
}
const once = result.onWillDispose(() => {
once.dispose();
ref.dispose();
});
return result;
}
private parseStreamOutput(op?: ICellOutput): { content: string; mode: ILanguageSelection } | undefined {
if (!op) {
return;
}
const streamOutputData = getStreamOutputData(op.outputs);
if (streamOutputData) {
return {
content: streamOutputData,
mode: this._languageService.createById(PLAINTEXT_LANGUAGE_ID)
};
}
return;
}
private _getResult(data: {
notebook: URI;
outputId?: string | undefined;
}, cell: ICell) {
let result: { content: string; mode: ILanguageSelection } | undefined = undefined;
const mode = this._languageService.createById('json');
const op = cell.outputs.find(op => op.outputId === data.outputId);
const streamOutputData = this.parseStreamOutput(op);
if (streamOutputData) {
result = streamOutputData;
return result;
}
const obj = cell.outputs.map(output => ({
metadata: output.metadata,
outputItems: output.outputs.map(opit => ({
mimeType: opit.mime,
data: opit.data.toString()
}))
}));
const outputSource = toFormattedString(obj, {});
result = {
content: outputSource,
mode
};
return result;
}
async provideOutputTextContent(resource: URI): Promise<ITextModel | null> {
const existing = this._modelService.getModel(resource);
if (existing) {
return existing;
}
const data = CellUri.parseCellOutputUri(resource);
if (!data) {
return null;
}
const ref = await this._notebookModelResolverService.resolve(data.notebook);
const cell = ref.object.notebook.cells.find(cell => !!cell.outputs.find(op => op.outputId === data.outputId));
if (!cell) {
ref.dispose();
return null;
}
const result = this._getResult(data, cell);
if (!result) {
ref.dispose();
return null;
}
const model = this._modelService.createModel(result.content, result.mode, resource);
const cellModelListener = Event.any(cell.onDidChangeOutputs ?? Event.None, cell.onDidChangeOutputItems ?? Event.None)(() => {
const newResult = this._getResult(data, cell);
if (!newResult) {
return;
}
model.setValue(newResult.content);
model.setLanguage(newResult.mode.languageId);
});
const once = model.onWillDispose(() => {
once.dispose();
cellModelListener.dispose();
ref.dispose();
});
return model;
}
}
class RegisterSchemasContribution extends Disposable implements IWorkbenchContribution {
constructor() {
super();
this.registerMetadataSchemas();
}
private registerMetadataSchemas(): void {
const jsonRegistry = Registry.as<IJSONContributionRegistry>(JSONExtensions.JSONContribution);
const metadataSchema: IJSONSchema = {
properties: {
['language']: {
type: 'string',
description: 'The language for the cell'
}
},
// patternProperties: allSettings.patternProperties,
additionalProperties: true,
allowTrailingCommas: true,
allowComments: true
};
jsonRegistry.registerSchema('vscode://schemas/notebook/cellmetadata', metadataSchema);
}
}
class NotebookEditorManager implements IWorkbenchContribution {
private readonly _disposables = new DisposableStore();
constructor(
@IEditorService private readonly _editorService: IEditorService,
@INotebookEditorModelResolverService private readonly _notebookEditorModelService: INotebookEditorModelResolverService,
@IEditorGroupsService editorGroups: IEditorGroupsService
) {
// OPEN notebook editor for models that have turned dirty without being visible in an editor
type E = IResolvedNotebookEditorModel;
this._disposables.add(Event.debounce<E, E[]>(
this._notebookEditorModelService.onDidChangeDirty,
(last, current) => !last ? [current] : [...last, current],
100
)(this._openMissingDirtyNotebookEditors, this));
// CLOSE editors when we are about to open conflicting notebooks
this._disposables.add(_notebookEditorModelService.onWillFailWithConflict(e => {
for (const group of editorGroups.groups) {
const conflictInputs = group.editors.filter(input => input instanceof NotebookEditorInput && input.viewType !== e.viewType && isEqual(input.resource, e.resource));
const p = group.closeEditors(conflictInputs);
e.waitUntil(p);
}
}));
}
dispose(): void {
this._disposables.dispose();
}
private _openMissingDirtyNotebookEditors(models: IResolvedNotebookEditorModel[]): void {
const result: IResourceEditorInput[] = [];
for (const model of models) {
if (model.isDirty() && !this._editorService.isOpened({ resource: model.resource, typeId: NotebookEditorInput.ID, editorId: model.viewType }) && extname(model.resource) !== '.interactive') {
result.push({
resource: model.resource,
options: { inactive: true, preserveFocus: true, pinned: true, override: model.viewType }
});
}
}
if (result.length > 0) {
this._editorService.openEditors(result);
}
}
}
class SimpleNotebookWorkingCopyEditorHandler extends Disposable implements IWorkbenchContribution, IWorkingCopyEditorHandler {
constructor(
@IInstantiationService private readonly _instantiationService: IInstantiationService,
@IWorkingCopyEditorService private readonly _workingCopyEditorService: IWorkingCopyEditorService,
@IExtensionService private readonly _extensionService: IExtensionService,
@INotebookService private readonly _notebookService: INotebookService
) {
super();
this._installHandler();
}
async handles(workingCopy: IWorkingCopyIdentifier): Promise<boolean> {
const viewType = this.handlesSync(workingCopy);
if (!viewType) {
return false;
}
return this._notebookService.canResolve(viewType);
}
private handlesSync(workingCopy: IWorkingCopyIdentifier): string /* viewType */ | undefined {
const viewType = this._getViewType(workingCopy);
if (!viewType || viewType === 'interactive') {
return undefined;
}
return viewType;
}
isOpen(workingCopy: IWorkingCopyIdentifier, editor: EditorInput): boolean {
if (!this.handlesSync(workingCopy)) {
return false;
}
return editor instanceof NotebookEditorInput && editor.viewType === this._getViewType(workingCopy) && isEqual(workingCopy.resource, editor.resource);
}
createEditor(workingCopy: IWorkingCopyIdentifier): EditorInput {
return NotebookEditorInput.create(this._instantiationService, workingCopy.resource, this._getViewType(workingCopy)!);
}
private async _installHandler(): Promise<void> {
await this._extensionService.whenInstalledExtensionsRegistered();
this._register(this._workingCopyEditorService.registerHandler(this));
}
private _getViewType(workingCopy: IWorkingCopyIdentifier): string | undefined {
return NotebookWorkingCopyTypeIdentifier.parse(workingCopy.typeId);
}
}
class NotebookLanguageSelectorScoreRefine {
constructor(
@INotebookService private readonly _notebookService: INotebookService,
@ILanguageFeaturesService languageFeaturesService: ILanguageFeaturesService,
) {
languageFeaturesService.setNotebookTypeResolver(this._getNotebookInfo.bind(this));
}
private _getNotebookInfo(uri: URI): NotebookInfo | undefined {
const cellUri = CellUri.parse(uri);
if (!cellUri) {
return undefined;
}
const notebook = this._notebookService.getNotebookTextModel(cellUri.notebook);
if (!notebook) {
return undefined;
}
return {
uri: notebook.uri,
type: notebook.viewType
};
}
}
class NotebookAccessibilityHelpContribution extends Disposable {
static ID: 'notebookAccessibilityHelpContribution';
constructor() {
super();
this._register(AccessibilityHelpAction.addImplementation(105, 'notebook', async accessor => {
const codeEditor = accessor.get(ICodeEditorService).getActiveCodeEditor() || accessor.get(ICodeEditorService).getFocusedCodeEditor();
if (!codeEditor) {
return;
}
runAccessibilityHelpAction(accessor, codeEditor);
}, NOTEBOOK_IS_ACTIVE_EDITOR));
}
}
class NotebookAccessibleViewContribution extends Disposable {
static ID: 'chatAccessibleViewContribution';
constructor() {
super();
this._register(AccessibleViewAction.addImplementation(100, 'notebook', accessor => {
const accessibleViewService = accessor.get(IAccessibleViewService);
const editorService = accessor.get(IEditorService);
return showAccessibleOutput(accessibleViewService, editorService);
},
ContextKeyExpr.and(NOTEBOOK_OUTPUT_FOCUSED, ContextKeyExpr.equals('resourceExtname', '.ipynb'))
));
}
}
const workbenchContributionsRegistry = Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench);
workbenchContributionsRegistry.registerWorkbenchContribution(NotebookContribution, LifecyclePhase.Starting);
workbenchContributionsRegistry.registerWorkbenchContribution(CellContentProvider, LifecyclePhase.Starting);
workbenchContributionsRegistry.registerWorkbenchContribution(CellInfoContentProvider, LifecyclePhase.Starting);
workbenchContributionsRegistry.registerWorkbenchContribution(RegisterSchemasContribution, LifecyclePhase.Starting);
workbenchContributionsRegistry.registerWorkbenchContribution(NotebookEditorManager, LifecyclePhase.Ready);
workbenchContributionsRegistry.registerWorkbenchContribution(NotebookLanguageSelectorScoreRefine, LifecyclePhase.Ready);
workbenchContributionsRegistry.registerWorkbenchContribution(SimpleNotebookWorkingCopyEditorHandler, LifecyclePhase.Ready);
workbenchContributionsRegistry.registerWorkbenchContribution(NotebookAccessibilityHelpContribution, LifecyclePhase.Eventually);
workbenchContributionsRegistry.registerWorkbenchContribution(NotebookAccessibleViewContribution, LifecyclePhase.Eventually);
registerSingleton(INotebookService, NotebookService, InstantiationType.Delayed);
registerSingleton(INotebookEditorWorkerService, NotebookEditorWorkerServiceImpl, InstantiationType.Delayed);
registerSingleton(INotebookEditorModelResolverService, NotebookModelResolverServiceImpl, InstantiationType.Delayed);
registerSingleton(INotebookCellStatusBarService, NotebookCellStatusBarService, InstantiationType.Delayed);
registerSingleton(INotebookEditorService, NotebookEditorWidgetService, InstantiationType.Delayed);
registerSingleton(INotebookKernelService, NotebookKernelService, InstantiationType.Delayed);
registerSingleton(INotebookKernelHistoryService, NotebookKernelHistoryService, InstantiationType.Delayed);
registerSingleton(INotebookExecutionService, NotebookExecutionService, InstantiationType.Delayed);
registerSingleton(INotebookExecutionStateService, NotebookExecutionStateService, InstantiationType.Delayed);
registerSingleton(INotebookRendererMessagingService, NotebookRendererMessagingService, InstantiationType.Delayed);
registerSingleton(INotebookKeymapService, NotebookKeymapService, InstantiationType.Delayed);
registerSingleton(INotebookLoggingService, NotebookLoggingService, InstantiationType.Delayed);
const schemas: IJSONSchemaMap = {};
function isConfigurationPropertySchema(x: IConfigurationPropertySchema | { [path: string]: IConfigurationPropertySchema }): x is IConfigurationPropertySchema {
return (typeof x.type !== 'undefined' || typeof x.anyOf !== 'undefined');
}
for (const editorOption of editorOptionsRegistry) {
const schema = editorOption.schema;
if (schema) {
if (isConfigurationPropertySchema(schema)) {
schemas[`editor.${editorOption.name}`] = schema;
} else {
for (const key in schema) {
if (Object.hasOwnProperty.call(schema, key)) {
schemas[key] = schema[key];
}
}
}
}
}
const editorOptionsCustomizationSchema: IConfigurationPropertySchema = {
description: nls.localize('notebook.editorOptions.experimentalCustomization', 'Settings for code editors used in notebooks. This can be used to customize most editor.* settings.'),
default: {},
allOf: [
{
properties: schemas,
}
// , {
// patternProperties: {
// '^\\[.*\\]$': {
// type: 'object',
// default: {},
// properties: schemas
// }
// }
// }
],
tags: ['notebookLayout']
};
const configurationRegistry = Registry.as<IConfigurationRegistry>(Extensions.Configuration);
configurationRegistry.registerConfiguration({
id: 'notebook',
order: 100,
title: nls.localize('notebookConfigurationTitle', "Notebook"),
type: 'object',
properties: {
[NotebookSetting.displayOrder]: {
description: nls.localize('notebook.displayOrder.description', "Priority list for output mime types"),
type: 'array',
items: {
type: 'string'
},
default: []
},
[NotebookSetting.cellToolbarLocation]: {
description: nls.localize('notebook.cellToolbarLocation.description', "Where the cell toolbar should be shown, or whether it should be hidden."),
type: 'object',
additionalProperties: {
markdownDescription: nls.localize('notebook.cellToolbarLocation.viewType', "Configure the cell toolbar position for for specific file types"),
type: 'string',
enum: ['left', 'right', 'hidden']
},
default: {
'default': 'right'
},
tags: ['notebookLayout']
},
[NotebookSetting.showCellStatusBar]: {
description: nls.localize('notebook.showCellStatusbar.description', "Whether the cell status bar should be shown."),
type: 'string',
enum: ['hidden', 'visible', 'visibleAfterExecute'],
enumDescriptions: [
nls.localize('notebook.showCellStatusbar.hidden.description', "The cell Status bar is always hidden."),
nls.localize('notebook.showCellStatusbar.visible.description', "The cell Status bar is always visible."),
nls.localize('notebook.showCellStatusbar.visibleAfterExecute.description', "The cell Status bar is hidden until the cell has executed. Then it becomes visible to show the execution status.")],
default: 'visible',
tags: ['notebookLayout']
},
[NotebookSetting.textDiffEditorPreview]: {
description: nls.localize('notebook.diff.enablePreview.description', "Whether to use the enhanced text diff editor for notebook."),
type: 'boolean',
default: true,
tags: ['notebookLayout']
},
[NotebookSetting.diffOverviewRuler]: {
description: nls.localize('notebook.diff.enableOverviewRuler.description', "Whether to render the overview ruler in the diff editor for notebook."),
type: 'boolean',
default: false,
tags: ['notebookLayout']
},
[NotebookSetting.cellToolbarVisibility]: {
markdownDescription: nls.localize('notebook.cellToolbarVisibility.description', "Whether the cell toolbar should appear on hover or click."),
type: 'string',
enum: ['hover', 'click'],
default: 'click',
tags: ['notebookLayout']
},
[NotebookSetting.undoRedoPerCell]: {
description: nls.localize('notebook.undoRedoPerCell.description', "Whether to use separate undo/redo stack for each cell."),
type: 'boolean',
default: true,
tags: ['notebookLayout']
},
[NotebookSetting.compactView]: {
description: nls.localize('notebook.compactView.description', "Control whether the notebook editor should be rendered in a compact form. For example, when turned on, it will decrease the left margin width."),
type: 'boolean',
default: true,
tags: ['notebookLayout']
},
[NotebookSetting.focusIndicator]: {
description: nls.localize('notebook.focusIndicator.description', "Controls where the focus indicator is rendered, either along the cell borders or on the left gutter."),
type: 'string',
enum: ['border', 'gutter'],
default: 'gutter',
tags: ['notebookLayout']
},
[NotebookSetting.insertToolbarLocation]: {
description: nls.localize('notebook.insertToolbarPosition.description', "Control where the insert cell actions should appear."),
type: 'string',
enum: ['betweenCells', 'notebookToolbar', 'both', 'hidden'],
enumDescriptions: [
nls.localize('insertToolbarLocation.betweenCells', "A toolbar that appears on hover between cells."),
nls.localize('insertToolbarLocation.notebookToolbar', "The toolbar at the top of the notebook editor."),
nls.localize('insertToolbarLocation.both', "Both toolbars."),
nls.localize('insertToolbarLocation.hidden', "The insert actions don't appear anywhere."),
],
default: 'both',
tags: ['notebookLayout']
},
[NotebookSetting.globalToolbar]: {
description: nls.localize('notebook.globalToolbar.description', "Control whether to render a global toolbar inside the notebook editor."),
type: 'boolean',
default: true,
tags: ['notebookLayout']
},
[NotebookSetting.stickyScroll]: {
description: nls.localize('notebook.stickyScroll.description', "Experimental. Control whether to render notebook Sticky Scroll headers in the notebook editor."),
type: 'boolean',
default: false,
tags: ['notebookLayout']
},
[NotebookSetting.consolidatedOutputButton]: {
description: nls.localize('notebook.consolidatedOutputButton.description', "Control whether outputs action should be rendered in the output toolbar."),
type: 'boolean',
default: true,
tags: ['notebookLayout']
},
[NotebookSetting.showFoldingControls]: {
description: nls.localize('notebook.showFoldingControls.description', "Controls when the Markdown header folding arrow is shown."),
type: 'string',
enum: ['always', 'never', 'mouseover'],
enumDescriptions: [
nls.localize('showFoldingControls.always', "The folding controls are always visible."),
nls.localize('showFoldingControls.never', "Never show the folding controls and reduce the gutter size."),
nls.localize('showFoldingControls.mouseover', "The folding controls are visible only on mouseover."),
],
default: 'mouseover',
tags: ['notebookLayout']
},
[NotebookSetting.dragAndDropEnabled]: {
description: nls.localize('notebook.dragAndDrop.description', "Control whether the notebook editor should allow moving cells through drag and drop."),
type: 'boolean',
default: true,
tags: ['notebookLayout']
},
[NotebookSetting.consolidatedRunButton]: {
description: nls.localize('notebook.consolidatedRunButton.description', "Control whether extra actions are shown in a dropdown next to the run button."),
type: 'boolean',
default: false,
tags: ['notebookLayout']
},
[NotebookSetting.globalToolbarShowLabel]: {
description: nls.localize('notebook.globalToolbarShowLabel', "Control whether the actions on the notebook toolbar should render label or not."),
type: 'string',
enum: ['always', 'never', 'dynamic'],
default: 'always',
tags: ['notebookLayout']
},
[NotebookSetting.textOutputLineLimit]: {
markdownDescription: nls.localize('notebook.textOutputLineLimit', "Controls how many lines of text are displayed in a text output. If {0} is enabled, this setting is used to determine the scroll height of the output.", '`#notebook.output.scrolling#`'),
type: 'number',
default: 30,
tags: ['notebookLayout', 'notebookOutputLayout']
},
[NotebookSetting.markupFontSize]: {
markdownDescription: nls.localize('notebook.markup.fontSize', "Controls the font size in pixels of rendered markup in notebooks. When set to {0}, 120% of {1} is used.", '`0`', '`#editor.fontSize#`'),
type: 'number',
default: 0,
tags: ['notebookLayout']
},
[NotebookSetting.cellEditorOptionsCustomizations]: editorOptionsCustomizationSchema,
[NotebookSetting.interactiveWindowCollapseCodeCells]: {
markdownDescription: nls.localize('notebook.interactiveWindow.collapseCodeCells', "Controls whether code cells in the interactive window are collapsed by default."),
type: 'string',
enum: ['always', 'never', 'fromEditor'],
default: 'fromEditor'
},
[NotebookSetting.outputLineHeight]: {
markdownDescription: nls.localize('notebook.outputLineHeight', "Line height of the output text within notebook cells.\n - When set to 0, editor line height is used.\n - Values between 0 and 8 will be used as a multiplier with the font size.\n - Values greater than or equal to 8 will be used as effective values."),
type: 'number',
default: 0,
tags: ['notebookLayout', 'notebookOutputLayout']
},
[NotebookSetting.outputFontSize]: {
markdownDescription: nls.localize('notebook.outputFontSize', "Font size for the output text within notebook cells. When set to 0, {0} is used.", '`#editor.fontSize#`'),
type: 'number',
default: 0,
tags: ['notebookLayout', 'notebookOutputLayout']
},
[NotebookSetting.outputFontFamily]: {
markdownDescription: nls.localize('notebook.outputFontFamily', "The font family of the output text within notebook cells. When set to empty, the {0} is used.", '`#editor.fontFamily#`'),
type: 'string',
tags: ['notebookLayout', 'notebookOutputLayout']
},
[NotebookSetting.outputScrolling]: {
markdownDescription: nls.localize('notebook.outputScrolling', "Initially render notebook outputs in a scrollable region when longer than the limit"),
type: 'boolean',
tags: ['notebookLayout', 'notebookOutputLayout'],
default: typeof product.quality === 'string' && product.quality !== 'stable' // only enable as default in insiders
},
[NotebookSetting.outputWordWrap]: {
markdownDescription: nls.localize('notebook.outputWordWrap', "Controls whether the lines in output should wrap."),
type: 'boolean',
tags: ['notebookLayout', 'notebookOutputLayout'],
default: false
},
[NotebookSetting.formatOnSave]: {
markdownDescription: nls.localize('notebook.formatOnSave', "Format a notebook on save. A formatter must be available, the file must not be saved after delay, and the editor must not be shutting down."),
type: 'boolean',
tags: ['notebookLayout'],
default: false
},
[NotebookSetting.codeActionsOnSave]: {
markdownDescription: nls.localize('notebook.codeActionsOnSave', "Experimental. Run a series of CodeActions for a notebook on save. CodeActions must be specified, the file must not be saved after delay, and the editor must not be shutting down. Example: `source.fixAll: true`"),
type: 'object',
additionalProperties: {
type: 'boolean'
},
default: {}
},
[NotebookSetting.formatOnCellExecution]: {
markdownDescription: nls.localize('notebook.formatOnCellExecution', "Format a notebook cell upon execution. A formatter must be available."),
type: 'boolean',
default: false
},
[NotebookSetting.confirmDeleteRunningCell]: {
markdownDescription: nls.localize('notebook.confirmDeleteRunningCell', "Control whether a confirmation prompt is required to delete a running cell."),
type: 'boolean',
default: true
},
[NotebookSetting.findScope]: {
markdownDescription: nls.localize('notebook.findScope', "Customize the Find Widget behavior for searching within notebook cells. When both markup source and markup preview are enabled, the Find Widget will search either the source code or preview based on the current state of the cell."),
type: 'object',
properties: {
markupSource: {
type: 'boolean',
default: true
},
markupPreview: {
type: 'boolean',
default: true
},
codeSource: {
type: 'boolean',
default: true
},
codeOutput: {
type: 'boolean',
default: true
}
},
default: {
markupSource: true,
markupPreview: true,
codeSource: true,
codeOutput: true
},
tags: ['notebookLayout']
},
[NotebookSetting.remoteSaving]: {
markdownDescription: nls.localize('notebook.remoteSaving', "Enables the incremental saving of notebooks in Remote environment. When enabled, only the changes to the notebook are sent to the extension host, improving performance for large notebooks and slow network connections."),
type: 'boolean',
default: typeof product.quality === 'string' && product.quality !== 'stable' // only enable as default in insiders
}
}
});
| src/vs/workbench/contrib/notebook/browser/notebook.contribution.ts | 1 | https://github.com/microsoft/vscode/commit/94956b4c3fb38badce912cae3d5a531502669885 | [
0.0005042794509790838,
0.0001795298740034923,
0.00016407622024416924,
0.00017110070621129125,
0.00004071718285558745
] |
{
"id": 2,
"code_window": [
"\t\treturn this._rawOutput.outputId;\n",
"\t}\n",
"\n",
"\tprivate _versionId = 0;\n",
"\n",
"\tget versionId() {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t/**\n",
"\t * Alternative output id that's reused when the output is updated.\n",
"\t */\n",
"\tprivate _alternativeOutputId: string;\n",
"\n",
"\tget alternativeOutputId(): string {\n",
"\t\treturn this._alternativeOutputId;\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/common/model/notebookCellOutputTextModel.ts",
"type": "add",
"edit_start_line_idx": 27
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { URI } from 'vs/base/common/uri';
import { isMacintosh, isLinux, isWindows } from 'vs/base/common/platform';
import { OutputLinkComputer } from 'vs/workbench/contrib/output/common/outputLinkComputer';
import { TestContextService } from 'vs/workbench/test/common/workbenchTestServices';
suite('OutputLinkProvider', () => {
function toOSPath(p: string): string {
if (isMacintosh || isLinux) {
return p.replace(/\\/g, '/');
}
return p;
}
test('OutputLinkProvider - Link detection', function () {
const rootFolder = isWindows ? URI.file('C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala') :
URI.file('C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala');
const patterns = OutputLinkComputer.createPatterns(rootFolder);
const contextService = new TestContextService();
let line = toOSPath('Foo bar');
let result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 0);
// Example: at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts
line = toOSPath(' at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts in');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/Game.ts').toString());
assert.strictEqual(result[0].range.startColumn, 5);
assert.strictEqual(result[0].range.endColumn, 84);
// Example: at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts:336
line = toOSPath(' at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts:336 in');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/Game.ts').toString() + '#336');
assert.strictEqual(result[0].range.startColumn, 5);
assert.strictEqual(result[0].range.endColumn, 88);
// Example: at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts:336:9
line = toOSPath(' at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts:336:9 in');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/Game.ts').toString() + '#336,9');
assert.strictEqual(result[0].range.startColumn, 5);
assert.strictEqual(result[0].range.endColumn, 90);
line = toOSPath(' at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts:336:9 in');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/Game.ts').toString() + '#336,9');
assert.strictEqual(result[0].range.startColumn, 5);
assert.strictEqual(result[0].range.endColumn, 90);
// Example: at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts>dir
line = toOSPath(' at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts>dir in');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/Game.ts').toString());
assert.strictEqual(result[0].range.startColumn, 5);
assert.strictEqual(result[0].range.endColumn, 84);
// Example: at [C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts:336:9]
line = toOSPath(' at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts:336:9] in');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/Game.ts').toString() + '#336,9');
assert.strictEqual(result[0].range.startColumn, 5);
assert.strictEqual(result[0].range.endColumn, 90);
// Example: at [C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts]
line = toOSPath(' at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts] in');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/Game.ts]').toString());
// Example: C:\Users\someone\AppData\Local\Temp\_monacodata_9888\workspaces\express\server.js on line 8
line = toOSPath('C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts on line 8');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/Game.ts').toString() + '#8');
assert.strictEqual(result[0].range.startColumn, 1);
assert.strictEqual(result[0].range.endColumn, 90);
// Example: C:\Users\someone\AppData\Local\Temp\_monacodata_9888\workspaces\express\server.js on line 8, column 13
line = toOSPath('C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts on line 8, column 13');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/Game.ts').toString() + '#8,13');
assert.strictEqual(result[0].range.startColumn, 1);
assert.strictEqual(result[0].range.endColumn, 101);
line = toOSPath('C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts on LINE 8, COLUMN 13');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/Game.ts').toString() + '#8,13');
assert.strictEqual(result[0].range.startColumn, 1);
assert.strictEqual(result[0].range.endColumn, 101);
// Example: C:\Users\someone\AppData\Local\Temp\_monacodata_9888\workspaces\express\server.js:line 8
line = toOSPath('C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts:line 8');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/Game.ts').toString() + '#8');
assert.strictEqual(result[0].range.startColumn, 1);
assert.strictEqual(result[0].range.endColumn, 87);
// Example: at File.put (C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Game.ts)
line = toOSPath(' at File.put (C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Game.ts)');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/Game.ts').toString());
assert.strictEqual(result[0].range.startColumn, 15);
assert.strictEqual(result[0].range.endColumn, 94);
// Example: at File.put (C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Game.ts:278)
line = toOSPath(' at File.put (C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Game.ts:278)');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/Game.ts').toString() + '#278');
assert.strictEqual(result[0].range.startColumn, 15);
assert.strictEqual(result[0].range.endColumn, 98);
// Example: at File.put (C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Game.ts:278:34)
line = toOSPath(' at File.put (C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Game.ts:278:34)');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/Game.ts').toString() + '#278,34');
assert.strictEqual(result[0].range.startColumn, 15);
assert.strictEqual(result[0].range.endColumn, 101);
line = toOSPath(' at File.put (C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Game.ts:278:34)');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/Game.ts').toString() + '#278,34');
assert.strictEqual(result[0].range.startColumn, 15);
assert.strictEqual(result[0].range.endColumn, 101);
// Example: C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Features.ts(45): error
line = toOSPath('C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/lib/something/Features.ts(45): error');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45');
assert.strictEqual(result[0].range.startColumn, 1);
assert.strictEqual(result[0].range.endColumn, 102);
// Example: C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Features.ts (45,18): error
line = toOSPath('C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/lib/something/Features.ts (45): error');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45');
assert.strictEqual(result[0].range.startColumn, 1);
assert.strictEqual(result[0].range.endColumn, 103);
// Example: C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Features.ts(45,18): error
line = toOSPath('C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/lib/something/Features.ts(45,18): error');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45,18');
assert.strictEqual(result[0].range.startColumn, 1);
assert.strictEqual(result[0].range.endColumn, 105);
line = toOSPath('C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/lib/something/Features.ts(45,18): error');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45,18');
assert.strictEqual(result[0].range.startColumn, 1);
assert.strictEqual(result[0].range.endColumn, 105);
// Example: C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Features.ts (45,18): error
line = toOSPath('C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/lib/something/Features.ts (45,18): error');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45,18');
assert.strictEqual(result[0].range.startColumn, 1);
assert.strictEqual(result[0].range.endColumn, 106);
line = toOSPath('C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/lib/something/Features.ts (45,18): error');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45,18');
assert.strictEqual(result[0].range.startColumn, 1);
assert.strictEqual(result[0].range.endColumn, 106);
// Example: C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Features.ts(45): error
line = toOSPath('C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\lib\\something\\Features.ts(45): error');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45');
assert.strictEqual(result[0].range.startColumn, 1);
assert.strictEqual(result[0].range.endColumn, 102);
// Example: C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Features.ts (45,18): error
line = toOSPath('C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\lib\\something\\Features.ts (45): error');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45');
assert.strictEqual(result[0].range.startColumn, 1);
assert.strictEqual(result[0].range.endColumn, 103);
// Example: C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Features.ts(45,18): error
line = toOSPath('C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\lib\\something\\Features.ts(45,18): error');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45,18');
assert.strictEqual(result[0].range.startColumn, 1);
assert.strictEqual(result[0].range.endColumn, 105);
line = toOSPath('C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\lib\\something\\Features.ts(45,18): error');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45,18');
assert.strictEqual(result[0].range.startColumn, 1);
assert.strictEqual(result[0].range.endColumn, 105);
// Example: C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Features.ts (45,18): error
line = toOSPath('C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\lib\\something\\Features.ts (45,18): error');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45,18');
assert.strictEqual(result[0].range.startColumn, 1);
assert.strictEqual(result[0].range.endColumn, 106);
line = toOSPath('C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\lib\\something\\Features.ts (45,18): error');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45,18');
assert.strictEqual(result[0].range.startColumn, 1);
assert.strictEqual(result[0].range.endColumn, 106);
// Example: C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\lib\\something\\Features Special.ts (45,18): error.
line = toOSPath('C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\lib\\something\\Features Special.ts (45,18): error');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/lib/something/Features Special.ts').toString() + '#45,18');
assert.strictEqual(result[0].range.startColumn, 1);
assert.strictEqual(result[0].range.endColumn, 114);
// Example: at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts.
line = toOSPath(' at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts. in');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/Game.ts').toString());
assert.strictEqual(result[0].range.startColumn, 5);
assert.strictEqual(result[0].range.endColumn, 84);
// Example: at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game
line = toOSPath(' at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game in');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
// Example: at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game\\
line = toOSPath(' at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game\\ in');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
// Example: at "C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts"
line = toOSPath(' at "C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts" in');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/Game.ts').toString());
assert.strictEqual(result[0].range.startColumn, 6);
assert.strictEqual(result[0].range.endColumn, 85);
// Example: at 'C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts'
line = toOSPath(' at \'C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts\' in');
result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 1);
assert.strictEqual(result[0].url, contextService.toResource('/Game.ts\'').toString());
assert.strictEqual(result[0].range.startColumn, 6);
assert.strictEqual(result[0].range.endColumn, 86);
});
test('OutputLinkProvider - #106847', function () {
const rootFolder = isWindows ? URI.file('C:\\Users\\username\\Desktop\\test-ts') :
URI.file('C:/Users/username/Desktop');
const patterns = OutputLinkComputer.createPatterns(rootFolder);
const contextService = new TestContextService();
const line = toOSPath('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa C:\\Users\\username\\Desktop\\test-ts\\prj.conf C:\\Users\\username\\Desktop\\test-ts\\prj.conf C:\\Users\\username\\Desktop\\test-ts\\prj.conf');
const result = OutputLinkComputer.detectLinks(line, 1, patterns, contextService);
assert.strictEqual(result.length, 3);
for (const res of result) {
assert.ok(res.range.startColumn > 0 && res.range.endColumn > 0);
}
});
});
| src/vs/workbench/contrib/output/test/browser/outputLinkProvider.test.ts | 0 | https://github.com/microsoft/vscode/commit/94956b4c3fb38badce912cae3d5a531502669885 | [
0.00018069404177367687,
0.00017199365538544953,
0.00016727365436963737,
0.00017240611487068236,
0.000002807244072755566
] |
{
"id": 2,
"code_window": [
"\t\treturn this._rawOutput.outputId;\n",
"\t}\n",
"\n",
"\tprivate _versionId = 0;\n",
"\n",
"\tget versionId() {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t/**\n",
"\t * Alternative output id that's reused when the output is updated.\n",
"\t */\n",
"\tprivate _alternativeOutputId: string;\n",
"\n",
"\tget alternativeOutputId(): string {\n",
"\t\treturn this._alternativeOutputId;\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/common/model/notebookCellOutputTextModel.ts",
"type": "add",
"edit_start_line_idx": 27
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as Objects from 'vs/base/common/objects';
import { IJSONSchema, IJSONSchemaMap } from 'vs/base/common/jsonSchema';
import commonSchema from './jsonSchemaCommon';
import { ProblemMatcherRegistry } from 'vs/workbench/contrib/tasks/common/problemMatcher';
import { TaskDefinitionRegistry } from './taskDefinitionRegistry';
import * as ConfigurationResolverUtils from 'vs/workbench/services/configurationResolver/common/configurationResolverUtils';
import { inputsSchema } from 'vs/workbench/services/configurationResolver/common/configurationResolverSchema';
import { getAllCodicons } from 'vs/base/common/codicons';
function fixReferences(literal: any) {
if (Array.isArray(literal)) {
literal.forEach(fixReferences);
} else if (typeof literal === 'object') {
if (literal['$ref']) {
literal['$ref'] = literal['$ref'] + '2';
}
Object.getOwnPropertyNames(literal).forEach(property => {
const value = literal[property];
if (Array.isArray(value) || typeof value === 'object') {
fixReferences(value);
}
});
}
}
const shellCommand: IJSONSchema = {
anyOf: [
{
type: 'boolean',
default: true,
description: nls.localize('JsonSchema.shell', 'Specifies whether the command is a shell command or an external program. Defaults to false if omitted.')
},
{
$ref: '#/definitions/shellConfiguration'
}
],
deprecationMessage: nls.localize('JsonSchema.tasks.isShellCommand.deprecated', 'The property isShellCommand is deprecated. Use the type property of the task and the shell property in the options instead. See also the 1.14 release notes.')
};
const hide: IJSONSchema = {
type: 'boolean',
description: nls.localize('JsonSchema.hide', 'Hide this task from the run task quick pick'),
default: true
};
const taskIdentifier: IJSONSchema = {
type: 'object',
additionalProperties: true,
properties: {
type: {
type: 'string',
description: nls.localize('JsonSchema.tasks.dependsOn.identifier', 'The task identifier.')
}
}
};
const dependsOn: IJSONSchema = {
anyOf: [
{
type: 'string',
description: nls.localize('JsonSchema.tasks.dependsOn.string', 'Another task this task depends on.')
},
taskIdentifier,
{
type: 'array',
description: nls.localize('JsonSchema.tasks.dependsOn.array', 'The other tasks this task depends on.'),
items: {
anyOf: [
{
type: 'string',
},
taskIdentifier
]
}
}
],
description: nls.localize('JsonSchema.tasks.dependsOn', 'Either a string representing another task or an array of other tasks that this task depends on.')
};
const dependsOrder: IJSONSchema = {
type: 'string',
enum: ['parallel', 'sequence'],
enumDescriptions: [
nls.localize('JsonSchema.tasks.dependsOrder.parallel', 'Run all dependsOn tasks in parallel.'),
nls.localize('JsonSchema.tasks.dependsOrder.sequence', 'Run all dependsOn tasks in sequence.'),
],
default: 'parallel',
description: nls.localize('JsonSchema.tasks.dependsOrder', 'Determines the order of the dependsOn tasks for this task. Note that this property is not recursive.')
};
const detail: IJSONSchema = {
type: 'string',
description: nls.localize('JsonSchema.tasks.detail', 'An optional description of a task that shows in the Run Task quick pick as a detail.')
};
const icon: IJSONSchema = {
type: 'object',
description: nls.localize('JsonSchema.tasks.icon', 'An optional icon for the task'),
properties: {
id: {
description: nls.localize('JsonSchema.tasks.icon.id', 'An optional codicon ID to use'),
type: ['string', 'null'],
enum: Array.from(getAllCodicons(), icon => icon.id),
markdownEnumDescriptions: Array.from(getAllCodicons(), icon => `$(${icon.id})`),
},
color: {
description: nls.localize('JsonSchema.tasks.icon.color', 'An optional color of the icon'),
type: ['string', 'null'],
enum: [
'terminal.ansiBlack',
'terminal.ansiRed',
'terminal.ansiGreen',
'terminal.ansiYellow',
'terminal.ansiBlue',
'terminal.ansiMagenta',
'terminal.ansiCyan',
'terminal.ansiWhite'
],
},
}
};
const presentation: IJSONSchema = {
type: 'object',
default: {
echo: true,
reveal: 'always',
focus: false,
panel: 'shared',
showReuseMessage: true,
clear: false,
},
description: nls.localize('JsonSchema.tasks.presentation', 'Configures the panel that is used to present the task\'s output and reads its input.'),
additionalProperties: false,
properties: {
echo: {
type: 'boolean',
default: true,
description: nls.localize('JsonSchema.tasks.presentation.echo', 'Controls whether the executed command is echoed to the panel. Default is true.')
},
focus: {
type: 'boolean',
default: false,
description: nls.localize('JsonSchema.tasks.presentation.focus', 'Controls whether the panel takes focus. Default is false. If set to true the panel is revealed as well.')
},
revealProblems: {
type: 'string',
enum: ['always', 'onProblem', 'never'],
enumDescriptions: [
nls.localize('JsonSchema.tasks.presentation.revealProblems.always', 'Always reveals the problems panel when this task is executed.'),
nls.localize('JsonSchema.tasks.presentation.revealProblems.onProblem', 'Only reveals the problems panel if a problem is found.'),
nls.localize('JsonSchema.tasks.presentation.revealProblems.never', 'Never reveals the problems panel when this task is executed.'),
],
default: 'never',
description: nls.localize('JsonSchema.tasks.presentation.revealProblems', 'Controls whether the problems panel is revealed when running this task or not. Takes precedence over option \"reveal\". Default is \"never\".')
},
reveal: {
type: 'string',
enum: ['always', 'silent', 'never'],
enumDescriptions: [
nls.localize('JsonSchema.tasks.presentation.reveal.always', 'Always reveals the terminal when this task is executed.'),
nls.localize('JsonSchema.tasks.presentation.reveal.silent', 'Only reveals the terminal if the task exits with an error or the problem matcher finds an error.'),
nls.localize('JsonSchema.tasks.presentation.reveal.never', 'Never reveals the terminal when this task is executed.'),
],
default: 'always',
description: nls.localize('JsonSchema.tasks.presentation.reveal', 'Controls whether the terminal running the task is revealed or not. May be overridden by option \"revealProblems\". Default is \"always\".')
},
panel: {
type: 'string',
enum: ['shared', 'dedicated', 'new'],
default: 'shared',
description: nls.localize('JsonSchema.tasks.presentation.instance', 'Controls if the panel is shared between tasks, dedicated to this task or a new one is created on every run.')
},
showReuseMessage: {
type: 'boolean',
default: true,
description: nls.localize('JsonSchema.tasks.presentation.showReuseMessage', 'Controls whether to show the `Terminal will be reused by tasks, press any key to close it` message.')
},
clear: {
type: 'boolean',
default: false,
description: nls.localize('JsonSchema.tasks.presentation.clear', 'Controls whether the terminal is cleared before executing the task.')
},
group: {
type: 'string',
description: nls.localize('JsonSchema.tasks.presentation.group', 'Controls whether the task is executed in a specific terminal group using split panes.')
},
close: {
type: 'boolean',
description: nls.localize('JsonSchema.tasks.presentation.close', 'Controls whether the terminal the task runs in is closed when the task exits.')
}
}
};
const terminal: IJSONSchema = Objects.deepClone(presentation);
terminal.deprecationMessage = nls.localize('JsonSchema.tasks.terminal', 'The terminal property is deprecated. Use presentation instead');
const groupStrings: IJSONSchema = {
type: 'string',
enum: [
'build',
'test',
'none'
],
enumDescriptions: [
nls.localize('JsonSchema.tasks.group.build', 'Marks the task as a build task accessible through the \'Run Build Task\' command.'),
nls.localize('JsonSchema.tasks.group.test', 'Marks the task as a test task accessible through the \'Run Test Task\' command.'),
nls.localize('JsonSchema.tasks.group.none', 'Assigns the task to no group')
],
description: nls.localize('JsonSchema.tasks.group.kind', 'The task\'s execution group.')
};
const group: IJSONSchema = {
oneOf: [
groupStrings,
{
type: 'object',
properties: {
kind: groupStrings,
isDefault: {
type: ['boolean', 'string'],
default: false,
description: nls.localize('JsonSchema.tasks.group.isDefault', 'Defines if this task is the default task in the group, or a glob to match the file which should trigger this task.')
}
}
},
],
defaultSnippets: [
{
body: { kind: 'build', isDefault: true },
description: nls.localize('JsonSchema.tasks.group.defaultBuild', 'Marks the task as the default build task.')
},
{
body: { kind: 'test', isDefault: true },
description: nls.localize('JsonSchema.tasks.group.defaultTest', 'Marks the task as the default test task.')
}
],
description: nls.localize('JsonSchema.tasks.group', 'Defines to which execution group this task belongs to. It supports "build" to add it to the build group and "test" to add it to the test group.')
};
const taskType: IJSONSchema = {
type: 'string',
enum: ['shell'],
default: 'process',
description: nls.localize('JsonSchema.tasks.type', 'Defines whether the task is run as a process or as a command inside a shell.')
};
const command: IJSONSchema = {
oneOf: [
{
oneOf: [
{
type: 'string'
},
{
type: 'array',
items: {
type: 'string'
},
description: nls.localize('JsonSchema.commandArray', 'The shell command to be executed. Array items will be joined using a space character')
}
]
},
{
type: 'object',
required: ['value', 'quoting'],
properties: {
value: {
oneOf: [
{
type: 'string'
},
{
type: 'array',
items: {
type: 'string'
},
description: nls.localize('JsonSchema.commandArray', 'The shell command to be executed. Array items will be joined using a space character')
}
],
description: nls.localize('JsonSchema.command.quotedString.value', 'The actual command value')
},
quoting: {
type: 'string',
enum: ['escape', 'strong', 'weak'],
enumDescriptions: [
nls.localize('JsonSchema.tasks.quoting.escape', 'Escapes characters using the shell\'s escape character (e.g. ` under PowerShell and \\ under bash).'),
nls.localize('JsonSchema.tasks.quoting.strong', 'Quotes the argument using the shell\'s strong quote character (e.g. \' under PowerShell and bash).'),
nls.localize('JsonSchema.tasks.quoting.weak', 'Quotes the argument using the shell\'s weak quote character (e.g. " under PowerShell and bash).'),
],
default: 'strong',
description: nls.localize('JsonSchema.command.quotesString.quote', 'How the command value should be quoted.')
}
}
}
],
description: nls.localize('JsonSchema.command', 'The command to be executed. Can be an external program or a shell command.')
};
const args: IJSONSchema = {
type: 'array',
items: {
oneOf: [
{
type: 'string',
},
{
type: 'object',
required: ['value', 'quoting'],
properties: {
value: {
type: 'string',
description: nls.localize('JsonSchema.args.quotedString.value', 'The actual argument value')
},
quoting: {
type: 'string',
enum: ['escape', 'strong', 'weak'],
enumDescriptions: [
nls.localize('JsonSchema.tasks.quoting.escape', 'Escapes characters using the shell\'s escape character (e.g. ` under PowerShell and \\ under bash).'),
nls.localize('JsonSchema.tasks.quoting.strong', 'Quotes the argument using the shell\'s strong quote character (e.g. \' under PowerShell and bash).'),
nls.localize('JsonSchema.tasks.quoting.weak', 'Quotes the argument using the shell\'s weak quote character (e.g. " under PowerShell and bash).'),
],
default: 'strong',
description: nls.localize('JsonSchema.args.quotesString.quote', 'How the argument value should be quoted.')
}
}
}
]
},
description: nls.localize('JsonSchema.tasks.args', 'Arguments passed to the command when this task is invoked.')
};
const label: IJSONSchema = {
type: 'string',
description: nls.localize('JsonSchema.tasks.label', "The task's user interface label")
};
const version: IJSONSchema = {
type: 'string',
enum: ['2.0.0'],
description: nls.localize('JsonSchema.version', 'The config\'s version number.')
};
const identifier: IJSONSchema = {
type: 'string',
description: nls.localize('JsonSchema.tasks.identifier', 'A user defined identifier to reference the task in launch.json or a dependsOn clause.'),
deprecationMessage: nls.localize('JsonSchema.tasks.identifier.deprecated', 'User defined identifiers are deprecated. For custom task use the name as a reference and for tasks provided by extensions use their defined task identifier.')
};
const runOptions: IJSONSchema = {
type: 'object',
additionalProperties: false,
properties: {
reevaluateOnRerun: {
type: 'boolean',
description: nls.localize('JsonSchema.tasks.reevaluateOnRerun', 'Whether to reevaluate task variables on rerun.'),
default: true
},
runOn: {
type: 'string',
enum: ['default', 'folderOpen'],
description: nls.localize('JsonSchema.tasks.runOn', 'Configures when the task should be run. If set to folderOpen, then the task will be run automatically when the folder is opened.'),
default: 'default'
},
instanceLimit: {
type: 'number',
description: nls.localize('JsonSchema.tasks.instanceLimit', 'The number of instances of the task that are allowed to run simultaneously.'),
default: 1
},
},
description: nls.localize('JsonSchema.tasks.runOptions', 'The task\'s run related options')
};
const commonSchemaDefinitions = commonSchema.definitions!;
const options: IJSONSchema = Objects.deepClone(commonSchemaDefinitions.options);
const optionsProperties = options.properties!;
optionsProperties.shell = Objects.deepClone(commonSchemaDefinitions.shellConfiguration);
const taskConfiguration: IJSONSchema = {
type: 'object',
additionalProperties: false,
properties: {
label: {
type: 'string',
description: nls.localize('JsonSchema.tasks.taskLabel', "The task's label")
},
taskName: {
type: 'string',
description: nls.localize('JsonSchema.tasks.taskName', 'The task\'s name'),
deprecationMessage: nls.localize('JsonSchema.tasks.taskName.deprecated', 'The task\'s name property is deprecated. Use the label property instead.')
},
identifier: Objects.deepClone(identifier),
group: Objects.deepClone(group),
isBackground: {
type: 'boolean',
description: nls.localize('JsonSchema.tasks.background', 'Whether the executed task is kept alive and is running in the background.'),
default: true
},
promptOnClose: {
type: 'boolean',
description: nls.localize('JsonSchema.tasks.promptOnClose', 'Whether the user is prompted when VS Code closes with a running task.'),
default: false
},
presentation: Objects.deepClone(presentation),
icon: Objects.deepClone(icon),
hide: Objects.deepClone(hide),
options: options,
problemMatcher: {
$ref: '#/definitions/problemMatcherType',
description: nls.localize('JsonSchema.tasks.matchers', 'The problem matcher(s) to use. Can either be a string or a problem matcher definition or an array of strings and problem matchers.')
},
runOptions: Objects.deepClone(runOptions),
dependsOn: Objects.deepClone(dependsOn),
dependsOrder: Objects.deepClone(dependsOrder),
detail: Objects.deepClone(detail),
}
};
const taskDefinitions: IJSONSchema[] = [];
TaskDefinitionRegistry.onReady().then(() => {
updateTaskDefinitions();
});
export function updateTaskDefinitions() {
for (const taskType of TaskDefinitionRegistry.all()) {
// Check that we haven't already added this task type
if (taskDefinitions.find(schema => {
return schema.properties?.type?.enum?.find ? schema.properties?.type.enum.find(element => element === taskType.taskType) : undefined;
})) {
continue;
}
const schema: IJSONSchema = Objects.deepClone(taskConfiguration);
const schemaProperties = schema.properties!;
// Since we do this after the schema is assigned we need to patch the refs.
schemaProperties.type = {
type: 'string',
description: nls.localize('JsonSchema.customizations.customizes.type', 'The task type to customize'),
enum: [taskType.taskType]
};
if (taskType.required) {
schema.required = taskType.required.slice();
} else {
schema.required = [];
}
// Customized tasks require that the task type be set.
schema.required.push('type');
if (taskType.properties) {
for (const key of Object.keys(taskType.properties)) {
const property = taskType.properties[key];
schemaProperties[key] = Objects.deepClone(property);
}
}
fixReferences(schema);
taskDefinitions.push(schema);
}
}
const customize = Objects.deepClone(taskConfiguration);
customize.properties!.customize = {
type: 'string',
deprecationMessage: nls.localize('JsonSchema.tasks.customize.deprecated', 'The customize property is deprecated. See the 1.14 release notes on how to migrate to the new task customization approach')
};
if (!customize.required) {
customize.required = [];
}
customize.required.push('customize');
taskDefinitions.push(customize);
const definitions = Objects.deepClone(commonSchemaDefinitions);
const taskDescription: IJSONSchema = definitions.taskDescription;
taskDescription.required = ['label'];
const taskDescriptionProperties = taskDescription.properties!;
taskDescriptionProperties.label = Objects.deepClone(label);
taskDescriptionProperties.command = Objects.deepClone(command);
taskDescriptionProperties.args = Objects.deepClone(args);
taskDescriptionProperties.isShellCommand = Objects.deepClone(shellCommand);
taskDescriptionProperties.dependsOn = dependsOn;
taskDescriptionProperties.hide = Objects.deepClone(hide);
taskDescriptionProperties.dependsOrder = dependsOrder;
taskDescriptionProperties.identifier = Objects.deepClone(identifier);
taskDescriptionProperties.type = Objects.deepClone(taskType);
taskDescriptionProperties.presentation = Objects.deepClone(presentation);
taskDescriptionProperties.terminal = terminal;
taskDescriptionProperties.icon = Objects.deepClone(icon);
taskDescriptionProperties.group = Objects.deepClone(group);
taskDescriptionProperties.runOptions = Objects.deepClone(runOptions);
taskDescriptionProperties.detail = detail;
taskDescriptionProperties.taskName.deprecationMessage = nls.localize(
'JsonSchema.tasks.taskName.deprecated',
'The task\'s name property is deprecated. Use the label property instead.'
);
// Clone the taskDescription for process task before setting a default to prevent two defaults #115281
const processTask = Objects.deepClone(taskDescription);
taskDescription.default = {
label: 'My Task',
type: 'shell',
command: 'echo Hello',
problemMatcher: []
};
definitions.showOutputType.deprecationMessage = nls.localize(
'JsonSchema.tasks.showOutput.deprecated',
'The property showOutput is deprecated. Use the reveal property inside the presentation property instead. See also the 1.14 release notes.'
);
taskDescriptionProperties.echoCommand.deprecationMessage = nls.localize(
'JsonSchema.tasks.echoCommand.deprecated',
'The property echoCommand is deprecated. Use the echo property inside the presentation property instead. See also the 1.14 release notes.'
);
taskDescriptionProperties.suppressTaskName.deprecationMessage = nls.localize(
'JsonSchema.tasks.suppressTaskName.deprecated',
'The property suppressTaskName is deprecated. Inline the command with its arguments into the task instead. See also the 1.14 release notes.'
);
taskDescriptionProperties.isBuildCommand.deprecationMessage = nls.localize(
'JsonSchema.tasks.isBuildCommand.deprecated',
'The property isBuildCommand is deprecated. Use the group property instead. See also the 1.14 release notes.'
);
taskDescriptionProperties.isTestCommand.deprecationMessage = nls.localize(
'JsonSchema.tasks.isTestCommand.deprecated',
'The property isTestCommand is deprecated. Use the group property instead. See also the 1.14 release notes.'
);
// Process tasks are almost identical schema-wise to shell tasks, but they are required to have a command
processTask.properties!.type = {
type: 'string',
enum: ['process'],
default: 'process',
description: nls.localize('JsonSchema.tasks.type', 'Defines whether the task is run as a process or as a command inside a shell.')
};
processTask.required!.push('command');
processTask.required!.push('type');
taskDefinitions.push(processTask);
taskDefinitions.push({
$ref: '#/definitions/taskDescription'
} as IJSONSchema);
const definitionsTaskRunnerConfigurationProperties = definitions.taskRunnerConfiguration.properties!;
const tasks = definitionsTaskRunnerConfigurationProperties.tasks;
tasks.items = {
oneOf: taskDefinitions
};
definitionsTaskRunnerConfigurationProperties.inputs = inputsSchema.definitions!.inputs;
definitions.commandConfiguration.properties!.isShellCommand = Objects.deepClone(shellCommand);
definitions.commandConfiguration.properties!.args = Objects.deepClone(args);
definitions.options.properties!.shell = {
$ref: '#/definitions/shellConfiguration'
};
definitionsTaskRunnerConfigurationProperties.isShellCommand = Objects.deepClone(shellCommand);
definitionsTaskRunnerConfigurationProperties.type = Objects.deepClone(taskType);
definitionsTaskRunnerConfigurationProperties.group = Objects.deepClone(group);
definitionsTaskRunnerConfigurationProperties.presentation = Objects.deepClone(presentation);
definitionsTaskRunnerConfigurationProperties.suppressTaskName.deprecationMessage = nls.localize(
'JsonSchema.tasks.suppressTaskName.deprecated',
'The property suppressTaskName is deprecated. Inline the command with its arguments into the task instead. See also the 1.14 release notes.'
);
definitionsTaskRunnerConfigurationProperties.taskSelector.deprecationMessage = nls.localize(
'JsonSchema.tasks.taskSelector.deprecated',
'The property taskSelector is deprecated. Inline the command with its arguments into the task instead. See also the 1.14 release notes.'
);
const osSpecificTaskRunnerConfiguration = Objects.deepClone(definitions.taskRunnerConfiguration);
delete osSpecificTaskRunnerConfiguration.properties!.tasks;
osSpecificTaskRunnerConfiguration.additionalProperties = false;
definitions.osSpecificTaskRunnerConfiguration = osSpecificTaskRunnerConfiguration;
definitionsTaskRunnerConfigurationProperties.version = Objects.deepClone(version);
const schema: IJSONSchema = {
oneOf: [
{
'allOf': [
{
type: 'object',
required: ['version'],
properties: {
version: Objects.deepClone(version),
windows: {
'$ref': '#/definitions/osSpecificTaskRunnerConfiguration',
'description': nls.localize('JsonSchema.windows', 'Windows specific command configuration')
},
osx: {
'$ref': '#/definitions/osSpecificTaskRunnerConfiguration',
'description': nls.localize('JsonSchema.mac', 'Mac specific command configuration')
},
linux: {
'$ref': '#/definitions/osSpecificTaskRunnerConfiguration',
'description': nls.localize('JsonSchema.linux', 'Linux specific command configuration')
}
}
},
{
$ref: '#/definitions/taskRunnerConfiguration'
}
]
}
]
};
schema.definitions = definitions;
function deprecatedVariableMessage(schemaMap: IJSONSchemaMap, property: string) {
const mapAtProperty = schemaMap[property].properties!;
if (mapAtProperty) {
Object.keys(mapAtProperty).forEach(name => {
deprecatedVariableMessage(mapAtProperty, name);
});
} else {
ConfigurationResolverUtils.applyDeprecatedVariableMessage(schemaMap[property]);
}
}
Object.getOwnPropertyNames(definitions).forEach(key => {
const newKey = key + '2';
definitions[newKey] = definitions[key];
delete definitions[key];
deprecatedVariableMessage(definitions, newKey);
});
fixReferences(schema);
export function updateProblemMatchers() {
try {
const matcherIds = ProblemMatcherRegistry.keys().map(key => '$' + key);
definitions.problemMatcherType2.oneOf![0].enum = matcherIds;
(definitions.problemMatcherType2.oneOf![2].items as IJSONSchema).anyOf![0].enum = matcherIds;
} catch (err) {
console.log('Installing problem matcher ids failed');
}
}
ProblemMatcherRegistry.onReady().then(() => {
updateProblemMatchers();
});
export default schema;
| src/vs/workbench/contrib/tasks/common/jsonSchema_v2.ts | 0 | https://github.com/microsoft/vscode/commit/94956b4c3fb38badce912cae3d5a531502669885 | [
0.00024409964680671692,
0.0001732890959829092,
0.00016597229114267975,
0.00017259376181755215,
0.000009226925612892956
] |
{
"id": 2,
"code_window": [
"\t\treturn this._rawOutput.outputId;\n",
"\t}\n",
"\n",
"\tprivate _versionId = 0;\n",
"\n",
"\tget versionId() {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t/**\n",
"\t * Alternative output id that's reused when the output is updated.\n",
"\t */\n",
"\tprivate _alternativeOutputId: string;\n",
"\n",
"\tget alternativeOutputId(): string {\n",
"\t\treturn this._alternativeOutputId;\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/notebook/common/model/notebookCellOutputTextModel.ts",
"type": "add",
"edit_start_line_idx": 27
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { extHostNamedCustomer } from 'vs/workbench/services/extensions/common/extHostCustomers';
import { MainContext, MainThreadClipboardShape } from '../common/extHost.protocol';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
@extHostNamedCustomer(MainContext.MainThreadClipboard)
export class MainThreadClipboard implements MainThreadClipboardShape {
constructor(
_context: any,
@IClipboardService private readonly _clipboardService: IClipboardService,
) { }
dispose(): void {
// nothing
}
$readText(): Promise<string> {
return this._clipboardService.readText();
}
$writeText(value: string): Promise<void> {
return this._clipboardService.writeText(value);
}
}
| src/vs/workbench/api/browser/mainThreadClipboard.ts | 0 | https://github.com/microsoft/vscode/commit/94956b4c3fb38badce912cae3d5a531502669885 | [
0.00017580458370503038,
0.00017256394494324923,
0.00016966664406936616,
0.0001722205925034359,
0.0000025175372684316244
] |
{
"id": 3,
"code_window": [
"\tconstructor(\n",
"\t\tprivate _rawOutput: IOutputDto\n",
"\t) {\n",
"\t\tsuper();\n",
"\t}\n",
"\n",
"\treplaceData(rawData: IOutputDto) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\t\tthis._alternativeOutputId = this._rawOutput.outputId;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/common/model/notebookCellOutputTextModel.ts",
"type": "add",
"edit_start_line_idx": 37
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { decodeBase64, encodeBase64, VSBuffer } from 'vs/base/common/buffer';
import { CancellationToken } from 'vs/base/common/cancellation';
import { IDiffResult } from 'vs/base/common/diff/diff';
import { Event } from 'vs/base/common/event';
import * as glob from 'vs/base/common/glob';
import { Iterable } from 'vs/base/common/iterator';
import { Mimes } from 'vs/base/common/mime';
import { Schemas } from 'vs/base/common/network';
import { basename } from 'vs/base/common/path';
import { isWindows } from 'vs/base/common/platform';
import { ISplice } from 'vs/base/common/sequence';
import { URI, UriComponents } from 'vs/base/common/uri';
import { ILineChange } from 'vs/editor/common/diff/smartLinesDiffComputer';
import * as editorCommon from 'vs/editor/common/editorCommon';
import { Command, WorkspaceEditMetadata } from 'vs/editor/common/languages';
import { IReadonlyTextBuffer } from 'vs/editor/common/model';
import { IAccessibilityInformation } from 'vs/platform/accessibility/common/accessibility';
import { RawContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IEditorModel } from 'vs/platform/editor/common/editor';
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
import { ThemeColor } from 'vs/base/common/themables';
import { UndoRedoGroup } from 'vs/platform/undoRedo/common/undoRedo';
import { IRevertOptions, ISaveOptions, IUntypedEditorInput } from 'vs/workbench/common/editor';
import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel';
import { ICellRange } from 'vs/workbench/contrib/notebook/common/notebookRange';
import { IWorkingCopyBackupMeta, IWorkingCopySaveEvent } from 'vs/workbench/services/workingCopy/common/workingCopy';
import { IMarkdownString } from 'vs/base/common/htmlContent';
export const NOTEBOOK_EDITOR_ID = 'workbench.editor.notebook';
export const NOTEBOOK_DIFF_EDITOR_ID = 'workbench.editor.notebookTextDiffEditor';
export const INTERACTIVE_WINDOW_EDITOR_ID = 'workbench.editor.interactive';
export enum CellKind {
Markup = 1,
Code = 2
}
export const NOTEBOOK_DISPLAY_ORDER: readonly string[] = [
'application/json',
'application/javascript',
'text/html',
'image/svg+xml',
Mimes.latex,
Mimes.markdown,
'image/png',
'image/jpeg',
Mimes.text
];
export const ACCESSIBLE_NOTEBOOK_DISPLAY_ORDER: readonly string[] = [
Mimes.latex,
Mimes.markdown,
'application/json',
'text/html',
'image/svg+xml',
'image/png',
'image/jpeg',
Mimes.text,
];
/**
* A mapping of extension IDs who contain renderers, to notebook ids who they
* should be treated as the same in the renderer selection logic. This is used
* to prefer the 1st party Jupyter renderers even though they're in a separate
* extension, for instance. See #136247.
*/
export const RENDERER_EQUIVALENT_EXTENSIONS: ReadonlyMap<string, ReadonlySet<string>> = new Map([
['ms-toolsai.jupyter', new Set(['jupyter-notebook', 'interactive'])],
['ms-toolsai.jupyter-renderers', new Set(['jupyter-notebook', 'interactive'])],
]);
export const RENDERER_NOT_AVAILABLE = '_notAvailable';
export type ContributedNotebookRendererEntrypoint = string | { readonly extends: string; readonly path: string };
export enum NotebookRunState {
Running = 1,
Idle = 2
}
export type NotebookDocumentMetadata = Record<string, unknown>;
export enum NotebookCellExecutionState {
Unconfirmed = 1,
Pending = 2,
Executing = 3
}
export enum NotebookExecutionState {
Unconfirmed = 1,
Pending = 2,
Executing = 3
}
export interface INotebookCellPreviousExecutionResult {
executionOrder?: number;
success?: boolean;
duration?: number;
}
export interface NotebookCellMetadata {
/**
* custom metadata
*/
[key: string]: unknown;
}
export interface NotebookCellInternalMetadata {
executionId?: string;
executionOrder?: number;
lastRunSuccess?: boolean;
runStartTime?: number;
runStartTimeAdjustment?: number;
runEndTime?: number;
renderDuration?: { [key: string]: number };
}
export interface NotebookCellCollapseState {
inputCollapsed?: boolean;
outputCollapsed?: boolean;
}
export interface NotebookCellDefaultCollapseConfig {
codeCell?: NotebookCellCollapseState;
markupCell?: NotebookCellCollapseState;
}
export type InteractiveWindowCollapseCodeCells = 'always' | 'never' | 'fromEditor';
export type TransientCellMetadata = { readonly [K in keyof NotebookCellMetadata]?: boolean };
export type CellContentMetadata = { readonly [K in keyof NotebookCellMetadata]?: boolean };
export type TransientDocumentMetadata = { readonly [K in keyof NotebookDocumentMetadata]?: boolean };
export interface TransientOptions {
readonly transientOutputs: boolean;
readonly transientCellMetadata: TransientCellMetadata;
readonly transientDocumentMetadata: TransientDocumentMetadata;
readonly cellContentMetadata: CellContentMetadata;
}
/** Note: enum values are used for sorting */
export const enum NotebookRendererMatch {
/** Renderer has a hard dependency on an available kernel */
WithHardKernelDependency = 0,
/** Renderer works better with an available kernel */
WithOptionalKernelDependency = 1,
/** Renderer is kernel-agnostic */
Pure = 2,
/** Renderer is for a different mimeType or has a hard dependency which is unsatisfied */
Never = 3,
}
/**
* Renderer messaging requirement. While this allows for 'optional' messaging,
* VS Code effectively treats it the same as true right now. "Partial
* activation" of extensions is a very tricky problem, which could allow
* solving this. But for now, optional is mostly only honored for aznb.
*/
export const enum RendererMessagingSpec {
Always = 'always',
Never = 'never',
Optional = 'optional',
}
export type NotebookRendererEntrypoint = { readonly extends: string | undefined; readonly path: URI };
export interface INotebookRendererInfo {
readonly id: string;
readonly displayName: string;
readonly entrypoint: NotebookRendererEntrypoint;
readonly extensionLocation: URI;
readonly extensionId: ExtensionIdentifier;
readonly messaging: RendererMessagingSpec;
readonly mimeTypes: readonly string[];
readonly isBuiltin: boolean;
matchesWithoutKernel(mimeType: string): NotebookRendererMatch;
matches(mimeType: string, kernelProvides: ReadonlyArray<string>): NotebookRendererMatch;
}
export interface INotebookStaticPreloadInfo {
readonly type: string;
readonly entrypoint: URI;
readonly extensionLocation: URI;
readonly localResourceRoots: readonly URI[];
}
export interface IOrderedMimeType {
mimeType: string;
rendererId: string;
isTrusted: boolean;
}
export interface IOutputItemDto {
readonly mime: string;
readonly data: VSBuffer;
}
export interface IOutputDto {
outputs: IOutputItemDto[];
outputId: string;
metadata?: Record<string, any>;
}
export interface ICellOutput {
readonly versionId: number;
outputs: IOutputItemDto[];
metadata?: Record<string, any>;
outputId: string;
onDidChangeData: Event<void>;
replaceData(items: IOutputDto): void;
appendData(items: IOutputItemDto[]): void;
appendedSinceVersion(versionId: number, mime: string): VSBuffer | undefined;
asDto(): IOutputDto;
bumpVersion(): void;
}
export interface CellInternalMetadataChangedEvent {
readonly lastRunSuccessChanged?: boolean;
}
export interface ICell {
readonly uri: URI;
handle: number;
language: string;
cellKind: CellKind;
outputs: ICellOutput[];
metadata: NotebookCellMetadata;
internalMetadata: NotebookCellInternalMetadata;
getHashValue(): number;
textBuffer: IReadonlyTextBuffer;
onDidChangeOutputs?: Event<NotebookCellOutputsSplice>;
onDidChangeOutputItems?: Event<void>;
onDidChangeLanguage: Event<string>;
onDidChangeMetadata: Event<void>;
onDidChangeInternalMetadata: Event<CellInternalMetadataChangedEvent>;
}
export interface INotebookTextModel {
readonly viewType: string;
metadata: NotebookDocumentMetadata;
readonly transientOptions: TransientOptions;
readonly uri: URI;
readonly versionId: number;
readonly length: number;
readonly cells: readonly ICell[];
reset(cells: ICellDto2[], metadata: NotebookDocumentMetadata, transientOptions: TransientOptions): void;
applyEdits(rawEdits: ICellEditOperation[], synchronous: boolean, beginSelectionState: ISelectionState | undefined, endSelectionsComputer: () => ISelectionState | undefined, undoRedoGroup: UndoRedoGroup | undefined, computeUndoRedo?: boolean): boolean;
onDidChangeContent: Event<NotebookTextModelChangedEvent>;
onWillDispose: Event<void>;
}
export type NotebookCellTextModelSplice<T> = [
start: number,
deleteCount: number,
newItems: T[]
];
export type NotebookCellOutputsSplice = {
start: number /* start */;
deleteCount: number /* delete count */;
newOutputs: ICellOutput[];
};
export interface IMainCellDto {
handle: number;
uri: UriComponents;
source: string[];
eol: string;
language: string;
cellKind: CellKind;
outputs: IOutputDto[];
metadata?: NotebookCellMetadata;
internalMetadata?: NotebookCellInternalMetadata;
}
export enum NotebookCellsChangeType {
ModelChange = 1,
Move = 2,
ChangeCellLanguage = 5,
Initialize = 6,
ChangeCellMetadata = 7,
Output = 8,
OutputItem = 9,
ChangeCellContent = 10,
ChangeDocumentMetadata = 11,
ChangeCellInternalMetadata = 12,
ChangeCellMime = 13,
Unknown = 100
}
export interface NotebookCellsInitializeEvent<T> {
readonly kind: NotebookCellsChangeType.Initialize;
readonly changes: NotebookCellTextModelSplice<T>[];
}
export interface NotebookCellContentChangeEvent {
readonly kind: NotebookCellsChangeType.ChangeCellContent;
readonly index: number;
}
export interface NotebookCellsModelChangedEvent<T> {
readonly kind: NotebookCellsChangeType.ModelChange;
readonly changes: NotebookCellTextModelSplice<T>[];
}
export interface NotebookCellsModelMoveEvent<T> {
readonly kind: NotebookCellsChangeType.Move;
readonly index: number;
readonly length: number;
readonly newIdx: number;
readonly cells: T[];
}
export interface NotebookOutputChangedEvent {
readonly kind: NotebookCellsChangeType.Output;
readonly index: number;
readonly outputs: IOutputDto[];
readonly append: boolean;
}
export interface NotebookOutputItemChangedEvent {
readonly kind: NotebookCellsChangeType.OutputItem;
readonly index: number;
readonly outputId: string;
readonly outputItems: IOutputItemDto[];
readonly append: boolean;
}
export interface NotebookCellsChangeLanguageEvent {
readonly kind: NotebookCellsChangeType.ChangeCellLanguage;
readonly index: number;
readonly language: string;
}
export interface NotebookCellsChangeMimeEvent {
readonly kind: NotebookCellsChangeType.ChangeCellMime;
readonly index: number;
readonly mime: string | undefined;
}
export interface NotebookCellsChangeMetadataEvent {
readonly kind: NotebookCellsChangeType.ChangeCellMetadata;
readonly index: number;
readonly metadata: NotebookCellMetadata;
}
export interface NotebookCellsChangeInternalMetadataEvent {
readonly kind: NotebookCellsChangeType.ChangeCellInternalMetadata;
readonly index: number;
readonly internalMetadata: NotebookCellInternalMetadata;
}
export interface NotebookDocumentChangeMetadataEvent {
readonly kind: NotebookCellsChangeType.ChangeDocumentMetadata;
readonly metadata: NotebookDocumentMetadata;
}
export interface NotebookDocumentUnknownChangeEvent {
readonly kind: NotebookCellsChangeType.Unknown;
}
export type NotebookRawContentEventDto = NotebookCellsInitializeEvent<IMainCellDto> | NotebookDocumentChangeMetadataEvent | NotebookCellContentChangeEvent | NotebookCellsModelChangedEvent<IMainCellDto> | NotebookCellsModelMoveEvent<IMainCellDto> | NotebookOutputChangedEvent | NotebookOutputItemChangedEvent | NotebookCellsChangeLanguageEvent | NotebookCellsChangeMimeEvent | NotebookCellsChangeMetadataEvent | NotebookCellsChangeInternalMetadataEvent | NotebookDocumentUnknownChangeEvent;
export type NotebookCellsChangedEventDto = {
readonly rawEvents: NotebookRawContentEventDto[];
readonly versionId: number;
};
export type NotebookRawContentEvent = (NotebookCellsInitializeEvent<ICell> | NotebookDocumentChangeMetadataEvent | NotebookCellContentChangeEvent | NotebookCellsModelChangedEvent<ICell> | NotebookCellsModelMoveEvent<ICell> | NotebookOutputChangedEvent | NotebookOutputItemChangedEvent | NotebookCellsChangeLanguageEvent | NotebookCellsChangeMimeEvent | NotebookCellsChangeMetadataEvent | NotebookCellsChangeInternalMetadataEvent | NotebookDocumentUnknownChangeEvent) & { transient: boolean };
export enum SelectionStateType {
Handle = 0,
Index = 1
}
export interface ISelectionHandleState {
kind: SelectionStateType.Handle;
primary: number | null;
selections: number[];
}
export interface ISelectionIndexState {
kind: SelectionStateType.Index;
focus: ICellRange;
selections: ICellRange[];
}
export type ISelectionState = ISelectionHandleState | ISelectionIndexState;
export type NotebookTextModelChangedEvent = {
readonly rawEvents: NotebookRawContentEvent[];
readonly versionId: number;
readonly synchronous: boolean | undefined;
readonly endSelectionState: ISelectionState | undefined;
};
export type NotebookTextModelWillAddRemoveEvent = {
readonly rawEvent: NotebookCellsModelChangedEvent<ICell>;
};
export const enum CellEditType {
Replace = 1,
Output = 2,
Metadata = 3,
CellLanguage = 4,
DocumentMetadata = 5,
Move = 6,
OutputItems = 7,
PartialMetadata = 8,
PartialInternalMetadata = 9,
}
export interface ICellDto2 {
source: string;
language: string;
mime: string | undefined;
cellKind: CellKind;
outputs: IOutputDto[];
metadata?: NotebookCellMetadata;
internalMetadata?: NotebookCellInternalMetadata;
collapseState?: NotebookCellCollapseState;
}
export interface ICellReplaceEdit {
editType: CellEditType.Replace;
index: number;
count: number;
cells: ICellDto2[];
}
export interface ICellOutputEdit {
editType: CellEditType.Output;
index: number;
outputs: IOutputDto[];
append?: boolean;
}
export interface ICellOutputEditByHandle {
editType: CellEditType.Output;
handle: number;
outputs: IOutputDto[];
append?: boolean;
}
export interface ICellOutputItemEdit {
editType: CellEditType.OutputItems;
outputId: string;
items: IOutputItemDto[];
append?: boolean;
}
export interface ICellMetadataEdit {
editType: CellEditType.Metadata;
index: number;
metadata: NotebookCellMetadata;
}
// These types are nullable because we need to use 'null' on the EH side so it is JSON-stringified
export type NullablePartialNotebookCellMetadata = {
[Key in keyof Partial<NotebookCellMetadata>]: NotebookCellMetadata[Key] | null
};
export interface ICellPartialMetadataEdit {
editType: CellEditType.PartialMetadata;
index: number;
metadata: NullablePartialNotebookCellMetadata;
}
export interface ICellPartialMetadataEditByHandle {
editType: CellEditType.PartialMetadata;
handle: number;
metadata: NullablePartialNotebookCellMetadata;
}
export type NullablePartialNotebookCellInternalMetadata = {
[Key in keyof Partial<NotebookCellInternalMetadata>]: NotebookCellInternalMetadata[Key] | null
};
export interface ICellPartialInternalMetadataEdit {
editType: CellEditType.PartialInternalMetadata;
index: number;
internalMetadata: NullablePartialNotebookCellInternalMetadata;
}
export interface ICellPartialInternalMetadataEditByHandle {
editType: CellEditType.PartialInternalMetadata;
handle: number;
internalMetadata: NullablePartialNotebookCellInternalMetadata;
}
export interface ICellLanguageEdit {
editType: CellEditType.CellLanguage;
index: number;
language: string;
}
export interface IDocumentMetadataEdit {
editType: CellEditType.DocumentMetadata;
metadata: NotebookDocumentMetadata;
}
export interface ICellMoveEdit {
editType: CellEditType.Move;
index: number;
length: number;
newIdx: number;
}
export type IImmediateCellEditOperation = ICellOutputEditByHandle | ICellPartialMetadataEditByHandle | ICellOutputItemEdit | ICellPartialInternalMetadataEdit | ICellPartialInternalMetadataEditByHandle | ICellPartialMetadataEdit;
export type ICellEditOperation = IImmediateCellEditOperation | ICellReplaceEdit | ICellOutputEdit | ICellMetadataEdit | ICellPartialMetadataEdit | ICellPartialInternalMetadataEdit | IDocumentMetadataEdit | ICellMoveEdit | ICellOutputItemEdit | ICellLanguageEdit;
export interface IWorkspaceNotebookCellEdit {
metadata?: WorkspaceEditMetadata;
resource: URI;
notebookVersionId: number | undefined;
cellEdit: ICellPartialMetadataEdit | IDocumentMetadataEdit | ICellReplaceEdit;
}
export interface NotebookData {
readonly cells: ICellDto2[];
readonly metadata: NotebookDocumentMetadata;
}
export interface INotebookContributionData {
extension?: ExtensionIdentifier;
providerDisplayName: string;
displayName: string;
filenamePattern: (string | glob.IRelativePattern | INotebookExclusiveDocumentFilter)[];
exclusive: boolean;
}
export namespace CellUri {
export const scheme = Schemas.vscodeNotebookCell;
const _lengths = ['W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f'];
const _padRegexp = new RegExp(`^[${_lengths.join('')}]+`);
const _radix = 7;
export function generate(notebook: URI, handle: number): URI {
const s = handle.toString(_radix);
const p = s.length < _lengths.length ? _lengths[s.length - 1] : 'z';
const fragment = `${p}${s}s${encodeBase64(VSBuffer.fromString(notebook.scheme), true, true)}`;
return notebook.with({ scheme, fragment });
}
export function parse(cell: URI): { notebook: URI; handle: number } | undefined {
if (cell.scheme !== scheme) {
return undefined;
}
const idx = cell.fragment.indexOf('s');
if (idx < 0) {
return undefined;
}
const handle = parseInt(cell.fragment.substring(0, idx).replace(_padRegexp, ''), _radix);
const _scheme = decodeBase64(cell.fragment.substring(idx + 1)).toString();
if (isNaN(handle)) {
return undefined;
}
return {
handle,
notebook: cell.with({ scheme: _scheme, fragment: null })
};
}
export function generateCellOutputUri(notebook: URI, outputId?: string) {
return notebook.with({
scheme: Schemas.vscodeNotebookCellOutput,
fragment: `op${outputId ?? ''},${notebook.scheme !== Schemas.file ? notebook.scheme : ''}`
});
}
export function parseCellOutputUri(uri: URI): { notebook: URI; outputId?: string } | undefined {
if (uri.scheme !== Schemas.vscodeNotebookCellOutput) {
return;
}
const match = /^op([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})?\,(.*)$/i.exec(uri.fragment);
if (!match) {
return undefined;
}
const outputId = (match[1] && match[1] !== '') ? match[1] : undefined;
const scheme = match[2];
return {
outputId,
notebook: uri.with({
scheme: scheme || Schemas.file,
fragment: null
})
};
}
export function generateCellPropertyUri(notebook: URI, handle: number, scheme: string): URI {
return CellUri.generate(notebook, handle).with({ scheme: scheme });
}
export function parseCellPropertyUri(uri: URI, propertyScheme: string) {
if (uri.scheme !== propertyScheme) {
return undefined;
}
return CellUri.parse(uri.with({ scheme: scheme }));
}
}
const normalizeSlashes = (str: string) => isWindows ? str.replace(/\//g, '\\') : str;
interface IMimeTypeWithMatcher {
pattern: string;
matches: glob.ParsedPattern;
}
export class MimeTypeDisplayOrder {
private readonly order: IMimeTypeWithMatcher[];
constructor(
initialValue: readonly string[] = [],
private readonly defaultOrder = NOTEBOOK_DISPLAY_ORDER,
) {
this.order = [...new Set(initialValue)].map(pattern => ({
pattern,
matches: glob.parse(normalizeSlashes(pattern))
}));
}
/**
* Returns a sorted array of the input mimetypes.
*/
public sort(mimetypes: Iterable<string>): string[] {
const remaining = new Map(Iterable.map(mimetypes, m => [m, normalizeSlashes(m)]));
let sorted: string[] = [];
for (const { matches } of this.order) {
for (const [original, normalized] of remaining) {
if (matches(normalized)) {
sorted.push(original);
remaining.delete(original);
break;
}
}
}
if (remaining.size) {
sorted = sorted.concat([...remaining.keys()].sort(
(a, b) => this.defaultOrder.indexOf(a) - this.defaultOrder.indexOf(b),
));
}
return sorted;
}
/**
* Records that the user selected the given mimetype over the other
* possible mimetypes, prioritizing it for future reference.
*/
public prioritize(chosenMimetype: string, otherMimetypes: readonly string[]) {
const chosenIndex = this.findIndex(chosenMimetype);
if (chosenIndex === -1) {
// always first, nothing more to do
this.order.unshift({ pattern: chosenMimetype, matches: glob.parse(normalizeSlashes(chosenMimetype)) });
return;
}
// Get the other mimetypes that are before the chosenMimetype. Then, move
// them after it, retaining order.
const uniqueIndicies = new Set(otherMimetypes.map(m => this.findIndex(m, chosenIndex)));
uniqueIndicies.delete(-1);
const otherIndices = Array.from(uniqueIndicies).sort();
this.order.splice(chosenIndex + 1, 0, ...otherIndices.map(i => this.order[i]));
for (let oi = otherIndices.length - 1; oi >= 0; oi--) {
this.order.splice(otherIndices[oi], 1);
}
}
/**
* Gets an array of in-order mimetype preferences.
*/
public toArray() {
return this.order.map(o => o.pattern);
}
private findIndex(mimeType: string, maxIndex = this.order.length) {
const normalized = normalizeSlashes(mimeType);
for (let i = 0; i < maxIndex; i++) {
if (this.order[i].matches(normalized)) {
return i;
}
}
return -1;
}
}
interface IMutableSplice<T> extends ISplice<T> {
readonly toInsert: T[];
deleteCount: number;
}
export function diff<T>(before: T[], after: T[], contains: (a: T) => boolean, equal: (a: T, b: T) => boolean = (a: T, b: T) => a === b): ISplice<T>[] {
const result: IMutableSplice<T>[] = [];
function pushSplice(start: number, deleteCount: number, toInsert: T[]): void {
if (deleteCount === 0 && toInsert.length === 0) {
return;
}
const latest = result[result.length - 1];
if (latest && latest.start + latest.deleteCount === start) {
latest.deleteCount += deleteCount;
latest.toInsert.push(...toInsert);
} else {
result.push({ start, deleteCount, toInsert });
}
}
let beforeIdx = 0;
let afterIdx = 0;
while (true) {
if (beforeIdx === before.length) {
pushSplice(beforeIdx, 0, after.slice(afterIdx));
break;
}
if (afterIdx === after.length) {
pushSplice(beforeIdx, before.length - beforeIdx, []);
break;
}
const beforeElement = before[beforeIdx];
const afterElement = after[afterIdx];
if (equal(beforeElement, afterElement)) {
// equal
beforeIdx += 1;
afterIdx += 1;
continue;
}
if (contains(afterElement)) {
// `afterElement` exists before, which means some elements before `afterElement` are deleted
pushSplice(beforeIdx, 1, []);
beforeIdx += 1;
} else {
// `afterElement` added
pushSplice(beforeIdx, 0, [afterElement]);
afterIdx += 1;
}
}
return result;
}
export interface ICellEditorViewState {
selections: editorCommon.ICursorState[];
}
export const NOTEBOOK_EDITOR_CURSOR_BOUNDARY = new RawContextKey<'none' | 'top' | 'bottom' | 'both'>('notebookEditorCursorAtBoundary', 'none');
export interface INotebookLoadOptions {
/**
* Go to disk bypassing any cache of the model if any.
*/
forceReadFromFile?: boolean;
}
export interface IResolvedNotebookEditorModel extends INotebookEditorModel {
notebook: NotebookTextModel;
}
export interface INotebookEditorModel extends IEditorModel {
readonly onDidChangeDirty: Event<void>;
readonly onDidSave: Event<IWorkingCopySaveEvent>;
readonly onDidChangeOrphaned: Event<void>;
readonly onDidChangeReadonly: Event<void>;
readonly onDidRevertUntitled: Event<void>;
readonly resource: URI;
readonly viewType: string;
readonly notebook: INotebookTextModel | undefined;
readonly hasErrorState: boolean;
isResolved(): this is IResolvedNotebookEditorModel;
isDirty(): boolean;
isModified(): boolean;
isReadonly(): boolean | IMarkdownString;
isOrphaned(): boolean;
hasAssociatedFilePath(): boolean;
load(options?: INotebookLoadOptions): Promise<IResolvedNotebookEditorModel>;
save(options?: ISaveOptions): Promise<boolean>;
saveAs(target: URI): Promise<IUntypedEditorInput | undefined>;
revert(options?: IRevertOptions): Promise<void>;
}
export interface INotebookDiffEditorModel extends IEditorModel {
original: IResolvedNotebookEditorModel;
modified: IResolvedNotebookEditorModel;
}
export interface NotebookDocumentBackupData extends IWorkingCopyBackupMeta {
readonly viewType: string;
readonly backupId?: string;
readonly mtime?: number;
}
export enum NotebookEditorPriority {
default = 'default',
option = 'option',
}
export interface INotebookSearchOptions {
regex?: boolean;
wholeWord?: boolean;
caseSensitive?: boolean;
wordSeparators?: string;
includeMarkupInput?: boolean;
includeMarkupPreview?: boolean;
includeCodeInput?: boolean;
includeOutput?: boolean;
}
export interface INotebookExclusiveDocumentFilter {
include?: string | glob.IRelativePattern;
exclude?: string | glob.IRelativePattern;
}
export interface INotebookDocumentFilter {
viewType?: string | string[];
filenamePattern?: string | glob.IRelativePattern | INotebookExclusiveDocumentFilter;
}
//TODO@rebornix test
export function isDocumentExcludePattern(filenamePattern: string | glob.IRelativePattern | INotebookExclusiveDocumentFilter): filenamePattern is { include: string | glob.IRelativePattern; exclude: string | glob.IRelativePattern } {
const arg = filenamePattern as INotebookExclusiveDocumentFilter;
if ((typeof arg.include === 'string' || glob.isRelativePattern(arg.include))
&& (typeof arg.exclude === 'string' || glob.isRelativePattern(arg.exclude))) {
return true;
}
return false;
}
export function notebookDocumentFilterMatch(filter: INotebookDocumentFilter, viewType: string, resource: URI): boolean {
if (Array.isArray(filter.viewType) && filter.viewType.indexOf(viewType) >= 0) {
return true;
}
if (filter.viewType === viewType) {
return true;
}
if (filter.filenamePattern) {
const filenamePattern = isDocumentExcludePattern(filter.filenamePattern) ? filter.filenamePattern.include : (filter.filenamePattern as string | glob.IRelativePattern);
const excludeFilenamePattern = isDocumentExcludePattern(filter.filenamePattern) ? filter.filenamePattern.exclude : undefined;
if (glob.match(filenamePattern, basename(resource.fsPath).toLowerCase())) {
if (excludeFilenamePattern) {
if (glob.match(excludeFilenamePattern, basename(resource.fsPath).toLowerCase())) {
// should exclude
return false;
}
}
return true;
}
}
return false;
}
export interface INotebookCellStatusBarItemProvider {
viewType: string;
onDidChangeStatusBarItems?: Event<void>;
provideCellStatusBarItems(uri: URI, index: number, token: CancellationToken): Promise<INotebookCellStatusBarItemList | undefined>;
}
export interface INotebookDiffResult {
cellsDiff: IDiffResult;
linesDiff?: { originalCellhandle: number; modifiedCellhandle: number; lineChanges: ILineChange[] }[];
}
export interface INotebookCellStatusBarItem {
readonly alignment: CellStatusbarAlignment;
readonly priority?: number;
readonly text: string;
readonly color?: string | ThemeColor;
readonly backgroundColor?: string | ThemeColor;
readonly tooltip?: string | IMarkdownString;
readonly command?: string | Command;
readonly accessibilityInformation?: IAccessibilityInformation;
readonly opacity?: string;
readonly onlyShowWhenActive?: boolean;
}
export interface INotebookCellStatusBarItemList {
items: INotebookCellStatusBarItem[];
dispose?(): void;
}
export type ShowCellStatusBarType = 'hidden' | 'visible' | 'visibleAfterExecute';
export const NotebookSetting = {
displayOrder: 'notebook.displayOrder',
cellToolbarLocation: 'notebook.cellToolbarLocation',
cellToolbarVisibility: 'notebook.cellToolbarVisibility',
showCellStatusBar: 'notebook.showCellStatusBar',
textDiffEditorPreview: 'notebook.diff.enablePreview',
diffOverviewRuler: 'notebook.diff.overviewRuler',
experimentalInsertToolbarAlignment: 'notebook.experimental.insertToolbarAlignment',
compactView: 'notebook.compactView',
focusIndicator: 'notebook.cellFocusIndicator',
insertToolbarLocation: 'notebook.insertToolbarLocation',
globalToolbar: 'notebook.globalToolbar',
stickyScroll: 'notebook.stickyScroll.enabled',
undoRedoPerCell: 'notebook.undoRedoPerCell',
consolidatedOutputButton: 'notebook.consolidatedOutputButton',
showFoldingControls: 'notebook.showFoldingControls',
dragAndDropEnabled: 'notebook.dragAndDropEnabled',
cellEditorOptionsCustomizations: 'notebook.editorOptionsCustomizations',
consolidatedRunButton: 'notebook.consolidatedRunButton',
openGettingStarted: 'notebook.experimental.openGettingStarted',
globalToolbarShowLabel: 'notebook.globalToolbarShowLabel',
markupFontSize: 'notebook.markup.fontSize',
interactiveWindowCollapseCodeCells: 'interactiveWindow.collapseCellInputCode',
outputScrollingDeprecated: 'notebook.experimental.outputScrolling',
outputScrolling: 'notebook.output.scrolling',
textOutputLineLimit: 'notebook.output.textLineLimit',
formatOnSave: 'notebook.formatOnSave.enabled',
formatOnCellExecution: 'notebook.formatOnCellExecution',
codeActionsOnSave: 'notebook.codeActionsOnSave',
outputWordWrap: 'notebook.output.wordWrap',
outputLineHeightDeprecated: 'notebook.outputLineHeight',
outputLineHeight: 'notebook.output.lineHeight',
outputFontSizeDeprecated: 'notebook.outputFontSize',
outputFontSize: 'notebook.output.fontSize',
outputFontFamilyDeprecated: 'notebook.outputFontFamily',
outputFontFamily: 'notebook.output.fontFamily',
findScope: 'notebook.find.scope',
logging: 'notebook.logging',
confirmDeleteRunningCell: 'notebook.confirmDeleteRunningCell',
remoteSaving: 'notebook.experimental.remoteSave'
} as const;
export const enum CellStatusbarAlignment {
Left = 1,
Right = 2
}
export class NotebookWorkingCopyTypeIdentifier {
private static _prefix = 'notebook/';
static create(viewType: string): string {
return `${NotebookWorkingCopyTypeIdentifier._prefix}${viewType}`;
}
static parse(candidate: string): string | undefined {
if (candidate.startsWith(NotebookWorkingCopyTypeIdentifier._prefix)) {
return candidate.substring(NotebookWorkingCopyTypeIdentifier._prefix.length);
}
return undefined;
}
}
export interface NotebookExtensionDescription {
readonly id: ExtensionIdentifier;
readonly location: UriComponents | undefined;
}
/**
* Whether the provided mime type is a text stream like `stdout`, `stderr`.
*/
export function isTextStreamMime(mimeType: string) {
return ['application/vnd.code.notebook.stdout', 'application/vnd.code.notebook.stderr'].includes(mimeType);
}
const textDecoder = new TextDecoder();
/**
* Given a stream of individual stdout outputs, this function will return the compressed lines, escaping some of the common terminal escape codes.
* E.g. some terminal escape codes would result in the previous line getting cleared, such if we had 3 lines and
* last line contained such a code, then the result string would be just the first two lines.
* @returns a single VSBuffer with the concatenated and compressed data, and whether any compression was done.
*/
export function compressOutputItemStreams(outputs: Uint8Array[]) {
const buffers: Uint8Array[] = [];
let startAppending = false;
// Pick the first set of outputs with the same mime type.
for (const output of outputs) {
if ((buffers.length === 0 || startAppending)) {
buffers.push(output);
startAppending = true;
}
}
let didCompression = compressStreamBuffer(buffers);
const concatenated = VSBuffer.concat(buffers.map(buffer => VSBuffer.wrap(buffer)));
const data = formatStreamText(concatenated);
didCompression = didCompression || data.byteLength !== concatenated.byteLength;
return { data, didCompression };
}
export const MOVE_CURSOR_1_LINE_COMMAND = `${String.fromCharCode(27)}[A`;
const MOVE_CURSOR_1_LINE_COMMAND_BYTES = MOVE_CURSOR_1_LINE_COMMAND.split('').map(c => c.charCodeAt(0));
const LINE_FEED = 10;
function compressStreamBuffer(streams: Uint8Array[]) {
let didCompress = false;
streams.forEach((stream, index) => {
if (index === 0 || stream.length < MOVE_CURSOR_1_LINE_COMMAND.length) {
return;
}
const previousStream = streams[index - 1];
// Remove the previous line if required.
const command = stream.subarray(0, MOVE_CURSOR_1_LINE_COMMAND.length);
if (command[0] === MOVE_CURSOR_1_LINE_COMMAND_BYTES[0] && command[1] === MOVE_CURSOR_1_LINE_COMMAND_BYTES[1] && command[2] === MOVE_CURSOR_1_LINE_COMMAND_BYTES[2]) {
const lastIndexOfLineFeed = previousStream.lastIndexOf(LINE_FEED);
if (lastIndexOfLineFeed === -1) {
return;
}
didCompress = true;
streams[index - 1] = previousStream.subarray(0, lastIndexOfLineFeed);
streams[index] = stream.subarray(MOVE_CURSOR_1_LINE_COMMAND.length);
}
});
return didCompress;
}
/**
* Took this from jupyter/notebook
* https://github.com/jupyter/notebook/blob/b8b66332e2023e83d2ee04f83d8814f567e01a4e/notebook/static/base/js/utils.js
* Remove characters that are overridden by backspace characters
*/
function fixBackspace(txt: string) {
let tmp = txt;
do {
txt = tmp;
// Cancel out anything-but-newline followed by backspace
tmp = txt.replace(/[^\n]\x08/gm, '');
} while (tmp.length < txt.length);
return txt;
}
/**
* Remove chunks that should be overridden by the effect of carriage return characters
* From https://github.com/jupyter/notebook/blob/master/notebook/static/base/js/utils.js
*/
function fixCarriageReturn(txt: string) {
txt = txt.replace(/\r+\n/gm, '\n'); // \r followed by \n --> newline
while (txt.search(/\r[^$]/g) > -1) {
const base = txt.match(/^(.*)\r+/m)![1];
let insert = txt.match(/\r+(.*)$/m)![1];
insert = insert + base.slice(insert.length, base.length);
txt = txt.replace(/\r+.*$/m, '\r').replace(/^.*\r/m, insert);
}
return txt;
}
const BACKSPACE_CHARACTER = '\b'.charCodeAt(0);
const CARRIAGE_RETURN_CHARACTER = '\r'.charCodeAt(0);
function formatStreamText(buffer: VSBuffer): VSBuffer {
// We have special handling for backspace and carriage return characters.
// Don't unnecessary decode the bytes if we don't need to perform any processing.
if (!buffer.buffer.includes(BACKSPACE_CHARACTER) && !buffer.buffer.includes(CARRIAGE_RETURN_CHARACTER)) {
return buffer;
}
// Do the same thing jupyter is doing
return VSBuffer.fromString(fixCarriageReturn(fixBackspace(textDecoder.decode(buffer.buffer))));
}
export interface INotebookKernelSourceAction {
readonly label: string;
readonly description?: string;
readonly detail?: string;
readonly command?: string | Command;
readonly documentation?: UriComponents | string;
}
| src/vs/workbench/contrib/notebook/common/notebookCommon.ts | 1 | https://github.com/microsoft/vscode/commit/94956b4c3fb38badce912cae3d5a531502669885 | [
0.018757622689008713,
0.0004823373747058213,
0.00016181249520741403,
0.00017179154383484274,
0.0018410416087135673
] |
{
"id": 3,
"code_window": [
"\tconstructor(\n",
"\t\tprivate _rawOutput: IOutputDto\n",
"\t) {\n",
"\t\tsuper();\n",
"\t}\n",
"\n",
"\treplaceData(rawData: IOutputDto) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\t\tthis._alternativeOutputId = this._rawOutput.outputId;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/common/model/notebookCellOutputTextModel.ts",
"type": "add",
"edit_start_line_idx": 37
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as path from 'path';
import * as testRunner from '../../../../test/integration/electron/testrunner';
const options: import('mocha').MochaOptions = {
ui: 'tdd',
color: true,
timeout: 60000
};
// These integration tests is being run in multiple environments (electron, web, remote)
// so we need to set the suite name based on the environment as the suite name is used
// for the test results file name
let suite = '';
if (process.env.VSCODE_BROWSER) {
suite = `${process.env.VSCODE_BROWSER} Browser Integration notebook output renderer Tests`;
} else if (process.env.REMOTE_VSCODE) {
suite = 'Remote Integration notebook output renderer Tests';
} else {
suite = 'Integration notebook output renderer Tests';
}
if (process.env.BUILD_ARTIFACTSTAGINGDIRECTORY) {
options.reporter = 'mocha-multi-reporters';
options.reporterOptions = {
reporterEnabled: 'spec, mocha-junit-reporter',
mochaJunitReporterReporterOptions: {
testsuitesTitle: `${suite} ${process.platform}`,
mochaFile: path.join(process.env.BUILD_ARTIFACTSTAGINGDIRECTORY, `test-results/${process.platform}-${process.arch}-${suite.toLowerCase().replace(/[^\w]/g, '-')}-results.xml`)
}
};
}
testRunner.configure(options);
export = testRunner;
| extensions/notebook-renderers/src/test/index.ts | 0 | https://github.com/microsoft/vscode/commit/94956b4c3fb38badce912cae3d5a531502669885 | [
0.00017803093942347914,
0.00017261106404475868,
0.00016728276386857033,
0.00017179515270981938,
0.000003874108188028913
] |
{
"id": 3,
"code_window": [
"\tconstructor(\n",
"\t\tprivate _rawOutput: IOutputDto\n",
"\t) {\n",
"\t\tsuper();\n",
"\t}\n",
"\n",
"\treplaceData(rawData: IOutputDto) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\t\tthis._alternativeOutputId = this._rawOutput.outputId;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/common/model/notebookCellOutputTextModel.ts",
"type": "add",
"edit_start_line_idx": 37
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Codicon } from 'vs/base/common/codicons';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { IModelDecorationOptions, IModelDecorationsChangeAccessor, MinimapPosition, TrackedRangeStickiness } from 'vs/editor/common/model';
import { ModelDecorationOptions } from 'vs/editor/common/model/textModel';
import { IDecorationProvider } from 'vs/editor/contrib/folding/browser/foldingModel';
import { localize } from 'vs/nls';
import { editorSelectionBackground, iconForeground, registerColor, transparent } from 'vs/platform/theme/common/colorRegistry';
import { registerIcon } from 'vs/platform/theme/common/iconRegistry';
import { themeColorFromId } from 'vs/platform/theme/common/themeService';
import { ThemeIcon } from 'vs/base/common/themables';
const foldBackground = registerColor('editor.foldBackground', { light: transparent(editorSelectionBackground, 0.3), dark: transparent(editorSelectionBackground, 0.3), hcDark: null, hcLight: null }, localize('foldBackgroundBackground', "Background color behind folded ranges. The color must not be opaque so as not to hide underlying decorations."), true);
registerColor('editorGutter.foldingControlForeground', { dark: iconForeground, light: iconForeground, hcDark: iconForeground, hcLight: iconForeground }, localize('editorGutter.foldingControlForeground', 'Color of the folding control in the editor gutter.'));
export const foldingExpandedIcon = registerIcon('folding-expanded', Codicon.chevronDown, localize('foldingExpandedIcon', 'Icon for expanded ranges in the editor glyph margin.'));
export const foldingCollapsedIcon = registerIcon('folding-collapsed', Codicon.chevronRight, localize('foldingCollapsedIcon', 'Icon for collapsed ranges in the editor glyph margin.'));
export const foldingManualCollapsedIcon = registerIcon('folding-manual-collapsed', foldingCollapsedIcon, localize('foldingManualCollapedIcon', 'Icon for manually collapsed ranges in the editor glyph margin.'));
export const foldingManualExpandedIcon = registerIcon('folding-manual-expanded', foldingExpandedIcon, localize('foldingManualExpandedIcon', 'Icon for manually expanded ranges in the editor glyph margin.'));
const foldedBackgroundMinimap = { color: themeColorFromId(foldBackground), position: MinimapPosition.Inline };
export class FoldingDecorationProvider implements IDecorationProvider {
private static readonly COLLAPSED_VISUAL_DECORATION = ModelDecorationOptions.register({
description: 'folding-collapsed-visual-decoration',
stickiness: TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges,
afterContentClassName: 'inline-folded',
isWholeLine: true,
firstLineDecorationClassName: ThemeIcon.asClassName(foldingCollapsedIcon),
});
private static readonly COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION = ModelDecorationOptions.register({
description: 'folding-collapsed-highlighted-visual-decoration',
stickiness: TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges,
afterContentClassName: 'inline-folded',
className: 'folded-background',
minimap: foldedBackgroundMinimap,
isWholeLine: true,
firstLineDecorationClassName: ThemeIcon.asClassName(foldingCollapsedIcon)
});
private static readonly MANUALLY_COLLAPSED_VISUAL_DECORATION = ModelDecorationOptions.register({
description: 'folding-manually-collapsed-visual-decoration',
stickiness: TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges,
afterContentClassName: 'inline-folded',
isWholeLine: true,
firstLineDecorationClassName: ThemeIcon.asClassName(foldingManualCollapsedIcon)
});
private static readonly MANUALLY_COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION = ModelDecorationOptions.register({
description: 'folding-manually-collapsed-highlighted-visual-decoration',
stickiness: TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges,
afterContentClassName: 'inline-folded',
className: 'folded-background',
minimap: foldedBackgroundMinimap,
isWholeLine: true,
firstLineDecorationClassName: ThemeIcon.asClassName(foldingManualCollapsedIcon)
});
private static readonly NO_CONTROLS_COLLAPSED_RANGE_DECORATION = ModelDecorationOptions.register({
description: 'folding-no-controls-range-decoration',
stickiness: TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges,
afterContentClassName: 'inline-folded',
isWholeLine: true
});
private static readonly NO_CONTROLS_COLLAPSED_HIGHLIGHTED_RANGE_DECORATION = ModelDecorationOptions.register({
description: 'folding-no-controls-range-decoration',
stickiness: TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges,
afterContentClassName: 'inline-folded',
className: 'folded-background',
minimap: foldedBackgroundMinimap,
isWholeLine: true
});
private static readonly EXPANDED_VISUAL_DECORATION = ModelDecorationOptions.register({
description: 'folding-expanded-visual-decoration',
stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
isWholeLine: true,
firstLineDecorationClassName: 'alwaysShowFoldIcons ' + ThemeIcon.asClassName(foldingExpandedIcon)
});
private static readonly EXPANDED_AUTO_HIDE_VISUAL_DECORATION = ModelDecorationOptions.register({
description: 'folding-expanded-auto-hide-visual-decoration',
stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
isWholeLine: true,
firstLineDecorationClassName: ThemeIcon.asClassName(foldingExpandedIcon)
});
private static readonly MANUALLY_EXPANDED_VISUAL_DECORATION = ModelDecorationOptions.register({
description: 'folding-manually-expanded-visual-decoration',
stickiness: TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges,
isWholeLine: true,
firstLineDecorationClassName: 'alwaysShowFoldIcons ' + ThemeIcon.asClassName(foldingManualExpandedIcon)
});
private static readonly MANUALLY_EXPANDED_AUTO_HIDE_VISUAL_DECORATION = ModelDecorationOptions.register({
description: 'folding-manually-expanded-auto-hide-visual-decoration',
stickiness: TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges,
isWholeLine: true,
firstLineDecorationClassName: ThemeIcon.asClassName(foldingManualExpandedIcon)
});
private static readonly NO_CONTROLS_EXPANDED_RANGE_DECORATION = ModelDecorationOptions.register({
description: 'folding-no-controls-range-decoration',
stickiness: TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges,
isWholeLine: true
});
private static readonly HIDDEN_RANGE_DECORATION = ModelDecorationOptions.register({
description: 'folding-hidden-range-decoration',
stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges
});
public showFoldingControls: 'always' | 'never' | 'mouseover' = 'mouseover';
public showFoldingHighlights: boolean = true;
constructor(private readonly editor: ICodeEditor) {
}
getDecorationOption(isCollapsed: boolean, isHidden: boolean, isManual: boolean): IModelDecorationOptions {
if (isHidden) { // is inside another collapsed region
return FoldingDecorationProvider.HIDDEN_RANGE_DECORATION;
}
if (this.showFoldingControls === 'never') {
if (isCollapsed) {
return this.showFoldingHighlights ? FoldingDecorationProvider.NO_CONTROLS_COLLAPSED_HIGHLIGHTED_RANGE_DECORATION : FoldingDecorationProvider.NO_CONTROLS_COLLAPSED_RANGE_DECORATION;
}
return FoldingDecorationProvider.NO_CONTROLS_EXPANDED_RANGE_DECORATION;
}
if (isCollapsed) {
return isManual ?
(this.showFoldingHighlights ? FoldingDecorationProvider.MANUALLY_COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION : FoldingDecorationProvider.MANUALLY_COLLAPSED_VISUAL_DECORATION)
: (this.showFoldingHighlights ? FoldingDecorationProvider.COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION : FoldingDecorationProvider.COLLAPSED_VISUAL_DECORATION);
} else if (this.showFoldingControls === 'mouseover') {
return isManual ? FoldingDecorationProvider.MANUALLY_EXPANDED_AUTO_HIDE_VISUAL_DECORATION : FoldingDecorationProvider.EXPANDED_AUTO_HIDE_VISUAL_DECORATION;
} else {
return isManual ? FoldingDecorationProvider.MANUALLY_EXPANDED_VISUAL_DECORATION : FoldingDecorationProvider.EXPANDED_VISUAL_DECORATION;
}
}
changeDecorations<T>(callback: (changeAccessor: IModelDecorationsChangeAccessor) => T): T {
return this.editor.changeDecorations(callback);
}
removeDecorations(decorationIds: string[]): void {
this.editor.removeDecorations(decorationIds);
}
}
| src/vs/editor/contrib/folding/browser/foldingDecorations.ts | 0 | https://github.com/microsoft/vscode/commit/94956b4c3fb38badce912cae3d5a531502669885 | [
0.00018447471666149795,
0.0001709204079816118,
0.00016593480540905148,
0.00017006875714287162,
0.00000421718914367375
] |
{
"id": 3,
"code_window": [
"\tconstructor(\n",
"\t\tprivate _rawOutput: IOutputDto\n",
"\t) {\n",
"\t\tsuper();\n",
"\t}\n",
"\n",
"\treplaceData(rawData: IOutputDto) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\t\tthis._alternativeOutputId = this._rawOutput.outputId;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/common/model/notebookCellOutputTextModel.ts",
"type": "add",
"edit_start_line_idx": 37
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { MarkdownPreviewManager } from './previewManager';
export const enum MarkdownPreviewSecurityLevel {
Strict = 0,
AllowInsecureContent = 1,
AllowScriptsAndAllContent = 2,
AllowInsecureLocalContent = 3
}
export interface ContentSecurityPolicyArbiter {
getSecurityLevelForResource(resource: vscode.Uri): MarkdownPreviewSecurityLevel;
setSecurityLevelForResource(resource: vscode.Uri, level: MarkdownPreviewSecurityLevel): Thenable<void>;
shouldAllowSvgsForResource(resource: vscode.Uri): void;
shouldDisableSecurityWarnings(): boolean;
setShouldDisableSecurityWarning(shouldShow: boolean): Thenable<void>;
}
export class ExtensionContentSecurityPolicyArbiter implements ContentSecurityPolicyArbiter {
private readonly _old_trusted_workspace_key = 'trusted_preview_workspace:';
private readonly _security_level_key = 'preview_security_level:';
private readonly _should_disable_security_warning_key = 'preview_should_show_security_warning:';
constructor(
private readonly _globalState: vscode.Memento,
private readonly _workspaceState: vscode.Memento
) { }
public getSecurityLevelForResource(resource: vscode.Uri): MarkdownPreviewSecurityLevel {
// Use new security level setting first
const level = this._globalState.get<MarkdownPreviewSecurityLevel | undefined>(this._security_level_key + this._getRoot(resource), undefined);
if (typeof level !== 'undefined') {
return level;
}
// Fallback to old trusted workspace setting
if (this._globalState.get<boolean>(this._old_trusted_workspace_key + this._getRoot(resource), false)) {
return MarkdownPreviewSecurityLevel.AllowScriptsAndAllContent;
}
return MarkdownPreviewSecurityLevel.Strict;
}
public setSecurityLevelForResource(resource: vscode.Uri, level: MarkdownPreviewSecurityLevel): Thenable<void> {
return this._globalState.update(this._security_level_key + this._getRoot(resource), level);
}
public shouldAllowSvgsForResource(resource: vscode.Uri) {
const securityLevel = this.getSecurityLevelForResource(resource);
return securityLevel === MarkdownPreviewSecurityLevel.AllowInsecureContent || securityLevel === MarkdownPreviewSecurityLevel.AllowScriptsAndAllContent;
}
public shouldDisableSecurityWarnings(): boolean {
return this._workspaceState.get<boolean>(this._should_disable_security_warning_key, false);
}
public setShouldDisableSecurityWarning(disabled: boolean): Thenable<void> {
return this._workspaceState.update(this._should_disable_security_warning_key, disabled);
}
private _getRoot(resource: vscode.Uri): vscode.Uri {
if (vscode.workspace.workspaceFolders) {
const folderForResource = vscode.workspace.getWorkspaceFolder(resource);
if (folderForResource) {
return folderForResource.uri;
}
if (vscode.workspace.workspaceFolders.length) {
return vscode.workspace.workspaceFolders[0].uri;
}
}
return resource;
}
}
export class PreviewSecuritySelector {
public constructor(
private readonly _cspArbiter: ContentSecurityPolicyArbiter,
private readonly _webviewManager: MarkdownPreviewManager
) { }
public async showSecuritySelectorForResource(resource: vscode.Uri): Promise<void> {
interface PreviewSecurityPickItem extends vscode.QuickPickItem {
readonly type: 'moreinfo' | 'toggle' | MarkdownPreviewSecurityLevel;
}
function markActiveWhen(when: boolean): string {
return when ? '• ' : '';
}
const currentSecurityLevel = this._cspArbiter.getSecurityLevelForResource(resource);
const selection = await vscode.window.showQuickPick<PreviewSecurityPickItem>(
[
{
type: MarkdownPreviewSecurityLevel.Strict,
label: markActiveWhen(currentSecurityLevel === MarkdownPreviewSecurityLevel.Strict) + vscode.l10n.t("Strict"),
description: vscode.l10n.t("Only load secure content"),
}, {
type: MarkdownPreviewSecurityLevel.AllowInsecureLocalContent,
label: markActiveWhen(currentSecurityLevel === MarkdownPreviewSecurityLevel.AllowInsecureLocalContent) + vscode.l10n.t("Allow insecure local content"),
description: vscode.l10n.t("Enable loading content over http served from localhost"),
}, {
type: MarkdownPreviewSecurityLevel.AllowInsecureContent,
label: markActiveWhen(currentSecurityLevel === MarkdownPreviewSecurityLevel.AllowInsecureContent) + vscode.l10n.t("Allow insecure content"),
description: vscode.l10n.t("Enable loading content over http"),
}, {
type: MarkdownPreviewSecurityLevel.AllowScriptsAndAllContent,
label: markActiveWhen(currentSecurityLevel === MarkdownPreviewSecurityLevel.AllowScriptsAndAllContent) + vscode.l10n.t("Disable"),
description: vscode.l10n.t("Allow all content and script execution. Not recommended"),
}, {
type: 'moreinfo',
label: vscode.l10n.t("More Information"),
description: ''
}, {
type: 'toggle',
label: this._cspArbiter.shouldDisableSecurityWarnings()
? vscode.l10n.t("Enable preview security warnings in this workspace")
: vscode.l10n.t("Disable preview security warning in this workspace"),
description: vscode.l10n.t("Does not affect the content security level")
},
], {
placeHolder: vscode.l10n.t("Select security settings for Markdown previews in this workspace"),
});
if (!selection) {
return;
}
if (selection.type === 'moreinfo') {
vscode.commands.executeCommand('vscode.open', vscode.Uri.parse('https://go.microsoft.com/fwlink/?linkid=854414'));
return;
}
if (selection.type === 'toggle') {
this._cspArbiter.setShouldDisableSecurityWarning(!this._cspArbiter.shouldDisableSecurityWarnings());
this._webviewManager.refresh();
return;
} else {
await this._cspArbiter.setSecurityLevelForResource(resource, selection.type);
}
this._webviewManager.refresh();
}
}
| extensions/markdown-language-features/src/preview/security.ts | 0 | https://github.com/microsoft/vscode/commit/94956b4c3fb38badce912cae3d5a531502669885 | [
0.00025488025858066976,
0.00018288797582499683,
0.0001685998577158898,
0.00017367838881909847,
0.000022715750674251467
] |
{
"id": 4,
"code_window": [
"\treadonly versionId: number;\n",
"\toutputs: IOutputItemDto[];\n",
"\tmetadata?: Record<string, any>;\n",
"\toutputId: string;\n",
"\tonDidChangeData: Event<void>;\n",
"\treplaceData(items: IOutputDto): void;\n",
"\tappendData(items: IOutputItemDto[]): void;\n",
"\tappendedSinceVersion(versionId: number, mime: string): VSBuffer | undefined;\n",
"\tasDto(): IOutputDto;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t/**\n",
"\t * Alternative output id that's reused when the output is updated.\n",
"\t */\n",
"\talternativeOutputId: string;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/common/notebookCommon.ts",
"type": "add",
"edit_start_line_idx": 216
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { VSBuffer } from 'vs/base/common/buffer';
import { Emitter } from 'vs/base/common/event';
import { Disposable } from 'vs/base/common/lifecycle';
import { ICellOutput, IOutputDto, IOutputItemDto, compressOutputItemStreams, isTextStreamMime } from 'vs/workbench/contrib/notebook/common/notebookCommon';
export class NotebookCellOutputTextModel extends Disposable implements ICellOutput {
private _onDidChangeData = this._register(new Emitter<void>());
onDidChangeData = this._onDidChangeData.event;
get outputs() {
return this._rawOutput.outputs || [];
}
get metadata(): Record<string, any> | undefined {
return this._rawOutput.metadata;
}
get outputId(): string {
return this._rawOutput.outputId;
}
private _versionId = 0;
get versionId() {
return this._versionId;
}
constructor(
private _rawOutput: IOutputDto
) {
super();
}
replaceData(rawData: IOutputDto) {
this.versionedBufferLengths = {};
this._rawOutput = rawData;
this.optimizeOutputItems();
this._versionId = this._versionId + 1;
this._onDidChangeData.fire();
}
appendData(items: IOutputItemDto[]) {
this.trackBufferLengths();
this._rawOutput.outputs.push(...items);
this.optimizeOutputItems();
this._versionId = this._versionId + 1;
this._onDidChangeData.fire();
}
private trackBufferLengths() {
this.outputs.forEach(output => {
if (isTextStreamMime(output.mime)) {
if (!this.versionedBufferLengths[output.mime]) {
this.versionedBufferLengths[output.mime] = {};
}
this.versionedBufferLengths[output.mime][this.versionId] = output.data.byteLength;
}
});
}
// mime: versionId: buffer length
private versionedBufferLengths: Record<string, Record<number, number>> = {};
appendedSinceVersion(versionId: number, mime: string): VSBuffer | undefined {
const bufferLength = this.versionedBufferLengths[mime]?.[versionId];
const output = this.outputs.find(output => output.mime === mime);
if (bufferLength && output) {
return output.data.slice(bufferLength);
}
return undefined;
}
private optimizeOutputItems() {
if (this.outputs.length > 1 && this.outputs.every(item => isTextStreamMime(item.mime))) {
// Look for the mimes in the items, and keep track of their order.
// Merge the streams into one output item, per mime type.
const mimeOutputs = new Map<string, Uint8Array[]>();
const mimeTypes: string[] = [];
this.outputs.forEach(item => {
let items: Uint8Array[];
if (mimeOutputs.has(item.mime)) {
items = mimeOutputs.get(item.mime)!;
} else {
items = [];
mimeOutputs.set(item.mime, items);
mimeTypes.push(item.mime);
}
items.push(item.data.buffer);
});
this.outputs.length = 0;
mimeTypes.forEach(mime => {
const compressionResult = compressOutputItemStreams(mimeOutputs.get(mime)!);
this.outputs.push({
mime,
data: compressionResult.data
});
if (compressionResult.didCompression) {
// we can't rely on knowing buffer lengths if we've erased previous lines
this.versionedBufferLengths = {};
}
});
}
}
asDto(): IOutputDto {
return {
// data: this._data,
metadata: this._rawOutput.metadata,
outputs: this._rawOutput.outputs,
outputId: this._rawOutput.outputId
};
}
bumpVersion() {
this._versionId = this._versionId + 1;
}
}
| src/vs/workbench/contrib/notebook/common/model/notebookCellOutputTextModel.ts | 1 | https://github.com/microsoft/vscode/commit/94956b4c3fb38badce912cae3d5a531502669885 | [
0.8889768719673157,
0.07101096957921982,
0.00016708300972823054,
0.0006168739637359977,
0.23616501688957214
] |
{
"id": 4,
"code_window": [
"\treadonly versionId: number;\n",
"\toutputs: IOutputItemDto[];\n",
"\tmetadata?: Record<string, any>;\n",
"\toutputId: string;\n",
"\tonDidChangeData: Event<void>;\n",
"\treplaceData(items: IOutputDto): void;\n",
"\tappendData(items: IOutputItemDto[]): void;\n",
"\tappendedSinceVersion(versionId: number, mime: string): VSBuffer | undefined;\n",
"\tasDto(): IOutputDto;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t/**\n",
"\t * Alternative output id that's reused when the output is updated.\n",
"\t */\n",
"\talternativeOutputId: string;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/common/notebookCommon.ts",
"type": "add",
"edit_start_line_idx": 216
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// empty placeholder declaration for the `editor/content` menu
| src/vscode-dts/vscode.proposed.contribEditorContentMenu.d.ts | 0 | https://github.com/microsoft/vscode/commit/94956b4c3fb38badce912cae3d5a531502669885 | [
0.0001767619833117351,
0.0001767619833117351,
0.0001767619833117351,
0.0001767619833117351,
0
] |
{
"id": 4,
"code_window": [
"\treadonly versionId: number;\n",
"\toutputs: IOutputItemDto[];\n",
"\tmetadata?: Record<string, any>;\n",
"\toutputId: string;\n",
"\tonDidChangeData: Event<void>;\n",
"\treplaceData(items: IOutputDto): void;\n",
"\tappendData(items: IOutputItemDto[]): void;\n",
"\tappendedSinceVersion(versionId: number, mime: string): VSBuffer | undefined;\n",
"\tasDto(): IOutputDto;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t/**\n",
"\t * Alternative output id that's reused when the output is updated.\n",
"\t */\n",
"\talternativeOutputId: string;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/common/notebookCommon.ts",
"type": "add",
"edit_start_line_idx": 216
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { EditorResourceAccessor, SideBySideEditor, EditorInputWithPreferredResource, EditorInputCapabilities, isEditorIdentifier, IResourceDiffEditorInput, IUntitledTextResourceEditorInput, isResourceEditorInput, isUntitledResourceEditorInput, isResourceDiffEditorInput, isEditorInputWithOptionsAndGroup, EditorInputWithOptions, isEditorInputWithOptions, isEditorInput, EditorInputWithOptionsAndGroup, isResourceSideBySideEditorInput, IResourceSideBySideEditorInput, isTextEditorViewState, isResourceMergeEditorInput, IResourceMergeEditorInput } from 'vs/workbench/common/editor';
import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput';
import { URI } from 'vs/base/common/uri';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { workbenchInstantiationService, TestServiceAccessor, TestEditorInput, registerTestEditor, registerTestFileEditor, registerTestResourceEditor, TestFileEditorInput, createEditorPart, registerTestSideBySideEditor } from 'vs/workbench/test/browser/workbenchTestServices';
import { Schemas } from 'vs/base/common/network';
import { UntitledTextEditorInput } from 'vs/workbench/services/untitled/common/untitledTextEditorInput';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { toResource } from 'vs/base/test/common/utils';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { whenEditorClosed } from 'vs/workbench/browser/editor';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { EditorService } from 'vs/workbench/services/editor/browser/editorService';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { SideBySideEditorInput } from 'vs/workbench/common/editor/sideBySideEditorInput';
import { EditorResolution, IResourceEditorInput } from 'vs/platform/editor/common/editor';
import { ICodeEditorViewState, IDiffEditorViewState } from 'vs/editor/common/editorCommon';
import { Position } from 'vs/editor/common/core/position';
suite('Workbench editor utils', () => {
class TestEditorInputWithPreferredResource extends TestEditorInput implements EditorInputWithPreferredResource {
constructor(resource: URI, public preferredResource: URI, typeId: string) {
super(resource, typeId);
}
}
const disposables = new DisposableStore();
const TEST_EDITOR_ID = 'MyTestEditorForEditors';
let instantiationService: IInstantiationService;
let accessor: TestServiceAccessor;
async function createServices(): Promise<TestServiceAccessor> {
const instantiationService = workbenchInstantiationService(undefined, disposables);
const part = await createEditorPart(instantiationService, disposables);
instantiationService.stub(IEditorGroupsService, part);
const editorService = instantiationService.createInstance(EditorService);
instantiationService.stub(IEditorService, editorService);
return instantiationService.createInstance(TestServiceAccessor);
}
setup(() => {
instantiationService = workbenchInstantiationService(undefined, disposables);
accessor = instantiationService.createInstance(TestServiceAccessor);
disposables.add(registerTestFileEditor());
disposables.add(registerTestSideBySideEditor());
disposables.add(registerTestResourceEditor());
disposables.add(registerTestEditor(TEST_EDITOR_ID, [new SyncDescriptor(TestFileEditorInput)]));
});
teardown(() => {
accessor.untitledTextEditorService.dispose();
disposables.clear();
});
test('untyped check functions', () => {
assert.ok(!isResourceEditorInput(undefined));
assert.ok(!isResourceEditorInput({}));
assert.ok(!isResourceEditorInput({ original: { resource: URI.file('/') }, modified: { resource: URI.file('/') } }));
assert.ok(isResourceEditorInput({ resource: URI.file('/') }));
assert.ok(!isUntitledResourceEditorInput(undefined));
assert.ok(isUntitledResourceEditorInput({}));
assert.ok(isUntitledResourceEditorInput({ resource: URI.file('/').with({ scheme: Schemas.untitled }) }));
assert.ok(isUntitledResourceEditorInput({ resource: URI.file('/'), forceUntitled: true }));
assert.ok(!isResourceDiffEditorInput(undefined));
assert.ok(!isResourceDiffEditorInput({}));
assert.ok(!isResourceDiffEditorInput({ resource: URI.file('/') }));
assert.ok(isResourceDiffEditorInput({ original: { resource: URI.file('/') }, modified: { resource: URI.file('/') } }));
assert.ok(isResourceDiffEditorInput({ original: { resource: URI.file('/') }, modified: { resource: URI.file('/') }, primary: { resource: URI.file('/') }, secondary: { resource: URI.file('/') } }));
assert.ok(!isResourceDiffEditorInput({ primary: { resource: URI.file('/') }, secondary: { resource: URI.file('/') } }));
assert.ok(!isResourceSideBySideEditorInput(undefined));
assert.ok(!isResourceSideBySideEditorInput({}));
assert.ok(!isResourceSideBySideEditorInput({ resource: URI.file('/') }));
assert.ok(isResourceSideBySideEditorInput({ primary: { resource: URI.file('/') }, secondary: { resource: URI.file('/') } }));
assert.ok(!isResourceSideBySideEditorInput({ original: { resource: URI.file('/') }, modified: { resource: URI.file('/') } }));
assert.ok(!isResourceSideBySideEditorInput({ primary: { resource: URI.file('/') }, secondary: { resource: URI.file('/') }, original: { resource: URI.file('/') }, modified: { resource: URI.file('/') } }));
assert.ok(!isResourceMergeEditorInput(undefined));
assert.ok(!isResourceMergeEditorInput({}));
assert.ok(!isResourceMergeEditorInput({ resource: URI.file('/') }));
assert.ok(isResourceMergeEditorInput({ input1: { resource: URI.file('/') }, input2: { resource: URI.file('/') }, base: { resource: URI.file('/') }, result: { resource: URI.file('/') } }));
});
test('EditorInputCapabilities', () => {
const testInput1 = new TestFileEditorInput(URI.file('resource1'), 'testTypeId');
const testInput2 = new TestFileEditorInput(URI.file('resource2'), 'testTypeId');
testInput1.capabilities = EditorInputCapabilities.None;
assert.strictEqual(testInput1.hasCapability(EditorInputCapabilities.None), true);
assert.strictEqual(testInput1.hasCapability(EditorInputCapabilities.Readonly), false);
assert.strictEqual(testInput1.isReadonly(), false);
assert.strictEqual(testInput1.hasCapability(EditorInputCapabilities.Untitled), false);
assert.strictEqual(testInput1.hasCapability(EditorInputCapabilities.RequiresTrust), false);
assert.strictEqual(testInput1.hasCapability(EditorInputCapabilities.Singleton), false);
testInput1.capabilities |= EditorInputCapabilities.Readonly;
assert.strictEqual(testInput1.hasCapability(EditorInputCapabilities.Readonly), true);
assert.strictEqual(!!testInput1.isReadonly(), true);
assert.strictEqual(testInput1.hasCapability(EditorInputCapabilities.None), false);
assert.strictEqual(testInput1.hasCapability(EditorInputCapabilities.Untitled), false);
assert.strictEqual(testInput1.hasCapability(EditorInputCapabilities.RequiresTrust), false);
assert.strictEqual(testInput1.hasCapability(EditorInputCapabilities.Singleton), false);
testInput1.capabilities = EditorInputCapabilities.None;
testInput2.capabilities = EditorInputCapabilities.None;
const sideBySideInput = instantiationService.createInstance(SideBySideEditorInput, 'name', undefined, testInput1, testInput2);
assert.strictEqual(sideBySideInput.hasCapability(EditorInputCapabilities.MultipleEditors), true);
assert.strictEqual(sideBySideInput.hasCapability(EditorInputCapabilities.Readonly), false);
assert.strictEqual(sideBySideInput.isReadonly(), false);
assert.strictEqual(sideBySideInput.hasCapability(EditorInputCapabilities.Untitled), false);
assert.strictEqual(sideBySideInput.hasCapability(EditorInputCapabilities.RequiresTrust), false);
assert.strictEqual(sideBySideInput.hasCapability(EditorInputCapabilities.Singleton), false);
testInput1.capabilities |= EditorInputCapabilities.Readonly;
assert.strictEqual(sideBySideInput.hasCapability(EditorInputCapabilities.Readonly), false);
assert.strictEqual(sideBySideInput.isReadonly(), false);
testInput2.capabilities |= EditorInputCapabilities.Readonly;
assert.strictEqual(sideBySideInput.hasCapability(EditorInputCapabilities.Readonly), true);
assert.strictEqual(!!sideBySideInput.isReadonly(), true);
testInput1.capabilities |= EditorInputCapabilities.Untitled;
assert.strictEqual(sideBySideInput.hasCapability(EditorInputCapabilities.Untitled), false);
testInput2.capabilities |= EditorInputCapabilities.Untitled;
assert.strictEqual(sideBySideInput.hasCapability(EditorInputCapabilities.Untitled), true);
testInput1.capabilities |= EditorInputCapabilities.RequiresTrust;
assert.strictEqual(sideBySideInput.hasCapability(EditorInputCapabilities.RequiresTrust), true);
testInput2.capabilities |= EditorInputCapabilities.RequiresTrust;
assert.strictEqual(sideBySideInput.hasCapability(EditorInputCapabilities.RequiresTrust), true);
testInput1.capabilities |= EditorInputCapabilities.Singleton;
assert.strictEqual(sideBySideInput.hasCapability(EditorInputCapabilities.Singleton), true);
testInput2.capabilities |= EditorInputCapabilities.Singleton;
assert.strictEqual(sideBySideInput.hasCapability(EditorInputCapabilities.Singleton), true);
});
test('EditorResourceAccessor - typed inputs', () => {
const service = accessor.untitledTextEditorService;
assert.ok(!EditorResourceAccessor.getCanonicalUri(null!));
assert.ok(!EditorResourceAccessor.getOriginalUri(null!));
const untitled = instantiationService.createInstance(UntitledTextEditorInput, service.create());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(untitled)?.toString(), untitled.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(untitled, { supportSideBySide: SideBySideEditor.PRIMARY })?.toString(), untitled.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(untitled, { supportSideBySide: SideBySideEditor.ANY })?.toString(), untitled.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(untitled, { supportSideBySide: SideBySideEditor.SECONDARY })?.toString(), untitled.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(untitled, { supportSideBySide: SideBySideEditor.BOTH })?.toString(), untitled.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(untitled, { filterByScheme: Schemas.untitled })?.toString(), untitled.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(untitled, { filterByScheme: [Schemas.file, Schemas.untitled] })?.toString(), untitled.resource.toString());
assert.ok(!EditorResourceAccessor.getCanonicalUri(untitled, { filterByScheme: Schemas.file }));
assert.strictEqual(EditorResourceAccessor.getOriginalUri(untitled)?.toString(), untitled.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(untitled, { supportSideBySide: SideBySideEditor.PRIMARY })?.toString(), untitled.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(untitled, { supportSideBySide: SideBySideEditor.ANY })?.toString(), untitled.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(untitled, { supportSideBySide: SideBySideEditor.SECONDARY })?.toString(), untitled.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(untitled, { supportSideBySide: SideBySideEditor.BOTH })?.toString(), untitled.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(untitled, { filterByScheme: Schemas.untitled })?.toString(), untitled.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(untitled, { filterByScheme: [Schemas.file, Schemas.untitled] })?.toString(), untitled.resource.toString());
assert.ok(!EditorResourceAccessor.getOriginalUri(untitled, { filterByScheme: Schemas.file }));
const file = new TestEditorInput(URI.file('/some/path.txt'), 'editorResourceFileTest');
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(file)?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(file, { supportSideBySide: SideBySideEditor.PRIMARY })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(file, { supportSideBySide: SideBySideEditor.ANY })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(file, { supportSideBySide: SideBySideEditor.SECONDARY })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(file, { supportSideBySide: SideBySideEditor.BOTH })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(file, { filterByScheme: Schemas.file })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(file, { filterByScheme: [Schemas.file, Schemas.untitled] })?.toString(), file.resource.toString());
assert.ok(!EditorResourceAccessor.getCanonicalUri(file, { filterByScheme: Schemas.untitled }));
assert.strictEqual(EditorResourceAccessor.getOriginalUri(file)?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(file, { supportSideBySide: SideBySideEditor.PRIMARY })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(file, { supportSideBySide: SideBySideEditor.ANY })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(file, { supportSideBySide: SideBySideEditor.SECONDARY })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(file, { supportSideBySide: SideBySideEditor.BOTH })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(file, { filterByScheme: Schemas.file })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(file, { filterByScheme: [Schemas.file, Schemas.untitled] })?.toString(), file.resource.toString());
assert.ok(!EditorResourceAccessor.getOriginalUri(file, { filterByScheme: Schemas.untitled }));
const diffInput = instantiationService.createInstance(DiffEditorInput, 'name', 'description', untitled, file, undefined);
const sideBySideInput = instantiationService.createInstance(SideBySideEditorInput, 'name', 'description', untitled, file);
for (const input of [diffInput, sideBySideInput]) {
assert.ok(!EditorResourceAccessor.getCanonicalUri(input));
assert.ok(!EditorResourceAccessor.getCanonicalUri(input, { filterByScheme: Schemas.file }));
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(input, { supportSideBySide: SideBySideEditor.PRIMARY })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(input, { supportSideBySide: SideBySideEditor.PRIMARY, filterByScheme: Schemas.file })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(input, { supportSideBySide: SideBySideEditor.PRIMARY, filterByScheme: [Schemas.file, Schemas.untitled] })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(input, { supportSideBySide: SideBySideEditor.SECONDARY })?.toString(), untitled.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(input, { supportSideBySide: SideBySideEditor.SECONDARY, filterByScheme: Schemas.untitled })?.toString(), untitled.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(input, { supportSideBySide: SideBySideEditor.SECONDARY, filterByScheme: [Schemas.file, Schemas.untitled] })?.toString(), untitled.resource.toString());
assert.strictEqual((EditorResourceAccessor.getCanonicalUri(input, { supportSideBySide: SideBySideEditor.BOTH }) as { primary: URI; secondary: URI }).primary.toString(), file.resource.toString());
assert.strictEqual((EditorResourceAccessor.getCanonicalUri(input, { supportSideBySide: SideBySideEditor.BOTH, filterByScheme: Schemas.file }) as { primary: URI; secondary: URI }).primary.toString(), file.resource.toString());
assert.strictEqual((EditorResourceAccessor.getCanonicalUri(input, { supportSideBySide: SideBySideEditor.BOTH, filterByScheme: [Schemas.file, Schemas.untitled] }) as { primary: URI; secondary: URI }).primary.toString(), file.resource.toString());
assert.strictEqual((EditorResourceAccessor.getCanonicalUri(input, { supportSideBySide: SideBySideEditor.BOTH }) as { primary: URI; secondary: URI }).secondary.toString(), untitled.resource.toString());
assert.strictEqual((EditorResourceAccessor.getCanonicalUri(input, { supportSideBySide: SideBySideEditor.BOTH, filterByScheme: Schemas.untitled }) as { primary: URI; secondary: URI }).secondary.toString(), untitled.resource.toString());
assert.strictEqual((EditorResourceAccessor.getCanonicalUri(input, { supportSideBySide: SideBySideEditor.BOTH, filterByScheme: [Schemas.file, Schemas.untitled] }) as { primary: URI; secondary: URI }).secondary.toString(), untitled.resource.toString());
assert.ok(!EditorResourceAccessor.getOriginalUri(input));
assert.ok(!EditorResourceAccessor.getOriginalUri(input, { filterByScheme: Schemas.file }));
assert.strictEqual(EditorResourceAccessor.getOriginalUri(input, { supportSideBySide: SideBySideEditor.PRIMARY })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(input, { supportSideBySide: SideBySideEditor.PRIMARY, filterByScheme: Schemas.file })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(input, { supportSideBySide: SideBySideEditor.PRIMARY, filterByScheme: [Schemas.file, Schemas.untitled] })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(input, { supportSideBySide: SideBySideEditor.SECONDARY })?.toString(), untitled.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(input, { supportSideBySide: SideBySideEditor.SECONDARY, filterByScheme: Schemas.untitled })?.toString(), untitled.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(input, { supportSideBySide: SideBySideEditor.SECONDARY, filterByScheme: [Schemas.file, Schemas.untitled] })?.toString(), untitled.resource.toString());
assert.strictEqual((EditorResourceAccessor.getOriginalUri(input, { supportSideBySide: SideBySideEditor.BOTH }) as { primary: URI; secondary: URI }).primary.toString(), file.resource.toString());
assert.strictEqual((EditorResourceAccessor.getOriginalUri(input, { supportSideBySide: SideBySideEditor.BOTH, filterByScheme: Schemas.file }) as { primary: URI; secondary: URI }).primary.toString(), file.resource.toString());
assert.strictEqual((EditorResourceAccessor.getOriginalUri(input, { supportSideBySide: SideBySideEditor.BOTH, filterByScheme: [Schemas.file, Schemas.untitled] }) as { primary: URI; secondary: URI }).primary.toString(), file.resource.toString());
assert.strictEqual((EditorResourceAccessor.getOriginalUri(input, { supportSideBySide: SideBySideEditor.BOTH }) as { primary: URI; secondary: URI }).secondary.toString(), untitled.resource.toString());
assert.strictEqual((EditorResourceAccessor.getOriginalUri(input, { supportSideBySide: SideBySideEditor.BOTH, filterByScheme: Schemas.untitled }) as { primary: URI; secondary: URI }).secondary.toString(), untitled.resource.toString());
assert.strictEqual((EditorResourceAccessor.getOriginalUri(input, { supportSideBySide: SideBySideEditor.BOTH, filterByScheme: [Schemas.file, Schemas.untitled] }) as { primary: URI; secondary: URI }).secondary.toString(), untitled.resource.toString());
}
const resource = URI.file('/some/path.txt');
const preferredResource = URI.file('/some/PATH.txt');
const fileWithPreferredResource = new TestEditorInputWithPreferredResource(URI.file('/some/path.txt'), URI.file('/some/PATH.txt'), 'editorResourceFileTest');
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(fileWithPreferredResource)?.toString(), resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(fileWithPreferredResource)?.toString(), preferredResource.toString());
});
test('EditorResourceAccessor - untyped inputs', () => {
assert.ok(!EditorResourceAccessor.getCanonicalUri(null!));
assert.ok(!EditorResourceAccessor.getOriginalUri(null!));
const untitledURI = URI.from({
scheme: Schemas.untitled,
authority: 'foo',
path: '/bar'
});
const untitled: IUntitledTextResourceEditorInput = {
resource: untitledURI
};
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(untitled)?.toString(), untitled.resource?.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(untitled, { supportSideBySide: SideBySideEditor.PRIMARY })?.toString(), untitled.resource?.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(untitled, { supportSideBySide: SideBySideEditor.ANY })?.toString(), untitled.resource?.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(untitled, { supportSideBySide: SideBySideEditor.SECONDARY })?.toString(), untitled.resource?.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(untitled, { supportSideBySide: SideBySideEditor.BOTH })?.toString(), untitled.resource?.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(untitled, { filterByScheme: Schemas.untitled })?.toString(), untitled.resource?.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(untitled, { filterByScheme: [Schemas.file, Schemas.untitled] })?.toString(), untitled.resource?.toString());
assert.ok(!EditorResourceAccessor.getCanonicalUri(untitled, { filterByScheme: Schemas.file }));
assert.strictEqual(EditorResourceAccessor.getOriginalUri(untitled)?.toString(), untitled.resource?.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(untitled, { supportSideBySide: SideBySideEditor.PRIMARY })?.toString(), untitled.resource?.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(untitled, { supportSideBySide: SideBySideEditor.ANY })?.toString(), untitled.resource?.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(untitled, { supportSideBySide: SideBySideEditor.SECONDARY })?.toString(), untitled.resource?.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(untitled, { supportSideBySide: SideBySideEditor.BOTH })?.toString(), untitled.resource?.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(untitled, { filterByScheme: Schemas.untitled })?.toString(), untitled.resource?.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(untitled, { filterByScheme: [Schemas.file, Schemas.untitled] })?.toString(), untitled.resource?.toString());
assert.ok(!EditorResourceAccessor.getOriginalUri(untitled, { filterByScheme: Schemas.file }));
const file: IResourceEditorInput = {
resource: URI.file('/some/path.txt')
};
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(file)?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(file, { supportSideBySide: SideBySideEditor.PRIMARY })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(file, { supportSideBySide: SideBySideEditor.ANY })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(file, { supportSideBySide: SideBySideEditor.SECONDARY })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(file, { supportSideBySide: SideBySideEditor.BOTH })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(file, { filterByScheme: Schemas.file })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(file, { filterByScheme: [Schemas.file, Schemas.untitled] })?.toString(), file.resource.toString());
assert.ok(!EditorResourceAccessor.getCanonicalUri(file, { filterByScheme: Schemas.untitled }));
assert.strictEqual(EditorResourceAccessor.getOriginalUri(file)?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(file, { supportSideBySide: SideBySideEditor.PRIMARY })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(file, { supportSideBySide: SideBySideEditor.ANY })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(file, { supportSideBySide: SideBySideEditor.SECONDARY })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(file, { supportSideBySide: SideBySideEditor.BOTH })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(file, { filterByScheme: Schemas.file })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(file, { filterByScheme: [Schemas.file, Schemas.untitled] })?.toString(), file.resource.toString());
assert.ok(!EditorResourceAccessor.getOriginalUri(file, { filterByScheme: Schemas.untitled }));
const diffInput: IResourceDiffEditorInput = { original: untitled, modified: file };
const sideBySideInput: IResourceSideBySideEditorInput = { primary: file, secondary: untitled };
for (const untypedInput of [diffInput, sideBySideInput]) {
assert.ok(!EditorResourceAccessor.getCanonicalUri(untypedInput));
assert.ok(!EditorResourceAccessor.getCanonicalUri(untypedInput, { filterByScheme: Schemas.file }));
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(untypedInput, { supportSideBySide: SideBySideEditor.PRIMARY })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(untypedInput, { supportSideBySide: SideBySideEditor.PRIMARY, filterByScheme: Schemas.file })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(untypedInput, { supportSideBySide: SideBySideEditor.PRIMARY, filterByScheme: [Schemas.file, Schemas.untitled] })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(untypedInput, { supportSideBySide: SideBySideEditor.SECONDARY })?.toString(), untitled.resource?.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(untypedInput, { supportSideBySide: SideBySideEditor.SECONDARY, filterByScheme: Schemas.untitled })?.toString(), untitled.resource?.toString());
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(untypedInput, { supportSideBySide: SideBySideEditor.SECONDARY, filterByScheme: [Schemas.file, Schemas.untitled] })?.toString(), untitled.resource?.toString());
assert.strictEqual((EditorResourceAccessor.getCanonicalUri(untypedInput, { supportSideBySide: SideBySideEditor.BOTH }) as { primary: URI; secondary: URI }).primary.toString(), file.resource.toString());
assert.strictEqual((EditorResourceAccessor.getCanonicalUri(untypedInput, { supportSideBySide: SideBySideEditor.BOTH, filterByScheme: Schemas.file }) as { primary: URI; secondary: URI }).primary.toString(), file.resource.toString());
assert.strictEqual((EditorResourceAccessor.getCanonicalUri(untypedInput, { supportSideBySide: SideBySideEditor.BOTH, filterByScheme: [Schemas.file, Schemas.untitled] }) as { primary: URI; secondary: URI }).primary.toString(), file.resource.toString());
assert.strictEqual((EditorResourceAccessor.getCanonicalUri(untypedInput, { supportSideBySide: SideBySideEditor.BOTH }) as { primary: URI; secondary: URI }).secondary.toString(), untitled.resource?.toString());
assert.strictEqual((EditorResourceAccessor.getCanonicalUri(untypedInput, { supportSideBySide: SideBySideEditor.BOTH, filterByScheme: Schemas.untitled }) as { primary: URI; secondary: URI }).secondary.toString(), untitled.resource?.toString());
assert.strictEqual((EditorResourceAccessor.getCanonicalUri(untypedInput, { supportSideBySide: SideBySideEditor.BOTH, filterByScheme: [Schemas.file, Schemas.untitled] }) as { primary: URI; secondary: URI }).secondary.toString(), untitled.resource?.toString());
assert.ok(!EditorResourceAccessor.getOriginalUri(untypedInput));
assert.ok(!EditorResourceAccessor.getOriginalUri(untypedInput, { filterByScheme: Schemas.file }));
assert.strictEqual(EditorResourceAccessor.getOriginalUri(untypedInput, { supportSideBySide: SideBySideEditor.PRIMARY })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(untypedInput, { supportSideBySide: SideBySideEditor.PRIMARY, filterByScheme: Schemas.file })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(untypedInput, { supportSideBySide: SideBySideEditor.PRIMARY, filterByScheme: [Schemas.file, Schemas.untitled] })?.toString(), file.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(untypedInput, { supportSideBySide: SideBySideEditor.SECONDARY })?.toString(), untitled.resource?.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(untypedInput, { supportSideBySide: SideBySideEditor.SECONDARY, filterByScheme: Schemas.untitled })?.toString(), untitled.resource?.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(untypedInput, { supportSideBySide: SideBySideEditor.SECONDARY, filterByScheme: [Schemas.file, Schemas.untitled] })?.toString(), untitled.resource?.toString());
assert.strictEqual((EditorResourceAccessor.getOriginalUri(untypedInput, { supportSideBySide: SideBySideEditor.BOTH }) as { primary: URI; secondary: URI }).primary.toString(), file.resource.toString());
assert.strictEqual((EditorResourceAccessor.getOriginalUri(untypedInput, { supportSideBySide: SideBySideEditor.BOTH, filterByScheme: Schemas.file }) as { primary: URI; secondary: URI }).primary.toString(), file.resource.toString());
assert.strictEqual((EditorResourceAccessor.getOriginalUri(untypedInput, { supportSideBySide: SideBySideEditor.BOTH, filterByScheme: [Schemas.file, Schemas.untitled] }) as { primary: URI; secondary: URI }).primary.toString(), file.resource.toString());
assert.strictEqual((EditorResourceAccessor.getOriginalUri(untypedInput, { supportSideBySide: SideBySideEditor.BOTH }) as { primary: URI; secondary: URI }).secondary.toString(), untitled.resource?.toString());
assert.strictEqual((EditorResourceAccessor.getOriginalUri(untypedInput, { supportSideBySide: SideBySideEditor.BOTH, filterByScheme: Schemas.untitled }) as { primary: URI; secondary: URI }).secondary.toString(), untitled.resource?.toString());
assert.strictEqual((EditorResourceAccessor.getOriginalUri(untypedInput, { supportSideBySide: SideBySideEditor.BOTH, filterByScheme: [Schemas.file, Schemas.untitled] }) as { primary: URI; secondary: URI }).secondary.toString(), untitled.resource?.toString());
}
const fileMerge: IResourceMergeEditorInput = {
input1: { resource: URI.file('/some/remote.txt') },
input2: { resource: URI.file('/some/local.txt') },
base: { resource: URI.file('/some/base.txt') },
result: { resource: URI.file('/some/merged.txt') }
};
assert.strictEqual(EditorResourceAccessor.getCanonicalUri(fileMerge)?.toString(), fileMerge.result.resource.toString());
assert.strictEqual(EditorResourceAccessor.getOriginalUri(fileMerge)?.toString(), fileMerge.result.resource.toString());
});
test('isEditorIdentifier', () => {
assert.strictEqual(isEditorIdentifier(undefined), false);
assert.strictEqual(isEditorIdentifier('undefined'), false);
const testInput1 = new TestFileEditorInput(URI.file('resource1'), 'testTypeId');
assert.strictEqual(isEditorIdentifier(testInput1), false);
assert.strictEqual(isEditorIdentifier({ editor: testInput1, groupId: 3 }), true);
});
test('isEditorInputWithOptionsAndGroup', () => {
const editorInput = new TestFileEditorInput(URI.file('resource1'), 'testTypeId');
assert.strictEqual(isEditorInput(editorInput), true);
assert.strictEqual(isEditorInputWithOptions(editorInput), false);
assert.strictEqual(isEditorInputWithOptionsAndGroup(editorInput), false);
const editorInputWithOptions: EditorInputWithOptions = { editor: editorInput, options: { override: EditorResolution.PICK } };
assert.strictEqual(isEditorInput(editorInputWithOptions), false);
assert.strictEqual(isEditorInputWithOptions(editorInputWithOptions), true);
assert.strictEqual(isEditorInputWithOptionsAndGroup(editorInputWithOptions), false);
const service = accessor.editorGroupService;
const editorInputWithOptionsAndGroup: EditorInputWithOptionsAndGroup = { editor: editorInput, options: { override: EditorResolution.PICK }, group: service.activeGroup };
assert.strictEqual(isEditorInput(editorInputWithOptionsAndGroup), false);
assert.strictEqual(isEditorInputWithOptions(editorInputWithOptionsAndGroup), true);
assert.strictEqual(isEditorInputWithOptionsAndGroup(editorInputWithOptionsAndGroup), true);
});
test('isTextEditorViewState', () => {
assert.strictEqual(isTextEditorViewState(undefined), false);
assert.strictEqual(isTextEditorViewState({}), false);
const codeEditorViewState: ICodeEditorViewState = {
contributionsState: {},
cursorState: [],
viewState: {
scrollLeft: 0,
firstPosition: new Position(1, 1),
firstPositionDeltaTop: 1
}
};
assert.strictEqual(isTextEditorViewState(codeEditorViewState), true);
const diffEditorViewState: IDiffEditorViewState = {
original: codeEditorViewState,
modified: codeEditorViewState
};
assert.strictEqual(isTextEditorViewState(diffEditorViewState), true);
});
test('whenEditorClosed (single editor)', async function () {
return testWhenEditorClosed(false, false, toResource.call(this, '/path/index.txt'));
});
test('whenEditorClosed (multiple editor)', async function () {
return testWhenEditorClosed(false, false, toResource.call(this, '/path/index.txt'), toResource.call(this, '/test.html'));
});
test('whenEditorClosed (single editor, diff editor)', async function () {
return testWhenEditorClosed(true, false, toResource.call(this, '/path/index.txt'));
});
test('whenEditorClosed (multiple editor, diff editor)', async function () {
return testWhenEditorClosed(true, false, toResource.call(this, '/path/index.txt'), toResource.call(this, '/test.html'));
});
test('whenEditorClosed (single custom editor)', async function () {
return testWhenEditorClosed(false, true, toResource.call(this, '/path/index.txt'));
});
test('whenEditorClosed (multiple custom editor)', async function () {
return testWhenEditorClosed(false, true, toResource.call(this, '/path/index.txt'), toResource.call(this, '/test.html'));
});
async function testWhenEditorClosed(sideBySide: boolean, custom: boolean, ...resources: URI[]): Promise<void> {
const accessor = await createServices();
for (const resource of resources) {
if (custom) {
await accessor.editorService.openEditor(new TestFileEditorInput(resource, 'testTypeId'), { pinned: true });
} else if (sideBySide) {
await accessor.editorService.openEditor(instantiationService.createInstance(SideBySideEditorInput, 'testSideBySideEditor', undefined, new TestFileEditorInput(resource, 'testTypeId'), new TestFileEditorInput(resource, 'testTypeId')), { pinned: true });
} else {
await accessor.editorService.openEditor({ resource, options: { pinned: true } });
}
}
const closedPromise = accessor.instantitionService.invokeFunction(accessor => whenEditorClosed(accessor, resources));
accessor.editorGroupService.activeGroup.closeAllEditors();
await closedPromise;
}
});
| src/vs/workbench/test/browser/parts/editor/editor.test.ts | 0 | https://github.com/microsoft/vscode/commit/94956b4c3fb38badce912cae3d5a531502669885 | [
0.00017827775445766747,
0.00017469716840423644,
0.00017037348879966885,
0.00017445243429392576,
0.0000018992091099789832
] |
{
"id": 4,
"code_window": [
"\treadonly versionId: number;\n",
"\toutputs: IOutputItemDto[];\n",
"\tmetadata?: Record<string, any>;\n",
"\toutputId: string;\n",
"\tonDidChangeData: Event<void>;\n",
"\treplaceData(items: IOutputDto): void;\n",
"\tappendData(items: IOutputItemDto[]): void;\n",
"\tappendedSinceVersion(versionId: number, mime: string): VSBuffer | undefined;\n",
"\tasDto(): IOutputDto;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t/**\n",
"\t * Alternative output id that's reused when the output is updated.\n",
"\t */\n",
"\talternativeOutputId: string;\n"
],
"file_path": "src/vs/workbench/contrib/notebook/common/notebookCommon.ts",
"type": "add",
"edit_start_line_idx": 216
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import 'mocha';
import * as vscode from 'vscode';
import { joinLines } from './util';
const testFileA = workspaceFile('a.md');
const debug = false;
function debugLog(...args: any[]) {
if (debug) {
console.log(...args);
}
}
function workspaceFile(...segments: string[]) {
return vscode.Uri.joinPath(vscode.workspace.workspaceFolders![0].uri, ...segments);
}
async function getLinksForFile(file: vscode.Uri): Promise<vscode.DocumentLink[]> {
debugLog('getting links', file.toString(), Date.now());
const r = (await vscode.commands.executeCommand<vscode.DocumentLink[]>('vscode.executeLinkProvider', file, /*linkResolveCount*/ 100))!;
debugLog('got links', file.toString(), Date.now());
return r;
}
(vscode.env.uiKind === vscode.UIKind.Web ? suite.skip : suite)('Markdown Document links', () => {
setup(async () => {
// the tests make the assumption that link providers are already registered
await vscode.extensions.getExtension('vscode.markdown-language-features')!.activate();
});
teardown(async () => {
await vscode.commands.executeCommand('workbench.action.closeAllEditors');
});
test('Should navigate to markdown file', async () => {
await withFileContents(testFileA, '[b](b.md)');
const [link] = await getLinksForFile(testFileA);
await executeLink(link);
assertActiveDocumentUri(workspaceFile('b.md'));
});
test('Should navigate to markdown file with leading ./', async () => {
await withFileContents(testFileA, '[b](./b.md)');
const [link] = await getLinksForFile(testFileA);
await executeLink(link);
assertActiveDocumentUri(workspaceFile('b.md'));
});
test('Should navigate to markdown file with leading /', async () => {
await withFileContents(testFileA, '[b](./b.md)');
const [link] = await getLinksForFile(testFileA);
await executeLink(link);
assertActiveDocumentUri(workspaceFile('b.md'));
});
test('Should navigate to markdown file without file extension', async () => {
await withFileContents(testFileA, '[b](b)');
const [link] = await getLinksForFile(testFileA);
await executeLink(link);
assertActiveDocumentUri(workspaceFile('b.md'));
});
test('Should navigate to markdown file in directory', async () => {
await withFileContents(testFileA, '[b](sub/c)');
const [link] = await getLinksForFile(testFileA);
await executeLink(link);
assertActiveDocumentUri(workspaceFile('sub', 'c.md'));
});
test('Should navigate to fragment by title in file', async () => {
await withFileContents(testFileA, '[b](sub/c#second)');
const [link] = await getLinksForFile(testFileA);
await executeLink(link);
assertActiveDocumentUri(workspaceFile('sub', 'c.md'));
assert.strictEqual(vscode.window.activeTextEditor!.selection.start.line, 1);
});
test('Should navigate to fragment by line', async () => {
await withFileContents(testFileA, '[b](sub/c#L2)');
const [link] = await getLinksForFile(testFileA);
await executeLink(link);
assertActiveDocumentUri(workspaceFile('sub', 'c.md'));
assert.strictEqual(vscode.window.activeTextEditor!.selection.start.line, 1);
});
test('Should navigate to line number within non-md file', async () => {
await withFileContents(testFileA, '[b](sub/foo.txt#L3)');
const [link] = await getLinksForFile(testFileA);
await executeLink(link);
assertActiveDocumentUri(workspaceFile('sub', 'foo.txt'));
assert.strictEqual(vscode.window.activeTextEditor!.selection.start.line, 2);
});
test('Should navigate to fragment within current file', async () => {
await withFileContents(testFileA, joinLines(
'[](a#header)',
'[](#header)',
'# Header'));
const links = await getLinksForFile(testFileA);
{
await executeLink(links[0]);
assertActiveDocumentUri(workspaceFile('a.md'));
assert.strictEqual(vscode.window.activeTextEditor!.selection.start.line, 2);
}
{
await executeLink(links[1]);
assertActiveDocumentUri(workspaceFile('a.md'));
assert.strictEqual(vscode.window.activeTextEditor!.selection.start.line, 2);
}
});
test.skip('Should navigate to fragment within current untitled file', async () => { // TODO: skip for now for ls migration
const testFile = workspaceFile('x.md').with({ scheme: 'untitled' });
await withFileContents(testFile, joinLines(
'[](#second)',
'# Second'));
const [link] = await getLinksForFile(testFile);
await executeLink(link);
assertActiveDocumentUri(testFile);
assert.strictEqual(vscode.window.activeTextEditor!.selection.start.line, 1);
});
});
function assertActiveDocumentUri(expectedUri: vscode.Uri) {
assert.strictEqual(
vscode.window.activeTextEditor!.document.uri.fsPath,
expectedUri.fsPath
);
}
async function withFileContents(file: vscode.Uri, contents: string): Promise<void> {
debugLog('openTextDocument', file.toString(), Date.now());
const document = await vscode.workspace.openTextDocument(file);
debugLog('showTextDocument', file.toString(), Date.now());
const editor = await vscode.window.showTextDocument(document);
debugLog('editTextDocument', file.toString(), Date.now());
await editor.edit(edit => {
edit.replace(new vscode.Range(0, 0, 1000, 0), contents);
});
debugLog('opened done', vscode.window.activeTextEditor?.document.toString(), Date.now());
}
async function executeLink(link: vscode.DocumentLink) {
debugLog('executingLink', link.target?.toString(), Date.now());
await vscode.commands.executeCommand('vscode.open', link.target!);
debugLog('executedLink', vscode.window.activeTextEditor?.document.toString(), Date.now());
}
| extensions/markdown-language-features/src/test/documentLink.test.ts | 0 | https://github.com/microsoft/vscode/commit/94956b4c3fb38badce912cae3d5a531502669885 | [
0.00017842859961092472,
0.0001756077544996515,
0.00017152196960523725,
0.00017565939924679697,
0.0000016083073433037498
] |
{
"id": 0,
"code_window": [
"import React, { useRef, useState } from 'react';\n",
"import { Button, Tabs } from 'antd';\n",
"\n",
"const defaultPanes = new Array(2).fill(null).map((_, index) => {\n",
" const id = String(index + 1);\n",
" return { label: `Tab ${id}`, children: `Content of Tab Pane ${index + 1}`, key: id };\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"type TargetKey = React.MouseEvent | React.KeyboardEvent | string;\n",
"\n"
],
"file_path": "components/tabs/demo/custom-add-trigger.tsx",
"type": "add",
"edit_start_line_idx": 3
} | import React, { useRef, useState } from 'react';
import { Button, Tabs } from 'antd';
const defaultPanes = new Array(2).fill(null).map((_, index) => {
const id = String(index + 1);
return { label: `Tab ${id}`, children: `Content of Tab Pane ${index + 1}`, key: id };
});
const App: React.FC = () => {
const [activeKey, setActiveKey] = useState(defaultPanes[0].key);
const [items, setItems] = useState(defaultPanes);
const newTabIndex = useRef(0);
const onChange = (key: string) => {
setActiveKey(key);
};
const add = () => {
const newActiveKey = `newTab${newTabIndex.current++}`;
setItems([...items, { label: 'New Tab', children: 'New Tab Pane', key: newActiveKey }]);
setActiveKey(newActiveKey);
};
const remove = (targetKey: string) => {
const targetIndex = items.findIndex((pane) => pane.key === targetKey);
const newPanes = items.filter((pane) => pane.key !== targetKey);
if (newPanes.length && targetKey === activeKey) {
const { key } = newPanes[targetIndex === newPanes.length ? targetIndex - 1 : targetIndex];
setActiveKey(key);
}
setItems(newPanes);
};
const onEdit = (targetKey: string, action: 'add' | 'remove') => {
if (action === 'add') {
add();
} else {
remove(targetKey);
}
};
return (
<div>
<div style={{ marginBottom: 16 }}>
<Button onClick={add}>ADD</Button>
</div>
<Tabs
hideAdd
onChange={onChange}
activeKey={activeKey}
type="editable-card"
onEdit={onEdit}
items={items}
/>
</div>
);
};
export default App;
| components/tabs/demo/custom-add-trigger.tsx | 1 | https://github.com/ant-design/ant-design/commit/546bda457f3724092edd01f8778d738deecc95de | [
0.9989182949066162,
0.6331292986869812,
0.00016613521438557655,
0.9004927277565002,
0.4499083161354065
] |
{
"id": 0,
"code_window": [
"import React, { useRef, useState } from 'react';\n",
"import { Button, Tabs } from 'antd';\n",
"\n",
"const defaultPanes = new Array(2).fill(null).map((_, index) => {\n",
" const id = String(index + 1);\n",
" return { label: `Tab ${id}`, children: `Content of Tab Pane ${index + 1}`, key: id };\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"type TargetKey = React.MouseEvent | React.KeyboardEvent | string;\n",
"\n"
],
"file_path": "components/tabs/demo/custom-add-trigger.tsx",
"type": "add",
"edit_start_line_idx": 3
} | ---
order: 10
title: 国际化
---
`antd` 目前的默认文案是英文,如果需要使用其他语言,可以参考下面的方案。
## ConfigProvider
antd 提供了一个 React 组件 [ConfigProvider](/components/config-provider-cn) 用于全局配置国际化文案。
```jsx
import zhCN from 'antd/locale/zh_CN';
return (
<ConfigProvider locale={zhCN}>
<App />
</ConfigProvider>
);
```
详细配置见:[ConfigProvider](/components/config-provider)。
注意:`zh_CN` 是文件名,以下表格也遵循同样的规则。
目前支持以下语言:
| 语言 | 文件名 |
| -------------------- | ------ |
| 阿拉伯语 | ar_EG |
| 阿塞拜疆语 | az_AZ |
| 保加利亚语 | bg_BG |
| 孟加拉语(孟加拉国) | bn_BD |
| 白俄罗斯语 | by_BY |
| 加泰罗尼亚语 | ca_ES |
| 捷克语 | cs_CZ |
| 丹麦语 | da_DK |
| 德语 | de_DE |
| 希腊语 | el_GR |
| 英语 | en_GB |
| 英语(美式) | en_US |
| 西班牙语 | es_ES |
| 巴斯克语 | eu_ES |
| 爱沙尼亚语 | et_EE |
| 波斯语 | fa_IR |
| 芬兰语 | fi_FI |
| 法语(比利时) | fr_BE |
| 法语(加拿大) | fr_CA |
| 法语(法国) | fr_FR |
| 爱尔兰语 | ga_IE |
| 加利西亚语(西班牙) | gl_ES |
| 希伯来语 | he_IL |
| 印地语 | hi_IN |
| 克罗地亚语 | hr_HR |
| 匈牙利语 | hu_HU |
| 亚美尼亚 | hy_AM |
| 印度尼西亚语 | id_ID |
| 意大利语 | it_IT |
| 冰岛语 | is_IS |
| 日语 | ja_JP |
| 格鲁吉亚语 | ka_GE |
| 高棉语 | km_KH |
| 北库尔德语 | kmr_IQ |
| 卡纳达语 | kn_IN |
| 哈萨克语 | kk_KZ |
| 韩语/朝鲜语 | ko_KR |
| 立陶宛语 | lt_LT |
| 拉脱维亚语 | lv_LV |
| 马其顿语 | mk_MK |
| 马拉雅拉姆语 | ml_IN |
| 蒙古语 | mn_MN |
| 马来语 (马来西亚) | ms_MY |
| 挪威语 | nb_NO |
| 尼泊尔语 | ne_NP |
| 荷兰语(比利时) | nl_BE |
| 荷兰语 | nl_NL |
| 波兰语 | pl_PL |
| 葡萄牙语(巴西) | pt_BR |
| 葡萄牙语 | pt_PT |
| 罗马尼亚语 | ro_RO |
| 俄罗斯语 | ru_RU |
| 僧伽罗语 | si_LK |
| 斯洛伐克语 | sk_SK |
| 塞尔维亚语 | sr_RS |
| 斯洛文尼亚语 | sl_SI |
| 瑞典语 | sv_SE |
| 泰米尔语 | ta_IN |
| 泰语 | th_TH |
| 土耳其语 | tr_TR |
| 土库曼 | tk_TK |
| 乌尔都语 (巴基斯坦) | ur_PK |
| 乌克兰语 | uk_UA |
| 越南语 | vi_VN |
| 简体中文 | zh_CN |
| 繁体中文(中国香港) | zh_HK |
| 繁体中文(中国台湾) | zh_TW |
具体的使用方法请参考 [ConfigProvider 文档](/components/config-provider-cn)。
## 增加语言包
如果你找不到你需要的语言包,欢迎你在 [英文语言包](https://github.com/ant-design/ant-design/blob/master/components/locale/en_US.tsx) 的基础上创建一个新的语言包,并给我们发一个 Pull Request,可以参考 [阿塞拜疆语的 PR](https://github.com/ant-design/ant-design/pull/21387)。
基本步骤如下:
1. Fork `antd` 并 git clone 到本地,切换到 `feature` 分支,执行一次拉取确保最新,基于 `feature` 分支切换一个新分支,以下工作将在新分支完成。
```bash
git clone [email protected]:<your organization>/ant-design.git
cd ant-design/
git remote add upstream origin [email protected]:ant-design/ant-design.git
git checkout -b <your new branch name>
```
2. 为 [rc-picker](https://github.com/react-component/picker) 添加对应语言,参考 [这个](https://github.com/react-component/picker/blob/master/src/locale/en_US.ts)。
3. 为 [rc-pagination](https://github.com/react-component/pagination) 添加对应语言,参考 [这个](https://github.com/react-component/pagination/blob/master/src/locale/en_US.js)。
4. 等待 `rc-picker` 和 `rc-pagination` 发布含上述内容的最低版本。
5. 参考 [阿塞拜疆语的 PR](https://github.com/ant-design/ant-design/pull/21387) 向 `antd` 发起 PR,完善对应语言的其他内容和更新 `rc-picker` 和 `rc-pagination` 版本。
6. 在 [index.test.tsx](https://github.com/ant-design/ant-design/blob/master/components/locale-provider/__tests__/index.test.tsx) 添加该语言的测试用例。
7. 更新 snapshot,在这之前或许你还需要先删除 `node_modules` 和 lock 文件 (`yarn.lock` or `package-lock.json`) 并全新安装。
```bash
npm run test -- components/locale -u
```
8. 更新 [docs/react/i18n.zh-CN.md](https://github.com/ant-design/ant-design/blob/master/docs/react/i18n.zh-CN.md) 和 [docs/react/i18n.zh-CN.md](https://github.com/ant-design/ant-design/blob/master/docs/react/i18n.zh-CN.md),将对应语言添加到文档列表。
9. 观察 CI 是否通过,若未通过,根据日志进行修改直至通过。
10. 万事俱备等待 review 。
## i18n 项目示例
你可以参考 [Ant Design Pro 国际化文档](https://pro.ant.design/docs/i18n-cn) 查看完整的国际化项目示例。
| docs/react/i18n.zh-CN.md | 0 | https://github.com/ant-design/ant-design/commit/546bda457f3724092edd01f8778d738deecc95de | [
0.00017944650608114898,
0.0001722698361845687,
0.00016398033767472953,
0.00017383878002874553,
0.000004592799086822197
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.