hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 0, "code_window": [ " return matchContext.router\n", " }\n", "\n", " const { history } = this.props\n", " const router = createRouterObject(history, this.transitionManager)\n", "\n", " return {\n", " ...router,\n", " location: state.location,\n", " params: state.params\n", " }\n", " },\n", "\n", " createTransitionManager() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " return createRouterObject(history, this.transitionManager, state)\n" ], "file_path": "modules/Router.js", "type": "replace", "edit_start_line_idx": 64 }
import React, { Component } from 'react' import { Link } from 'react-router' const dark = 'hsl(200, 20%, 20%)' const light = '#fff' const styles = {} styles.wrapper = { padding: '10px 20px', overflow: 'hidden', background: dark, color: light } styles.link = { padding: 11, color: light, fontWeight: 200 } styles.activeLink = { ...styles.link, background: light, color: dark } class GlobalNav extends Component { constructor(props, context) { super(props, context) this.logOut = this.logOut.bind(this) } logOut() { alert('log out') } render() { const { user } = this.props return ( <div style={styles.wrapper}> <div style={{ float: 'left' }}> <Link to="/" style={styles.link}>Home</Link>{' '} <Link to="/calendar" style={styles.link} activeStyle={styles.activeLink}>Calendar</Link>{' '} <Link to="/grades" style={styles.link} activeStyle={styles.activeLink}>Grades</Link>{' '} <Link to="/messages" style={styles.link} activeStyle={styles.activeLink}>Messages</Link>{' '} </div> <div style={{ float: 'right' }}> <Link style={styles.link} to="/profile">{user.name}</Link> <button onClick={this.logOut}>log out</button> </div> </div> ) } } GlobalNav.defaultProps = { user: { id: 1, name: 'Ryan Florence' } } export default GlobalNav
examples/huge-apps/components/GlobalNav.js
0
https://github.com/remix-run/react-router/commit/a76efddfa20945807a422ac88860b7108f0cf4d5
[ 0.0003817607357632369, 0.00020303497149143368, 0.00016714452067390084, 0.00017102158744819462, 0.00007332000677706674 ]
{ "id": 0, "code_window": [ " return matchContext.router\n", " }\n", "\n", " const { history } = this.props\n", " const router = createRouterObject(history, this.transitionManager)\n", "\n", " return {\n", " ...router,\n", " location: state.location,\n", " params: state.params\n", " }\n", " },\n", "\n", " createTransitionManager() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " return createRouterObject(history, this.transitionManager, state)\n" ], "file_path": "modules/Router.js", "type": "replace", "edit_start_line_idx": 64 }
<!doctype html public "embarassment"> <meta charset="utf-8"/> <base href="/huge-apps"/> <title>Huge Apps Example</title> <link href="/global.css" rel="stylesheet"/> <style> body { margin: 0; font-family: sans-serif; } a { color: hsl(200, 50%, 40%); text-decoration: none; } </style> <body> <div id="example"/> <script src="/__build__/shared.js"></script> <script src="/__build__/huge-apps.js"></script>
examples/huge-apps/index.html
0
https://github.com/remix-run/react-router/commit/a76efddfa20945807a422ac88860b7108f0cf4d5
[ 0.00036670698318630457, 0.00023664248874410987, 0.00017119600670412183, 0.00017202449089381844, 0.0000919701051316224 ]
{ "id": 1, "code_window": [ "export function createRouterObject(history, transitionManager) {\n", " return {\n", " ...history,\n", " setRouteLeaveHook: transitionManager.listenBeforeLeavingRoute,\n" ], "labels": [ "replace", "keep", "keep", "keep" ], "after_edit": [ "export function createRouterObject(history, transitionManager, state) {\n" ], "file_path": "modules/RouterUtils.js", "type": "replace", "edit_start_line_idx": 0 }
import invariant from 'invariant' import createMemoryHistory from './createMemoryHistory' import createTransitionManager from './createTransitionManager' import { createRoutes } from './RouteUtils' import { createRouterObject } from './RouterUtils' /** * A high-level API to be used for server-side rendering. * * This function matches a location to a set of routes and calls * callback(error, redirectLocation, renderProps) when finished. * * Note: You probably don't want to use this in a browser unless you're using * server-side rendering with async routes. */ function match({ history, routes, location, ...options }, callback) { invariant( history || location, 'match needs a history or a location' ) history = history ? history : createMemoryHistory(options) const transitionManager = createTransitionManager( history, createRoutes(routes) ) let unlisten if (location) { // Allow match({ location: '/the/path', ... }) location = history.createLocation(location) } else { // Pick up the location from the history via synchronous history.listen // call if needed. unlisten = history.listen(historyLocation => { location = historyLocation }) } transitionManager.match(location, function (error, redirectLocation, nextState) { let renderProps if (nextState) { const router = { ...createRouterObject(history, transitionManager), location: nextState.location, params: nextState.params } renderProps = { ...nextState, router, matchContext: { transitionManager, router } } } callback(error, redirectLocation, renderProps) // Defer removing the listener to here to prevent DOM histories from having // to unwind DOM event listeners unnecessarily, in case callback renders a // <Router> and attaches another history listener. if (unlisten) { unlisten() } }) } export default match
modules/match.js
1
https://github.com/remix-run/react-router/commit/a76efddfa20945807a422ac88860b7108f0cf4d5
[ 0.9992326498031616, 0.36426371335983276, 0.00017544034926686436, 0.006337522529065609, 0.4669712781906128 ]
{ "id": 1, "code_window": [ "export function createRouterObject(history, transitionManager) {\n", " return {\n", " ...history,\n", " setRouteLeaveHook: transitionManager.listenBeforeLeavingRoute,\n" ], "labels": [ "replace", "keep", "keep", "keep" ], "after_edit": [ "export function createRouterObject(history, transitionManager, state) {\n" ], "file_path": "modules/RouterUtils.js", "type": "replace", "edit_start_line_idx": 0 }
# Contributor Code of Conduct As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery * Personal attacks * Trolling or insulting/derogatory comments * Public or private harassment * Publishing other's private information, such as physical or electronic addresses, without explicit permission * Other unethical or unprofessional conduct Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team. This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting a project maintainer at [email protected]. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. Maintainers are obligated to maintain confidentiality with regard to the reporter of an incident. This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.3.0, available at [http://contributor-covenant.org/version/1/3/0/][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/3/0/
CODE_OF_CONDUCT.md
0
https://github.com/remix-run/react-router/commit/a76efddfa20945807a422ac88860b7108f0cf4d5
[ 0.00017544034926686436, 0.00017059739911928773, 0.00016608597070444375, 0.00017041196406353265, 0.000003203344931534957 ]
{ "id": 1, "code_window": [ "export function createRouterObject(history, transitionManager) {\n", " return {\n", " ...history,\n", " setRouteLeaveHook: transitionManager.listenBeforeLeavingRoute,\n" ], "labels": [ "replace", "keep", "keep", "keep" ], "after_edit": [ "export function createRouterObject(history, transitionManager, state) {\n" ], "file_path": "modules/RouterUtils.js", "type": "replace", "edit_start_line_idx": 0 }
module.exports = { path: ':assignmentId', getComponent(nextState, cb) { require.ensure([], (require) => { cb(null, require('./components/Assignment')) }) } }
examples/huge-apps/routes/Course/routes/Assignments/routes/Assignment/index.js
0
https://github.com/remix-run/react-router/commit/a76efddfa20945807a422ac88860b7108f0cf4d5
[ 0.00017012980242725462, 0.00017012980242725462, 0.00017012980242725462, 0.00017012980242725462, 0 ]
{ "id": 1, "code_window": [ "export function createRouterObject(history, transitionManager) {\n", " return {\n", " ...history,\n", " setRouteLeaveHook: transitionManager.listenBeforeLeavingRoute,\n" ], "labels": [ "replace", "keep", "keep", "keep" ], "after_edit": [ "export function createRouterObject(history, transitionManager, state) {\n" ], "file_path": "modules/RouterUtils.js", "type": "replace", "edit_start_line_idx": 0 }
module.exports = { path: 'profile', getComponent(nextState, cb) { require.ensure([], (require) => { cb(null, require('./components/Profile')) }) } }
examples/huge-apps/routes/Profile/index.js
0
https://github.com/remix-run/react-router/commit/a76efddfa20945807a422ac88860b7108f0cf4d5
[ 0.00017202776507474482, 0.00017202776507474482, 0.00017202776507474482, 0.00017202776507474482, 0 ]
{ "id": 2, "code_window": [ " return {\n", " ...history,\n", " setRouteLeaveHook: transitionManager.listenBeforeLeavingRoute,\n", " isActive: transitionManager.isActive\n", " }\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " isActive: transitionManager.isActive,\n", " location: state.location,\n", " params: state.params\n" ], "file_path": "modules/RouterUtils.js", "type": "replace", "edit_start_line_idx": 4 }
export function createRouterObject(history, transitionManager) { return { ...history, setRouteLeaveHook: transitionManager.listenBeforeLeavingRoute, isActive: transitionManager.isActive } }
modules/RouterUtils.js
1
https://github.com/remix-run/react-router/commit/a76efddfa20945807a422ac88860b7108f0cf4d5
[ 0.7809180617332458, 0.7809180617332458, 0.7809180617332458, 0.7809180617332458, 0 ]
{ "id": 2, "code_window": [ " return {\n", " ...history,\n", " setRouteLeaveHook: transitionManager.listenBeforeLeavingRoute,\n", " isActive: transitionManager.isActive\n", " }\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " isActive: transitionManager.isActive,\n", " location: state.location,\n", " params: state.params\n" ], "file_path": "modules/RouterUtils.js", "type": "replace", "edit_start_line_idx": 4 }
import React, { Component } from 'react' import { Link } from 'react-router' const dark = 'hsl(200, 20%, 20%)' const light = '#fff' const styles = {} styles.wrapper = { padding: '10px 20px', overflow: 'hidden', background: dark, color: light } styles.link = { padding: 11, color: light, fontWeight: 200 } styles.activeLink = { ...styles.link, background: light, color: dark } class GlobalNav extends Component { constructor(props, context) { super(props, context) this.logOut = this.logOut.bind(this) } logOut() { alert('log out') } render() { const { user } = this.props return ( <div style={styles.wrapper}> <div style={{ float: 'left' }}> <Link to="/" style={styles.link}>Home</Link>{' '} <Link to="/calendar" style={styles.link} activeStyle={styles.activeLink}>Calendar</Link>{' '} <Link to="/grades" style={styles.link} activeStyle={styles.activeLink}>Grades</Link>{' '} <Link to="/messages" style={styles.link} activeStyle={styles.activeLink}>Messages</Link>{' '} </div> <div style={{ float: 'right' }}> <Link style={styles.link} to="/profile">{user.name}</Link> <button onClick={this.logOut}>log out</button> </div> </div> ) } } GlobalNav.defaultProps = { user: { id: 1, name: 'Ryan Florence' } } export default GlobalNav
examples/huge-apps/components/GlobalNav.js
0
https://github.com/remix-run/react-router/commit/a76efddfa20945807a422ac88860b7108f0cf4d5
[ 0.0001733113022055477, 0.00017159132403321564, 0.00016923702787607908, 0.00017202398157678545, 0.000001600465907358739 ]
{ "id": 2, "code_window": [ " return {\n", " ...history,\n", " setRouteLeaveHook: transitionManager.listenBeforeLeavingRoute,\n", " isActive: transitionManager.isActive\n", " }\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " isActive: transitionManager.isActive,\n", " location: state.location,\n", " params: state.params\n" ], "file_path": "modules/RouterUtils.js", "type": "replace", "edit_start_line_idx": 4 }
import { matchPattern } from './PatternUtils' function deepEqual(a, b) { if (a == b) return true if (a == null || b == null) return false if (Array.isArray(a)) { return ( Array.isArray(b) && a.length === b.length && a.every((item, index) => deepEqual(item, b[index])) ) } if (typeof a === 'object') { for (let p in a) { if (!Object.prototype.hasOwnProperty.call(a, p)) { continue } if (a[p] === undefined) { if (b[p] !== undefined) { return false } } else if (!Object.prototype.hasOwnProperty.call(b, p)) { return false } else if (!deepEqual(a[p], b[p])) { return false } } return true } return String(a) === String(b) } /** * Returns true if the current pathname matches the supplied one, net of * leading and trailing slash normalization. This is sufficient for an * indexOnly route match. */ function pathIsActive(pathname, currentPathname) { // Normalize leading slash for consistency. Leading slash on pathname has // already been normalized in isActive. See caveat there. if (currentPathname.charAt(0) !== '/') { currentPathname = `/${currentPathname}` } // Normalize the end of both path names too. Maybe `/foo/` shouldn't show // `/foo` as active, but in this case, we would already have failed the // match. if (pathname.charAt(pathname.length - 1) !== '/') { pathname += '/' } if (currentPathname.charAt(currentPathname.length - 1) !== '/') { currentPathname += '/' } return currentPathname === pathname } /** * Returns true if the given pathname matches the active routes and params. */ function routeIsActive(pathname, routes, params) { let remainingPathname = pathname, paramNames = [], paramValues = [] // for...of would work here but it's probably slower post-transpilation. for (let i = 0, len = routes.length; i < len; ++i) { const route = routes[i] const pattern = route.path || '' if (pattern.charAt(0) === '/') { remainingPathname = pathname paramNames = [] paramValues = [] } if (remainingPathname !== null && pattern) { const matched = matchPattern(pattern, remainingPathname) if (matched) { remainingPathname = matched.remainingPathname paramNames = [ ...paramNames, ...matched.paramNames ] paramValues = [ ...paramValues, ...matched.paramValues ] } else { remainingPathname = null } if (remainingPathname === '') { // We have an exact match on the route. Just check that all the params // match. // FIXME: This doesn't work on repeated params. return paramNames.every((paramName, index) => ( String(paramValues[index]) === String(params[paramName]) )) } } } return false } /** * Returns true if all key/value pairs in the given query are * currently active. */ function queryIsActive(query, activeQuery) { if (activeQuery == null) return query == null if (query == null) return true return deepEqual(query, activeQuery) } /** * Returns true if a <Link> to the given pathname/query combination is * currently active. */ export default function isActive( { pathname, query }, indexOnly, currentLocation, routes, params ) { if (currentLocation == null) return false // TODO: This is a bit ugly. It keeps around support for treating pathnames // without preceding slashes as absolute paths, but possibly also works // around the same quirks with basenames as in matchRoutes. if (pathname.charAt(0) !== '/') { pathname = `/${pathname}` } if (!pathIsActive(pathname, currentLocation.pathname)) { // The path check is necessary and sufficient for indexOnly, but otherwise // we still need to check the routes. if (indexOnly || !routeIsActive(pathname, routes, params)) { return false } } return queryIsActive(query, currentLocation.query) }
modules/isActive.js
0
https://github.com/remix-run/react-router/commit/a76efddfa20945807a422ac88860b7108f0cf4d5
[ 0.006551751866936684, 0.000692611385602504, 0.0001644842850510031, 0.00016947441326919943, 0.0015884079039096832 ]
{ "id": 2, "code_window": [ " return {\n", " ...history,\n", " setRouteLeaveHook: transitionManager.listenBeforeLeavingRoute,\n", " isActive: transitionManager.isActive\n", " }\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " isActive: transitionManager.isActive,\n", " location: state.location,\n", " params: state.params\n" ], "file_path": "modules/RouterUtils.js", "type": "replace", "edit_start_line_idx": 4 }
# Glossary This is a glossary of common terms used in the React Router codebase and documentation listed in alphabetical order, along with their [type signatures](http://flowtype.org/docs/quick-reference.html). * [Action](#action) * [Component](#component) * [EnterHook](#enterhook) * [Hash](#hash) * [LeaveHook](#leavehook) * [Location](#location) * [LocationDescriptor](#locationdescriptor) * [LocationKey](#locationkey) * [LocationState](#locationstate) * [Path](#path) * [Pathname](#pathname) * [Params](#params) * [Query](#query) * [QueryString](#querystring) * [RedirectFunction](#redirectfunction) * [Route](#route) * [RouteComponent](#routecomponent) * [RouteConfig](#routeconfig) * [RouteHook](#routehook) * [RoutePattern](#routepattern) * [Router](#router) * [RouterState](#routerstate) ## Action ```js type Action = 'PUSH' | 'REPLACE' | 'POP'; ``` An *action* describes the type of change to a URL. Possible values are: - `PUSH` – indicates a new item was added to the history - `REPLACE` – indicates the current item in history was altered - `POP` – indicates there is a new current item, i.e. the "current pointer" changed ## Component ```js type Component = ReactClass | string; ``` A *component* is a React component class or a string (e.g. "div"). Basically, it's anything that can be used as the first argument to [`React.createElement`](https://facebook.github.io/react/docs/top-level-api.html#react.createelement). ## EnterHook ```js type EnterHook = (nextState: RouterState, replace: RedirectFunction, callback?: Function) => any; ``` An *enter hook* is a user-defined function that is called when a route is about to be rendered. It receives the next [router state](#routerstate) as its first argument. The [`replace` function](#redirectfunction) may be used to trigger a transition to a different URL. If an enter hook needs to execute asynchronously, it may list a 3rd `callback` argument that it must call in order to cause the transition to proceed. **Caution:** Using the `callback` in an enter hook causes the transition to wait until it is called. **This can lead to a non-responsive UI if you don't call it very quickly**. ### Hash type Hash = string; A *hash* is a string that represents the hash portion of the URL. It is synonymous with `window.location.hash` in web browsers. ## LeaveHook ```js type LeaveHook = () => any; ``` A *leave hook* is a user-defined function that is called when a route is about to be unmounted. ## Location ```js type Location = { pathname: Pathname; search: QueryString; query: Query; state: LocationState; action: Action; key: LocationKey; }; ``` A *location* answers two important (philosophical) questions: - Where am I? - How did I get here? New locations are typically created each time the URL changes. You can read more about locations in [the `history` docs](https://github.com/reactjs/history/blob/master/docs/Location.md). ### LocationDescriptor type LocationDescriptorObject = { pathname: Pathname; search: Search; query: Query; state: LocationState; }; type LocationDescriptor = LocationDescriptorObject | Path; A *location descriptor* is the pushable analogue of a location. Locations tell you where you are; you create location descriptors to say where to go. You can read more about location descriptors in [the `history` docs](https://github.com/reactjs/history/blob/master/docs/Location.md). ## LocationKey ```js type LocationKey = string; ``` A *location key* is a string that is unique to a particular [`location`](#location). It is the one piece of data that most accurately answers the question "Where am I?". ## LocationState ```js type LocationState = ?Object; ``` A *location state* is an arbitrary object of data associated with a particular [`location`](#location). This is basically a way to tie extra state to a location that is not contained in the URL. This type gets its name from the first argument to HTML5's [`pushState`][pushState] and [`replaceState`][replaceState] methods. [pushState]: https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method [replaceState]: https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_replaceState()_method ## Path ```js type Path = Pathname + QueryString + Hash; ``` A *path* represents a URL path. ## Pathname ```js type Pathname = string; ``` A *pathname* is the portion of a URL that describes a hierarchical path, including the preceding `/`. For example, in `http://example.com/the/path?the=query`, `/the/path` is the pathname. It is synonymous with `window.location.pathname` in web browsers. ## QueryString ```js type QueryString = string; ``` A *query string* is the portion of the URL that follows the [pathname](#pathname), including any preceding `?`. For example, in `http://example.com/the/path?the=query`, `?the=query` is the query string. It is synonymous with `window.location.search` in web browsers. ## Query ```js type Query = Object; ``` A *query* is the parsed version of a [query string](#querystring). ## Params ```js type Params = Object; ``` The word *params* refers to an object of key/value pairs that were parsed out of the original URL's [pathname](#pathname). The values of this object are typically strings, unless there is more than one param with the same name in which case the value is an array. ## RedirectFunction ```js type RedirectFunction = (state: ?LocationState, pathname: Pathname | Path, query: ?Query) => void; ``` A *redirect function* is used in [`onEnter` hooks](#enterhook) to trigger a transition to a new URL. ## Route ```js type Route = { component: RouteComponent; path: ?RoutePattern; onEnter: ?EnterHook; onLeave: ?LeaveHook; }; ``` A *route* specifies a [component](#component) that is part of the user interface (UI). Routes should be nested in a tree-like structure that follows the hierarchy of your components. It may help to think of a route as an "entry point" into your UI. You don't need a route for every component in your component hierarchy, only for those places where your UI differs based on the URL. ## RouteComponent ```js type RouteComponent = Component; ``` The term *route component* refers to a [component](#component) that is directly rendered by a [route](#route) (i.e. the `<Route component>`). The router creates elements from route components and provides them as `this.props.children` to route components further up the hierarchy. In addition to `children`, route components receive the following props: - `router` – The [router](#router) instance - `location` – The current [location](#location) - `params` – The current [params](#params) - `route` – The [route](#route) that declared this component - `routeParams` – A subset of the [params](#params) that were specified in the route's [`path`](#routepattern) ## RouteConfig ```js type RouteConfig = Array<Route>; ``` A *route config* is an array of [route](#route)s that specifies the order in which routes should be tried when the router attempts to match a URL. ## RouteHook ```js type RouteHook = (nextLocation?: Location) => any; ``` A *route hook* is a function that is used to prevent the user from leaving a route. On normal transitions, it receives the next [location](#location) as an argument and must either `return false` to cancel the transition or `return` a prompt message to show the user. When invoked during the `beforeunload` event in web browsers, it does not receive any arguments and must `return` a prompt message to cancel the transition. ## RoutePattern ```js type RoutePattern = string; ``` A *route pattern* (or "path") is a string that describes a portion of a URL. Patterns are compiled into functions that are used to try and match a URL. Patterns may use the following special characters: - `:paramName` – matches a URL segment up to the next `/`, `?`, or `#`. The matched string is called a [param](#params) - `()` – Wraps a portion of the URL that is optional - `*` – Matches all characters (non-greedy) up to the next character in the pattern, or to the end of the URL if there is none, and creates a `splat` [param](#params) - `**` - Matches all characters (greedy) until the next `/`, `?`, or `#` and creates a `splat` [param](#params) Route patterns are relative to the pattern of the parent route unless they begin with a `/`, in which case they begin matching at the beginning of the URL. ## Router ```js type Router = { push(location: LocationDescriptor) => void; replace(location: LocationDescriptor) => void; go(n: number) => void; goBack() => void; goForward() => void; setRouteLeaveHook(hook: RouteHook) => Function; isActive(location: LocationDescriptor, indexOnly: boolean) => void; }; ``` A *router* object allows for procedural manipulation of the routing state. ## RouterState ```js type RouterState = { location: Location; routes: Array<Route>; params: Params; components: Array<Component>; }; ``` A *router state* represents the current state of a router. It contains: - the current [`location`](#location), - an array of [`routes`](#route) that match that location, - an object of [`params`](#params) that were parsed out of the URL, and - an array of [`components`](#component) that will be rendered to the page in hierarchical order.
docs/Glossary.md
0
https://github.com/remix-run/react-router/commit/a76efddfa20945807a422ac88860b7108f0cf4d5
[ 0.011850317008793354, 0.0008111320785246789, 0.00016311842773575336, 0.0001702399895293638, 0.0022094619926065207 ]
{ "id": 3, "code_window": [ " listenBeforeLeavingRoute: expect.createSpy().andReturn(listenBeforeLeavingRouteSentinel),\n", " isActive: expect.createSpy().andReturn(isActiveSentinel)\n", " }\n", "\n", " router = createRouterObject(history, transitionManager)\n", "\n", " class Component extends React.Component {\n", " constructor(props, ctx) {\n", " super(props, ctx)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " router = createRouterObject(history, transitionManager, {})\n" ], "file_path": "modules/__tests__/RouterContext-test.js", "type": "replace", "edit_start_line_idx": 33 }
export function createRouterObject(history, transitionManager) { return { ...history, setRouteLeaveHook: transitionManager.listenBeforeLeavingRoute, isActive: transitionManager.isActive } }
modules/RouterUtils.js
1
https://github.com/remix-run/react-router/commit/a76efddfa20945807a422ac88860b7108f0cf4d5
[ 0.0015764071140438318, 0.0015764071140438318, 0.0015764071140438318, 0.0015764071140438318, 0 ]
{ "id": 3, "code_window": [ " listenBeforeLeavingRoute: expect.createSpy().andReturn(listenBeforeLeavingRouteSentinel),\n", " isActive: expect.createSpy().andReturn(isActiveSentinel)\n", " }\n", "\n", " router = createRouterObject(history, transitionManager)\n", "\n", " class Component extends React.Component {\n", " constructor(props, ctx) {\n", " super(props, ctx)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " router = createRouterObject(history, transitionManager, {})\n" ], "file_path": "modules/__tests__/RouterContext-test.js", "type": "replace", "edit_start_line_idx": 33 }
# Contributor Code of Conduct As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery * Personal attacks * Trolling or insulting/derogatory comments * Public or private harassment * Publishing other's private information, such as physical or electronic addresses, without explicit permission * Other unethical or unprofessional conduct Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team. This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting a project maintainer at [email protected]. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. Maintainers are obligated to maintain confidentiality with regard to the reporter of an incident. This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.3.0, available at [http://contributor-covenant.org/version/1/3/0/][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/3/0/
CODE_OF_CONDUCT.md
0
https://github.com/remix-run/react-router/commit/a76efddfa20945807a422ac88860b7108f0cf4d5
[ 0.000176393921719864, 0.00017326655506622046, 0.00016738615522626787, 0.00017398314957972616, 0.000003207076360922656 ]
{ "id": 3, "code_window": [ " listenBeforeLeavingRoute: expect.createSpy().andReturn(listenBeforeLeavingRouteSentinel),\n", " isActive: expect.createSpy().andReturn(isActiveSentinel)\n", " }\n", "\n", " router = createRouterObject(history, transitionManager)\n", "\n", " class Component extends React.Component {\n", " constructor(props, ctx) {\n", " super(props, ctx)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " router = createRouterObject(history, transitionManager, {})\n" ], "file_path": "modules/__tests__/RouterContext-test.js", "type": "replace", "edit_start_line_idx": 33 }
# Introduction React Router is a powerful routing library built on top of [React](http://facebook.github.io/react/) that helps you add new screens and flows to your application incredibly quickly, all while keeping the URL in sync with what's being displayed on the page. To illustrate the problems React Router is going to solve for you, let's build a small application without it. We will be using [ES6/ES2015 syntax and language features](https://github.com/lukehoban/es6features#readme) throughout the documentation for any example code. ### Without React Router ```js import React from 'react' import { render } from 'react-dom' const About = React.createClass({/*...*/}) const Inbox = React.createClass({/*...*/}) const Home = React.createClass({/*...*/}) const App = React.createClass({ getInitialState() { return { route: window.location.hash.substr(1) } }, componentDidMount() { window.addEventListener('hashchange', () => { this.setState({ route: window.location.hash.substr(1) }) }) }, render() { let Child switch (this.state.route) { case '/about': Child = About; break; case '/inbox': Child = Inbox; break; default: Child = Home; } return ( <div> <h1>App</h1> <ul> <li><a href="#/about">About</a></li> <li><a href="#/inbox">Inbox</a></li> </ul> <Child/> </div> ) } }) render(<App />, document.body) ``` As the hash portion of the URL changes, `<App>` will render a different `<Child>` by branching on `this.state.route`. Pretty straightforward stuff. But it gets complicated fast. Imagine now that `Inbox` has some nested UI at different URLs, maybe something like this master detail view: ``` path: /inbox/messages/1234 +---------+------------+------------------------+ | About | Inbox | | +---------+ +------------------------+ | Compose Reply Reply All Archive | +-----------------------------------------------+ |Movie tomorrow| | +--------------+ Subject: TPS Report | |TPS Report From: [email protected] | +--------------+ | |New Pull Reque| So ... | +--------------+ | |... | | +--------------+--------------------------------+ ``` And maybe a stats page when not viewing a message: ``` path: /inbox +---------+------------+------------------------+ | About | Inbox | | +---------+ +------------------------+ | Compose Reply Reply All Archive | +-----------------------------------------------+ |Movie tomorrow| | +--------------+ 10 Unread Messages | |TPS Report | 22 drafts | +--------------+ | |New Pull Reque| | +--------------+ | |... | | +--------------+--------------------------------+ ``` We'd have to make our URL parsing a lot smarter, and we would end up with a lot of code to figure out which branch of nested components to be rendered at any given URL: `App -> About`, `App -> Inbox -> Messages -> Message`, `App -> Inbox -> Messages -> Stats`, etc. ### With React Router Let's refactor our app to use React Router. ```js import React from 'react' import { render } from 'react-dom' // First we import some modules... import { Router, Route, IndexRoute, Link, hashHistory } from 'react-router' // Then we delete a bunch of code from App and // add some <Link> elements... const App = React.createClass({ render() { return ( <div> <h1>App</h1> {/* change the <a>s to <Link>s */} <ul> <li><Link to="/about">About</Link></li> <li><Link to="/inbox">Inbox</Link></li> </ul> {/* next we replace `<Child>` with `this.props.children` the router will figure out the children for us */} {this.props.children} </div> ) } }) // Finally, we render a <Router> with some <Route>s. // It does all the fancy routing stuff for us. render(( <Router history={hashHistory}> <Route path="/" component={App}> <IndexRoute component={Home} /> <Route path="about" component={About} /> <Route path="inbox" component={Inbox} /> </Route> </Router> ), document.body) ``` React Router knows how to build nested UI for us, so we don't have to manually figure out which `<Child>` component to render. For example, for a full path `/about` it would build `<App><About /></App>`. Internally, the router converts your `<Route>` element hierarchy to a [route config](/docs/Glossary.md#routeconfig). But if you're not digging the JSX you can use plain objects instead: ```js const routes = { path: '/', component: App, indexRoute: { component: Home }, childRoutes: [ { path: 'about', component: About }, { path: 'inbox', component: Inbox }, ] } render(<Router history={history} routes={routes} />, document.body) ``` ## Adding More UI Alright, now we're ready to nest the inbox messages inside the inbox UI. ```js // Make a new component to render inside of Inbox const Message = React.createClass({ render() { return <h3>Message</h3> } }) const Inbox = React.createClass({ render() { return ( <div> <h2>Inbox</h2> {/* Render the child route component */} {this.props.children} </div> ) } }) render(( <Router history={history}> <Route path="/" component={App}> <IndexRoute component={Home} /> <Route path="about" component={About} /> <Route path="inbox" component={Inbox}> {/* add some nested routes where we want the UI to nest */} {/* render the stats page when at `/inbox` */} <IndexRoute component={InboxStats}/> {/* render the message component at /inbox/messages/123 */} <Route path="messages/:id" component={Message} /> </Route> </Route> </Router> ), document.body) ``` Now visits to URLs like `inbox/messages/Jkei3c32` will match the new route and build this for you: ``` <App> <Inbox> <Message params={{ id: 'Jkei3c32' }}/> </Inbox> </App> ``` And visits to `/inbox` will build this: ``` <App> <Inbox> <InboxStats/> </Inbox> </App> ``` ### Getting URL Parameters We're going to need to know something about the message in order to fetch it from the server. Route components get some useful properties injected into them when you render, particularly the parameters from the dynamic segment of your path. In our case, `:id`. ```js const Message = React.createClass({ componentDidMount() { // from the path `/inbox/messages/:id` const id = this.props.params.id fetchMessage(id, function (err, message) { this.setState({ message: message }) }) }, // ... }) ``` You can also access parameters from the query string. For instance, if you're on `/foo?bar=baz`, you can access `this.props.location.query.bar` to get the value `"baz"` from your Route component. That's the gist of React Router. Application UIs are boxes inside of boxes inside of boxes; now you can keep those boxes in sync with the URL and link to them easily. The docs about [route configuration](/docs/guides/RouteConfiguration.md) describe more of the router's features in depth.
docs/Introduction.md
0
https://github.com/remix-run/react-router/commit/a76efddfa20945807a422ac88860b7108f0cf4d5
[ 0.003572092391550541, 0.0004055393219459802, 0.00016255929949693382, 0.0001739199215080589, 0.0006963016930967569 ]
{ "id": 3, "code_window": [ " listenBeforeLeavingRoute: expect.createSpy().andReturn(listenBeforeLeavingRouteSentinel),\n", " isActive: expect.createSpy().andReturn(isActiveSentinel)\n", " }\n", "\n", " router = createRouterObject(history, transitionManager)\n", "\n", " class Component extends React.Component {\n", " constructor(props, ctx) {\n", " super(props, ctx)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " router = createRouterObject(history, transitionManager, {})\n" ], "file_path": "modules/__tests__/RouterContext-test.js", "type": "replace", "edit_start_line_idx": 33 }
import React from 'react' import { render } from 'react-dom' import { browserHistory, Router, Route, Link, routerShape } from 'react-router' import auth from './auth' const App = React.createClass({ getInitialState() { return { loggedIn: auth.loggedIn() } }, updateAuth(loggedIn) { this.setState({ loggedIn: loggedIn }) }, componentWillMount() { auth.onChange = this.updateAuth auth.login() }, render() { return ( <div> <ul> <li> {this.state.loggedIn ? ( <Link to="/logout">Log out</Link> ) : ( <Link to="/login">Sign in</Link> )} </li> <li><Link to="/about">About</Link></li> <li><Link to="/dashboard">Dashboard</Link> (authenticated)</li> </ul> {this.props.children || <p>You are {!this.state.loggedIn && 'not'} logged in.</p>} </div> ) } }) const Dashboard = React.createClass({ render() { const token = auth.getToken() return ( <div> <h1>Dashboard</h1> <p>You made it!</p> <p>{token}</p> </div> ) } }) const Login = React.createClass({ contextTypes: { router: routerShape.isRequired }, getInitialState() { return { error: false } }, handleSubmit(event) { event.preventDefault() const email = this.refs.email.value const pass = this.refs.pass.value auth.login(email, pass, (loggedIn) => { if (!loggedIn) return this.setState({ error: true }) const { location } = this.props if (location.state && location.state.nextPathname) { this.context.router.replace(location.state.nextPathname) } else { this.context.router.replace('/') } }) }, render() { return ( <form onSubmit={this.handleSubmit}> <label><input ref="email" placeholder="email" defaultValue="[email protected]" /></label> <label><input ref="pass" placeholder="password" /></label> (hint: password1)<br /> <button type="submit">login</button> {this.state.error && ( <p>Bad login information</p> )} </form> ) } }) const About = React.createClass({ render() { return <h1>About</h1> } }) const Logout = React.createClass({ componentDidMount() { auth.logout() }, render() { return <p>You are now logged out</p> } }) function requireAuth(nextState, replace) { if (!auth.loggedIn()) { replace({ pathname: '/login', state: { nextPathname: nextState.location.pathname } }) } } render(( <Router history={browserHistory}> <Route path="/" component={App}> <Route path="login" component={Login} /> <Route path="logout" component={Logout} /> <Route path="about" component={About} /> <Route path="dashboard" component={Dashboard} onEnter={requireAuth} /> </Route> </Router> ), document.getElementById('example'))
examples/auth-flow/app.js
0
https://github.com/remix-run/react-router/commit/a76efddfa20945807a422ac88860b7108f0cf4d5
[ 0.0004250180791132152, 0.00019981327932327986, 0.0001662337890593335, 0.0001730611256789416, 0.00007134603220038116 ]
{ "id": 4, "code_window": [ "\n", " transitionManager.match(location, function (error, redirectLocation, nextState) {\n", " let renderProps\n", "\n", " if (nextState) {\n", " const router = {\n", " ...createRouterObject(history, transitionManager),\n", " location: nextState.location,\n", " params: nextState.params\n", " }\n", "\n", " renderProps = {\n", " ...nextState,\n", " router,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " const router = createRouterObject(history, transitionManager, nextState)\n" ], "file_path": "modules/match.js", "type": "replace", "edit_start_line_idx": 45 }
import invariant from 'invariant' import createMemoryHistory from './createMemoryHistory' import createTransitionManager from './createTransitionManager' import { createRoutes } from './RouteUtils' import { createRouterObject } from './RouterUtils' /** * A high-level API to be used for server-side rendering. * * This function matches a location to a set of routes and calls * callback(error, redirectLocation, renderProps) when finished. * * Note: You probably don't want to use this in a browser unless you're using * server-side rendering with async routes. */ function match({ history, routes, location, ...options }, callback) { invariant( history || location, 'match needs a history or a location' ) history = history ? history : createMemoryHistory(options) const transitionManager = createTransitionManager( history, createRoutes(routes) ) let unlisten if (location) { // Allow match({ location: '/the/path', ... }) location = history.createLocation(location) } else { // Pick up the location from the history via synchronous history.listen // call if needed. unlisten = history.listen(historyLocation => { location = historyLocation }) } transitionManager.match(location, function (error, redirectLocation, nextState) { let renderProps if (nextState) { const router = { ...createRouterObject(history, transitionManager), location: nextState.location, params: nextState.params } renderProps = { ...nextState, router, matchContext: { transitionManager, router } } } callback(error, redirectLocation, renderProps) // Defer removing the listener to here to prevent DOM histories from having // to unwind DOM event listeners unnecessarily, in case callback renders a // <Router> and attaches another history listener. if (unlisten) { unlisten() } }) } export default match
modules/match.js
1
https://github.com/remix-run/react-router/commit/a76efddfa20945807a422ac88860b7108f0cf4d5
[ 0.9986087679862976, 0.2506908178329468, 0.00017041928367689252, 0.0016261233249679208, 0.4316443204879761 ]
{ "id": 4, "code_window": [ "\n", " transitionManager.match(location, function (error, redirectLocation, nextState) {\n", " let renderProps\n", "\n", " if (nextState) {\n", " const router = {\n", " ...createRouterObject(history, transitionManager),\n", " location: nextState.location,\n", " params: nextState.params\n", " }\n", "\n", " renderProps = {\n", " ...nextState,\n", " router,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " const router = createRouterObject(history, transitionManager, nextState)\n" ], "file_path": "modules/match.js", "type": "replace", "edit_start_line_idx": 45 }
/*eslint-disable no-console, no-var */ var express = require('express') var rewrite = require('express-urlrewrite') var webpack = require('webpack') var webpackDevMiddleware = require('webpack-dev-middleware') var WebpackConfig = require('./webpack.config') var app = express() app.use(webpackDevMiddleware(webpack(WebpackConfig), { publicPath: '/__build__/', stats: { colors: true } })) var fs = require('fs') var path = require('path') fs.readdirSync(__dirname).forEach(function (file) { if (fs.statSync(path.join(__dirname, file)).isDirectory()) app.use(rewrite('/' + file + '/*', '/' + file + '/index.html')) }) app.use(express.static(__dirname)) app.listen(8080, function () { console.log('Server listening on http://localhost:8080, Ctrl+C to stop') })
examples/server.js
0
https://github.com/remix-run/react-router/commit/a76efddfa20945807a422ac88860b7108f0cf4d5
[ 0.00017644355830270797, 0.00017437835049349815, 0.00017281492182519287, 0.00017387655680067837, 0.0000015232848227242357 ]
{ "id": 4, "code_window": [ "\n", " transitionManager.match(location, function (error, redirectLocation, nextState) {\n", " let renderProps\n", "\n", " if (nextState) {\n", " const router = {\n", " ...createRouterObject(history, transitionManager),\n", " location: nextState.location,\n", " params: nextState.params\n", " }\n", "\n", " renderProps = {\n", " ...nextState,\n", " router,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " const router = createRouterObject(history, transitionManager, nextState)\n" ], "file_path": "modules/match.js", "type": "replace", "edit_start_line_idx": 45 }
import React from 'react' class Grades extends React.Component { render() { return ( <div> <h2>Grades</h2> </div> ) } } module.exports = Grades
examples/huge-apps/routes/Grades/components/Grades.js
0
https://github.com/remix-run/react-router/commit/a76efddfa20945807a422ac88860b7108f0cf4d5
[ 0.00017631539958529174, 0.00017607290646992624, 0.0001758303988026455, 0.00017607290646992624, 2.425003913231194e-7 ]
{ "id": 4, "code_window": [ "\n", " transitionManager.match(location, function (error, redirectLocation, nextState) {\n", " let renderProps\n", "\n", " if (nextState) {\n", " const router = {\n", " ...createRouterObject(history, transitionManager),\n", " location: nextState.location,\n", " params: nextState.params\n", " }\n", "\n", " renderProps = {\n", " ...nextState,\n", " router,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " const router = createRouterObject(history, transitionManager, nextState)\n" ], "file_path": "modules/match.js", "type": "replace", "edit_start_line_idx": 45 }
import assert from 'assert' import expect from 'expect' import React from 'react' import { render, unmountComponentAtNode } from 'react-dom' import useRouterHistory from '../useRouterHistory' import createHistory from 'history/lib/createMemoryHistory' import Redirect from '../Redirect' import Router from '../Router' import Route from '../Route' describe('useRouterHistory', function () { it('passes along options, especially query parsing', function (done) { const history = useRouterHistory(createHistory)({ stringifyQuery() { assert(true) done() } }) history.push({ pathname: '/', query: { test: true } }) }) describe('when using basename', function () { let node beforeEach(function () { node = document.createElement('div') }) afterEach(function () { unmountComponentAtNode(node) }) it('should regard basename', function (done) { const pathnames = [] const basenames = [] const history = useRouterHistory(createHistory)({ entries: '/foo/notes/5', basename: '/foo' }) history.listen(function (location) { pathnames.push(location.pathname) basenames.push(location.basename) }) render(( <Router history={history}> <Route path="/messages/:id" /> <Redirect from="/notes/:id" to="/messages/:id" /> </Router> ), node, function () { expect(pathnames).toEqual([ '/notes/5', '/messages/5' ]) expect(basenames).toEqual([ '/foo', '/foo' ]) expect(this.state.location.pathname).toEqual('/messages/5') expect(this.state.location.basename).toEqual('/foo') done() }) }) }) })
modules/__tests__/useRouterHistory-test.js
0
https://github.com/remix-run/react-router/commit/a76efddfa20945807a422ac88860b7108f0cf4d5
[ 0.0031197520438581705, 0.0014294545399025083, 0.0001650697086006403, 0.0011446841526776552, 0.0012936193961650133 ]
{ "id": 0, "code_window": [ "// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n", "// TypeScript Version: 3.0\n", "\n", "import * as React from 'react';\n", "import { GenericStoreEnhancer } from 'redux';\n", "\n", "export interface IDevTools {\n", " new (): JSX.ElementClass;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { StoreEnhancer } from 'redux';\n" ], "file_path": "types/redux-devtools/index.d.ts", "type": "replace", "edit_start_line_idx": 7 }
{ "private": true, "dependencies": { "redux": "^3.6.0" } }
types/redux-devtools/package.json
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.0001700983411865309, 0.0001700983411865309, 0.0001700983411865309, 0.0001700983411865309, 0 ]
{ "id": 0, "code_window": [ "// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n", "// TypeScript Version: 3.0\n", "\n", "import * as React from 'react';\n", "import { GenericStoreEnhancer } from 'redux';\n", "\n", "export interface IDevTools {\n", " new (): JSX.ElementClass;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { StoreEnhancer } from 'redux';\n" ], "file_path": "types/redux-devtools/index.d.ts", "type": "replace", "edit_start_line_idx": 7 }
import * as WebSocket from 'uws'; import { Buffer } from 'buffer'; import * as http from'http'; import * as https from'https'; import * as fs from'fs'; const WebSocketServer = WebSocket.Server; const non_ssl = new WebSocketServer({ port: 3000 }); let non_ssl_disconnections = 0; non_ssl.on('connection', function(ws) { ws.on('message', function(message) { ws.send(message); }); ws.on('close', function() { if (++non_ssl_disconnections == 519) { non_ssl.close(); } }); }); const options = { key: fs.readFileSync('../../ssl/key.pem'), cert: fs.readFileSync('../../ssl/cert.pem'), passphrase: '1234' }; const httpsServer = https.createServer(options, (req: any, res: any) => { req.socket.end(); }); const ssl = new WebSocketServer({ server: httpsServer }); let ssl_disconnections = 0; ssl.on('connection', function(ws) { ws.on('message', function(message) { ws.send(message); }); ws.on('close', function() { if (++ssl_disconnections == 519) { ssl.close(); } }); }); httpsServer.listen(3001); /** * HTTP module. */ const document: Buffer = Buffer.from('Hello world!'); const server: http.Server = WebSocket.http.createServer( (req: http.IncomingMessage, res: http.ServerResponse): void => { if (req.method === 'POST') { const body: Buffer[] = []; req.on('data', (chunk: Buffer) => { body.push(Buffer.from(chunk)); }).on('end', () => { res.end('You posted me this: ' + Buffer.concat(body).toString()); }); // handle some GET url } else if (req.url === '/') { res.end(document); } else { res.end('Unknown request by: ' + req.headers['user-agent']); } }); server.listen(3002);
types/uws/uws-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.00017448958533350378, 0.00017088867025449872, 0.00016710023919586092, 0.00017080370162148029, 0.000002552126943555777 ]
{ "id": 0, "code_window": [ "// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n", "// TypeScript Version: 3.0\n", "\n", "import * as React from 'react';\n", "import { GenericStoreEnhancer } from 'redux';\n", "\n", "export interface IDevTools {\n", " new (): JSX.ElementClass;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { StoreEnhancer } from 'redux';\n" ], "file_path": "types/redux-devtools/index.d.ts", "type": "replace", "edit_start_line_idx": 7 }
{ "compilerOptions": { "module": "commonjs", "lib": [ "es6" ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", "merge-env-tests.ts" ] }
types/merge-env/tsconfig.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.00017284606292378157, 0.00017203419702127576, 0.00017153228691313416, 0.00017172424122691154, 5.793998525405186e-7 ]
{ "id": 0, "code_window": [ "// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n", "// TypeScript Version: 3.0\n", "\n", "import * as React from 'react';\n", "import { GenericStoreEnhancer } from 'redux';\n", "\n", "export interface IDevTools {\n", " new (): JSX.ElementClass;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { StoreEnhancer } from 'redux';\n" ], "file_path": "types/redux-devtools/index.d.ts", "type": "replace", "edit_start_line_idx": 7 }
import unorm = require("unorm"); function listNormalizations(raw: string) { return [ unorm.nfd(raw), unorm.nfkd(raw), unorm.nfc(raw), unorm.nfkc(raw), ]; }
types/unorm/unorm-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.00017630228830967098, 0.00017579591076355428, 0.00017528953321743757, 0.00017579591076355428, 5.063775461167097e-7 ]
{ "id": 1, "code_window": [ "\n", "export interface IDevTools {\n", " new (): JSX.ElementClass;\n", " instrument(): GenericStoreEnhancer\n", "}\n", "\n", "export declare function createDevTools(el: React.ReactElement): IDevTools;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " instrument(): StoreEnhancer\n" ], "file_path": "types/redux-devtools/index.d.ts", "type": "replace", "edit_start_line_idx": 11 }
// Type definitions for redux-devtools 3.0.0 // Project: https://github.com/gaearon/redux-devtools // Definitions by: Petryshyn Sergii <https://github.com/mc-petry> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 3.0 import * as React from 'react'; import { GenericStoreEnhancer } from 'redux'; export interface IDevTools { new (): JSX.ElementClass; instrument(): GenericStoreEnhancer } export declare function createDevTools(el: React.ReactElement): IDevTools; export declare function persistState(debugSessionKey: string): GenericStoreEnhancer; declare const factory: { instrument(): (opts: any) => any }; export default factory;
types/redux-devtools/index.d.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.9983600974082947, 0.361600786447525, 0.00017173471860587597, 0.0862705335021019, 0.451626718044281 ]
{ "id": 1, "code_window": [ "\n", "export interface IDevTools {\n", " new (): JSX.ElementClass;\n", " instrument(): GenericStoreEnhancer\n", "}\n", "\n", "export declare function createDevTools(el: React.ReactElement): IDevTools;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " instrument(): StoreEnhancer\n" ], "file_path": "types/redux-devtools/index.d.ts", "type": "replace", "edit_start_line_idx": 11 }
import * as hapi from 'hapi'; import * as crumb from 'crumb'; const server = new hapi.Server({ port: 8000 }); server.register({ plugin: crumb, options: { key: 'csrf-token', size: 50, autoGenerate: true, addToViewContext: true, cookieOptions: { path: '/', }, headerName: 'X-CSRF-Token', restful: true, skip: () => false, enforce: true, logUnauthorized: false, } }); server.route({ method: 'get', path: '/', handler: async (_, h) => { return h.continue; }, }); server.route({ method: 'get', path: '/custom', options: { plugins: { crumb: { key: 'x-csrf-token', source: 'query', restful: true, }, }, }, handler: async (_, h) => { return h.continue; }, });
types/crumb/crumb-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.00017648309585638344, 0.00017299327009823173, 0.00017042644321918488, 0.0001725885085761547, 0.0000022012559384165797 ]
{ "id": 1, "code_window": [ "\n", "export interface IDevTools {\n", " new (): JSX.ElementClass;\n", " instrument(): GenericStoreEnhancer\n", "}\n", "\n", "export declare function createDevTools(el: React.ReactElement): IDevTools;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " instrument(): StoreEnhancer\n" ], "file_path": "types/redux-devtools/index.d.ts", "type": "replace", "edit_start_line_idx": 11 }
{ "extends": "dtslint/dt.json", "rules": { "adjacent-overload-signatures": false, "array-type": false, "arrow-return-shorthand": false, "ban-types": false, "callable-types": false, "comment-format": false, "dt-header": false, "npm-naming": false, "eofline": false, "export-just-namespace": false, "import-spacing": false, "interface-name": false, "interface-over-type-literal": false, "jsdoc-format": false, "max-line-length": false, "member-access": false, "new-parens": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, "no-consecutive-blank-lines": false, "no-construct": false, "no-declare-current-package": false, "no-duplicate-imports": false, "no-duplicate-variable": false, "no-empty-interface": false, "no-for-in-array": false, "no-inferrable-types": false, "no-internal-module": false, "no-irregular-whitespace": false, "no-mergeable-namespace": false, "no-misused-new": false, "no-namespace": false, "no-object-literal-type-assertion": false, "no-padding": false, "no-redundant-jsdoc": false, "no-redundant-jsdoc-2": false, "no-redundant-undefined": false, "no-reference-import": false, "no-relative-import-in-test": false, "no-self-import": false, "no-single-declare-module": false, "no-string-throw": false, "no-unnecessary-callback-wrapper": false, "no-unnecessary-class": false, "no-unnecessary-generics": false, "no-unnecessary-qualifier": false, "no-unnecessary-type-assertion": false, "no-useless-files": false, "no-var-keyword": false, "no-var-requires": false, "no-void-expression": false, "no-trailing-whitespace": false, "object-literal-key-quotes": false, "object-literal-shorthand": false, "one-line": false, "one-variable-per-declaration": false, "only-arrow-functions": false, "prefer-conditional-expression": false, "prefer-const": false, "prefer-declare-function": false, "prefer-for-of": false, "prefer-method-signature": false, "prefer-template": false, "radix": false, "semicolon": false, "space-before-function-paren": false, "space-within-parens": false, "strict-export-declare-modifiers": false, "trim-file": false, "triple-equals": false, "typedef-whitespace": false, "unified-signatures": false, "void-return": false, "whitespace": false } }
types/inherits/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.0001731950178509578, 0.00017104485596064478, 0.0001686966570559889, 0.00017166709585580975, 0.0000014150920151223545 ]
{ "id": 1, "code_window": [ "\n", "export interface IDevTools {\n", " new (): JSX.ElementClass;\n", " instrument(): GenericStoreEnhancer\n", "}\n", "\n", "export declare function createDevTools(el: React.ReactElement): IDevTools;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " instrument(): StoreEnhancer\n" ], "file_path": "types/redux-devtools/index.d.ts", "type": "replace", "edit_start_line_idx": 11 }
import * as React from 'react'; import { CSSModule } from '../index'; export interface CardProps extends React.HTMLAttributes<HTMLElement> { [key: string]: any; tag?: React.ReactType; inverse?: boolean; color?: string; body?: boolean; outline?: boolean; className?: string; cssModule?: CSSModule; style?: React.CSSProperties; } declare class Card<T = {[key: string]: any}> extends React.Component<CardProps> {} export default Card;
types/reactstrap/lib/Card.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.0001856932940427214, 0.00018149147217627615, 0.0001772896503098309, 0.00018149147217627615, 0.000004201821866445243 ]
{ "id": 2, "code_window": [ "}\n", "\n", "export declare function createDevTools(el: React.ReactElement): IDevTools;\n", "export declare function persistState(debugSessionKey: string): GenericStoreEnhancer;\n", "\n", "declare const factory: { instrument(): (opts: any) => any };\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export declare function persistState(debugSessionKey: string): StoreEnhancer;\n" ], "file_path": "types/redux-devtools/index.d.ts", "type": "replace", "edit_start_line_idx": 15 }
// Type definitions for redux-devtools 3.0.0 // Project: https://github.com/gaearon/redux-devtools // Definitions by: Petryshyn Sergii <https://github.com/mc-petry> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 3.0 import * as React from 'react'; import { GenericStoreEnhancer } from 'redux'; export interface IDevTools { new (): JSX.ElementClass; instrument(): GenericStoreEnhancer } export declare function createDevTools(el: React.ReactElement): IDevTools; export declare function persistState(debugSessionKey: string): GenericStoreEnhancer; declare const factory: { instrument(): (opts: any) => any }; export default factory;
types/redux-devtools/index.d.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.9959409236907959, 0.3330104947090149, 0.00017844424291979522, 0.0029120813123881817, 0.46876394748687744 ]
{ "id": 2, "code_window": [ "}\n", "\n", "export declare function createDevTools(el: React.ReactElement): IDevTools;\n", "export declare function persistState(debugSessionKey: string): GenericStoreEnhancer;\n", "\n", "declare const factory: { instrument(): (opts: any) => any };\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export declare function persistState(debugSessionKey: string): StoreEnhancer;\n" ], "file_path": "types/redux-devtools/index.d.ts", "type": "replace", "edit_start_line_idx": 15 }
import Ember from 'ember'; import DS from 'ember-data'; import Controller from '@ember/controller'; class MyModel extends DS.Model {} declare module 'ember-data/types/registries/model' { export default interface ModelRegistry { 'my-model': MyModel; } } Ember.Route.extend({ model(): any { return this.store.findAll('my-model'); } }); Controller.extend({ actions: { create(): any { this.queryParams; return this.store.createRecord('my-model'); } } }); Ember.DataAdapter.extend({ test() { this.store.findRecord('my-model', 123); } });
types/ember-data/test/injections.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.00017647114873398095, 0.0001716406986815855, 0.00016642935224808753, 0.00017183113959617913, 0.0000035657978969538817 ]
{ "id": 2, "code_window": [ "}\n", "\n", "export declare function createDevTools(el: React.ReactElement): IDevTools;\n", "export declare function persistState(debugSessionKey: string): GenericStoreEnhancer;\n", "\n", "declare const factory: { instrument(): (opts: any) => any };\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export declare function persistState(debugSessionKey: string): StoreEnhancer;\n" ], "file_path": "types/redux-devtools/index.d.ts", "type": "replace", "edit_start_line_idx": 15 }
import webpack = require('webpack'); export interface OpaqueFileSizes { root: string; sizes: Record<string, number>; } /** * Captures JS and CSS asset sizes inside the passed `buildFolder`. Save the * result value to compare it after the build. */ export function measureFileSizesBeforeBuild(buildFolder: string): Promise<OpaqueFileSizes>; /** * Prints the JS and CSS asset sizes after the build, and includes a size * comparison with `previousFileSizes` that were captured earlier using * `measureFileSizesBeforeBuild()`. `maxBundleGzipSize` and * `maxChunkGzipSizemay` may optionally be specified to display a warning when * the main bundle or a chunk exceeds the specified size (in bytes). */ export function printFileSizesAfterBuild( webpackStats: webpack.Stats, previousFileSizes: OpaqueFileSizes, buildFolder: string, maxBundleGzipSize?: number, maxChunkGzipSize?: number, ): void;
types/react-dev-utils/FileSizeReporter.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.00017032865434885025, 0.00016833185509312898, 0.00016666881856508553, 0.00016799807781353593, 0.0000015126472590054618 ]
{ "id": 2, "code_window": [ "}\n", "\n", "export declare function createDevTools(el: React.ReactElement): IDevTools;\n", "export declare function persistState(debugSessionKey: string): GenericStoreEnhancer;\n", "\n", "declare const factory: { instrument(): (opts: any) => any };\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export declare function persistState(debugSessionKey: string): StoreEnhancer;\n" ], "file_path": "types/redux-devtools/index.d.ts", "type": "replace", "edit_start_line_idx": 15 }
// Type definitions for jQuery.qrcode v0.12.0 // Project: https://github.com/lrsjng/jquery-qrcode // Definitions by: Dan Manastireanu <https://github.com/danmana> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// <reference types="jquery" /> declare namespace JQueryQRCode { /** * One of the possible mode types. */ export const enum Mode { NORMAL, LABEL_STRIP, LABEL_BOX, IMAGE_STRIP, IMAGE_BOX } interface Options { /** * Render method: 'canvas', 'image' or 'div' * @default 'canvas' */ render?: string, /** * Start of version range, somewhere in 1 .. 40 * @default 1 */ minVersion?: number, /** * End of version range, somewhere in 1 .. 40 * @default 40 */ maxVersion?: number, /** * Error correction level: 'L', 'M', 'Q' or 'H' * @default 'L' */ ecLevel?: string, /** * Left offset in pixels, if drawn onto existing canvas * @default 0 */ left?: number, /** * Top offset in pixels, if drawn onto existing canvas * @default 0 */ top?: number, /** * Size in pixel * @default 200 */ size?: number, /** * Code color or image element * @default '#000' */ fill?: string, /** * Background color or image element, null for transparent background * @default null */ background?: string, /** * The text content of the QR code. * @default 'no text' */ text?: string, /** * Corner radius relative to module width: 0.0 .. 0.5 * @default 0 */ radius?: number, /** * Quiet zone in modules * @default 0 */ quiet?: number, /** * Mode * @default Mode.NORMAL */ mode?: Mode, /** @default 0.1 */ mSize?: number, /** @default 0.5 */ mPosX?: number, /** @default 0.5 */ mPosY?: number, /** @default 'no label' */ label?: string, /** @default 'sans' */ fontname?: string, /** @default '#000' */ fontcolor?: string, /** @default null */ image?: string } } interface JQuery { /** * Create a QR Code inside the selected container. * @param options */ qrcode(options?: JQueryQRCode.Options): JQuery; }
types/jquery.qrcode/index.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.00017794065934140235, 0.00017401057993993163, 0.00016726728063076735, 0.00017462657706346363, 0.000002491515033398173 ]
{ "id": 3, "code_window": [ "{\n", " \"private\": true,\n", " \"dependencies\": {\n", " \"redux\": \"^3.6.0\"\n", " }\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " \"redux\": \"^4.0.4\"\n" ], "file_path": "types/redux-devtools/package.json", "type": "replace", "edit_start_line_idx": 3 }
// Type definitions for redux-devtools 3.0.0 // Project: https://github.com/gaearon/redux-devtools // Definitions by: Petryshyn Sergii <https://github.com/mc-petry> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 3.0 import * as React from 'react'; import { GenericStoreEnhancer } from 'redux'; export interface IDevTools { new (): JSX.ElementClass; instrument(): GenericStoreEnhancer } export declare function createDevTools(el: React.ReactElement): IDevTools; export declare function persistState(debugSessionKey: string): GenericStoreEnhancer; declare const factory: { instrument(): (opts: any) => any }; export default factory;
types/redux-devtools/index.d.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.00017568258044775575, 0.00016936917381826788, 0.0001658881374169141, 0.00016653680359013379, 0.0000044721000449499115 ]
{ "id": 3, "code_window": [ "{\n", " \"private\": true,\n", " \"dependencies\": {\n", " \"redux\": \"^3.6.0\"\n", " }\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " \"redux\": \"^4.0.4\"\n" ], "file_path": "types/redux-devtools/package.json", "type": "replace", "edit_start_line_idx": 3 }
{ "private": true, "dependencies": { "flatpickr": "^4.0.6" } }
types/react-flatpickr/package.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.0004947826964780688, 0.0004947826964780688, 0.0004947826964780688, 0.0004947826964780688, 0 ]
{ "id": 3, "code_window": [ "{\n", " \"private\": true,\n", " \"dependencies\": {\n", " \"redux\": \"^3.6.0\"\n", " }\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " \"redux\": \"^4.0.4\"\n" ], "file_path": "types/redux-devtools/package.json", "type": "replace", "edit_start_line_idx": 3 }
{ "compilerOptions": { "module": "commonjs", "lib": [ "es6", "dom" ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": false, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", "ng-dialog-tests.ts" ] }
types/ng-dialog/tsconfig.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.0001665285526541993, 0.000166366808116436, 0.00016606712597422302, 0.0001665047457208857, 2.1213003265074803e-7 ]
{ "id": 3, "code_window": [ "{\n", " \"private\": true,\n", " \"dependencies\": {\n", " \"redux\": \"^3.6.0\"\n", " }\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " \"redux\": \"^4.0.4\"\n" ], "file_path": "types/redux-devtools/package.json", "type": "replace", "edit_start_line_idx": 3 }
{ "extends": "dtslint/dt.json" }
types/react-slider/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.0001679018314462155, 0.0001679018314462155, 0.0001679018314462155, 0.0001679018314462155, 0 ]
{ "id": 4, "code_window": [ "import * as React from 'react'\n", "import { compose, createStore, Reducer, Store, GenericStoreEnhancer } from 'redux'\n", "import { Provider } from 'react-redux'\n", "import { createDevTools, persistState } from 'redux-devtools'\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { compose, createStore, Reducer, Store, StoreEnhancer } from 'redux'\n" ], "file_path": "types/redux-devtools/redux-devtools-tests.tsx", "type": "replace", "edit_start_line_idx": 1 }
import * as React from 'react' import { compose, createStore, Reducer, Store, GenericStoreEnhancer } from 'redux' import { Provider } from 'react-redux' import { createDevTools, persistState } from 'redux-devtools' declare var reducer: Reducer<any> class DevToolsMonitor extends React.Component { } const DevTools = createDevTools( <DevToolsMonitor /> ) const storeEnhancer = compose( DevTools.instrument(), persistState('test-session') ) as GenericStoreEnhancer const finalCreateStore = storeEnhancer(createStore) const store = finalCreateStore(reducer) class App extends React.Component { render() { return ( <Provider store={store}> <DevTools /> </Provider> ) } }
types/redux-devtools/redux-devtools-tests.tsx
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.7348129749298096, 0.1857641190290451, 0.00017313193529844284, 0.004035197664052248, 0.3170059323310852 ]
{ "id": 4, "code_window": [ "import * as React from 'react'\n", "import { compose, createStore, Reducer, Store, GenericStoreEnhancer } from 'redux'\n", "import { Provider } from 'react-redux'\n", "import { createDevTools, persistState } from 'redux-devtools'\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { compose, createStore, Reducer, Store, StoreEnhancer } from 'redux'\n" ], "file_path": "types/redux-devtools/redux-devtools-tests.tsx", "type": "replace", "edit_start_line_idx": 1 }
{ "extends": "dtslint/dt.json" }
types/express-correlation-id/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.0001707812334643677, 0.0001707812334643677, 0.0001707812334643677, 0.0001707812334643677, 0 ]
{ "id": 4, "code_window": [ "import * as React from 'react'\n", "import { compose, createStore, Reducer, Store, GenericStoreEnhancer } from 'redux'\n", "import { Provider } from 'react-redux'\n", "import { createDevTools, persistState } from 'redux-devtools'\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { compose, createStore, Reducer, Store, StoreEnhancer } from 'redux'\n" ], "file_path": "types/redux-devtools/redux-devtools-tests.tsx", "type": "replace", "edit_start_line_idx": 1 }
{ "compilerOptions": { "module": "commonjs", "lib": [ "es6" ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true, "strictFunctionTypes": true, "paths": { "@iarna/toml": [ "iarna__toml" ], "@iarna/toml/*": [ "iarna__toml/*" ] } }, "files": [ "index.d.ts", "parse-async.d.ts", "parse-stream.d.ts", "parse-string.d.ts", "stringify.d.ts", "iarna__toml-tests.ts" ] }
types/iarna__toml/tsconfig.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.00017589092021808028, 0.00017268324154429138, 0.00016902608331292868, 0.00017290798132307827, 0.000002518021801733994 ]
{ "id": 4, "code_window": [ "import * as React from 'react'\n", "import { compose, createStore, Reducer, Store, GenericStoreEnhancer } from 'redux'\n", "import { Provider } from 'react-redux'\n", "import { createDevTools, persistState } from 'redux-devtools'\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { compose, createStore, Reducer, Store, StoreEnhancer } from 'redux'\n" ], "file_path": "types/redux-devtools/redux-devtools-tests.tsx", "type": "replace", "edit_start_line_idx": 1 }
{ "extends": "dtslint/dt.json" }
types/lodash.trim/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.0001707812334643677, 0.0001707812334643677, 0.0001707812334643677, 0.0001707812334643677, 0 ]
{ "id": 5, "code_window": [ "import { Provider } from 'react-redux'\n", "import { createDevTools, persistState } from 'redux-devtools'\n", "\n", "declare var reducer: Reducer<any>\n", "\n", "class DevToolsMonitor extends React.Component {\n", "}\n", "\n", "const DevTools = createDevTools(\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "declare var reducer: Reducer\n" ], "file_path": "types/redux-devtools/redux-devtools-tests.tsx", "type": "replace", "edit_start_line_idx": 5 }
{ "private": true, "dependencies": { "redux": "^3.6.0" } }
types/redux-devtools/package.json
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.00016976924962364137, 0.00016976924962364137, 0.00016976924962364137, 0.00016976924962364137, 0 ]
{ "id": 5, "code_window": [ "import { Provider } from 'react-redux'\n", "import { createDevTools, persistState } from 'redux-devtools'\n", "\n", "declare var reducer: Reducer<any>\n", "\n", "class DevToolsMonitor extends React.Component {\n", "}\n", "\n", "const DevTools = createDevTools(\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "declare var reducer: Reducer\n" ], "file_path": "types/redux-devtools/redux-devtools-tests.tsx", "type": "replace", "edit_start_line_idx": 5 }
declare const getComputedStyle: ( element: Element ) => { getPropertyValue: (prop: string) => string }; export = getComputedStyle;
types/dom-helpers/style/getComputedStyle.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.00017432762251701206, 0.00017432762251701206, 0.00017432762251701206, 0.00017432762251701206, 0 ]
{ "id": 5, "code_window": [ "import { Provider } from 'react-redux'\n", "import { createDevTools, persistState } from 'redux-devtools'\n", "\n", "declare var reducer: Reducer<any>\n", "\n", "class DevToolsMonitor extends React.Component {\n", "}\n", "\n", "const DevTools = createDevTools(\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "declare var reducer: Reducer\n" ], "file_path": "types/redux-devtools/redux-devtools-tests.tsx", "type": "replace", "edit_start_line_idx": 5 }
import { lensIndex } from '../index'; export default lensIndex;
types/ramda/es/lensIndex.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.00017806675168685615, 0.00017806675168685615, 0.00017806675168685615, 0.00017806675168685615, 0 ]
{ "id": 5, "code_window": [ "import { Provider } from 'react-redux'\n", "import { createDevTools, persistState } from 'redux-devtools'\n", "\n", "declare var reducer: Reducer<any>\n", "\n", "class DevToolsMonitor extends React.Component {\n", "}\n", "\n", "const DevTools = createDevTools(\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "declare var reducer: Reducer\n" ], "file_path": "types/redux-devtools/redux-devtools-tests.tsx", "type": "replace", "edit_start_line_idx": 5 }
// Type definitions for polygon 1.0 // Project: https://github.com/tmpvar/polygon.js#readme // Definitions by: Konrad Klockgether <https://github.com/Nielio> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /* tslint:disable:array-type */ // cause contradictory error messages import Vec2 = require('vec2'); /** * Create a new polygon: * * ```javascript * var p = new Polygon([ * Vec2(0, 0), * Vec2(10, 0), * Vec2(0, 10) * ]); * * ``` * * You can pass an array of `Vec2`s, arrays `[x, y]`, or objects `{ x: 10, y: 20 }` * * **Stuff to Note**: most of the Vec2's methods take a `returnNew` as the last parameter. * If passed a truthy value, a new vector will be returned to you. * Otherwise the operation will be applied to `this` and `this` will be returned. */ declare class Polygon { readonly points: Vec2[]; /** * Returns the number of points in this polygon */ readonly length: number; constructor(points: Vec2[] | number[][] | { x: number, y: number }[]); /** * Something like Array.forEach on points */ each(fn: (prev: Vec2, current: Vec2, next: Vec2, idx: number) => any): Polygon; /** * Returns the point at index `idx`. note: this will wrap in both directions */ point(idx: number): Vec2; /** * Ensure all of the points are unique */ dedupe(returnNew?: boolean): Polygon; /** * Insert `vec2` at the specified index */ insert(vec2: Vec2, index: number): void; /** * Remove the specified `vec2` or numeric index from this polygon */ remove(vecOrIndex: Vec2 | number): Polygon; /** * Removes contiguous points that are the same */ clean(returnNew?: boolean): Polygon; /** * Returns the direction in which a polygon is wound (true === clockwise) */ winding(): boolean; /** * Rewinds the polygon in the specified direction (true === clockwise) */ rewind(cw: boolean): Polygon; /** * Computes the area of the polygon */ area(): number; /** * Finds the closest point in this polygon to `vec2` */ closestPointTo(vec2: Vec2): Vec2; /** * Returns a `Vec2` at the center of the AABB */ center(): Vec2; /** * Scales this polygon around `origin` (default is `this.center()`) and will return a new polygon if requested with `returnNew` */ scale(amount: number, origin: Vec2, returnNew?: boolean): Polygon; /** * Returns true if `vec2` is inside the polygon */ containsPoint(vec2: Vec2): boolean; /** * Returns true if `poly` is completely contained in this polygon */ containsPolygon(poly: Polygon): boolean; /** * Returns an object `{x:_, y:_, w:_, h:_}` representing the axis-aligned bounding box of this polygyon */ aabb(): { x: number, y: number, w: number, h: number }; /** * Performs an offset/buffering operation on this polygon and returns a new one */ offset(amount: number): Polygon; /** * Return an array `[startpoint, endpoint]` representing the line at the specified `index` */ line(index: number): [Vec2, Vec2]; /** * Iterate over the lines in this polygon */ lines(fn: (start: Vec2, end: Vec2, index: number) => any): Polygon; /** * Find self-intersections and return them as a new polygon */ selfIntersections(): Polygon; /** * Remove self intersections from this polygon. returns an array of polygons */ pruneSelfIntersections(): Polygon[]; /** * Return a new instance of this polygon */ clone(): Polygon; /** * Rotate by origin `vec2` (default `this.center()`) by radians `rads` and return a clone if `returnNew` is specified */ rotate(rads: number, vec2: Vec2, returnNew?: boolean): Polygon; /** * Translate by `vec2` and return a clone if `returnNew` is specified */ translate(vec2: Vec2, returnNew?: boolean): Polygon; /** * Return true if this polygon has the same components and the incoming `poly` */ equal(poly: Polygon): boolean; /** * Works with an array of vec2's, * an object containing a `.position` and `.radius`, * an object populated with x1,y1,x2,y2, * an object populated with x,y,w,h, * and an object populated with x,y,width,height. * See the tests for more info */ contains( thing: Vec2[] | { position: Vec2, radius: number } | { x1: number, y1: number, x2: number, y2: number } | { x: number, y: number, w: number, h: number } | { x: number, y: number, width: number, height: number } ): boolean; /** * Returns a new polygon representing the boolean union of `this` and the incoming `polygon` */ union(polygon: Polygon): Polygon; /** * Returns a new polygon representing the boolean cut of `polygon` from `this` */ cut(polygon: Polygon): Polygon; /** * Convert this polygon into an array of arrays (`[[x, y]]`) */ toArray(): number[][]; } export = Polygon;
types/polygon/index.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.00017824393580667675, 0.00017547528841532767, 0.00017048722656909376, 0.00017585247405804694, 0.0000020918432710459456 ]
{ "id": 6, "code_window": [ "\n", "const storeEnhancer = compose(\n", " DevTools.instrument(),\n", " persistState('test-session')\n", ") as GenericStoreEnhancer\n", "\n", "const finalCreateStore = storeEnhancer(createStore)\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ ") as StoreEnhancer\n" ], "file_path": "types/redux-devtools/redux-devtools-tests.tsx", "type": "replace", "edit_start_line_idx": 17 }
import * as React from 'react' import { compose, createStore, Reducer, Store, GenericStoreEnhancer } from 'redux' import { Provider } from 'react-redux' import { createDevTools, persistState } from 'redux-devtools' declare var reducer: Reducer<any> class DevToolsMonitor extends React.Component { } const DevTools = createDevTools( <DevToolsMonitor /> ) const storeEnhancer = compose( DevTools.instrument(), persistState('test-session') ) as GenericStoreEnhancer const finalCreateStore = storeEnhancer(createStore) const store = finalCreateStore(reducer) class App extends React.Component { render() { return ( <Provider store={store}> <DevTools /> </Provider> ) } }
types/redux-devtools/redux-devtools-tests.tsx
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.998293936252594, 0.7433760762214661, 0.00017925258725881577, 0.9875155091285706, 0.42916837334632874 ]
{ "id": 6, "code_window": [ "\n", "const storeEnhancer = compose(\n", " DevTools.instrument(),\n", " persistState('test-session')\n", ") as GenericStoreEnhancer\n", "\n", "const finalCreateStore = storeEnhancer(createStore)\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ ") as StoreEnhancer\n" ], "file_path": "types/redux-devtools/redux-devtools-tests.tsx", "type": "replace", "edit_start_line_idx": 17 }
{ "extends": "dtslint/dt.json" }
types/session-file-store/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.0001739087310852483, 0.0001739087310852483, 0.0001739087310852483, 0.0001739087310852483, 0 ]
{ "id": 6, "code_window": [ "\n", "const storeEnhancer = compose(\n", " DevTools.instrument(),\n", " persistState('test-session')\n", ") as GenericStoreEnhancer\n", "\n", "const finalCreateStore = storeEnhancer(createStore)\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ ") as StoreEnhancer\n" ], "file_path": "types/redux-devtools/redux-devtools-tests.tsx", "type": "replace", "edit_start_line_idx": 17 }
import MemoryFileSystem = require('memory-fs') import webpack = require('webpack') // integration with webpack const compiler = webpack() compiler.inputFileSystem = new MemoryFileSystem() compiler.outputFileSystem = new MemoryFileSystem()
types/memory-fs/test/webpack.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.00017811990983318537, 0.00017811990983318537, 0.00017811990983318537, 0.00017811990983318537, 0 ]
{ "id": 6, "code_window": [ "\n", "const storeEnhancer = compose(\n", " DevTools.instrument(),\n", " persistState('test-session')\n", ") as GenericStoreEnhancer\n", "\n", "const finalCreateStore = storeEnhancer(createStore)\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ ") as StoreEnhancer\n" ], "file_path": "types/redux-devtools/redux-devtools-tests.tsx", "type": "replace", "edit_start_line_idx": 17 }
{ "compilerOptions": { "module": "commonjs", "lib": [ "es6" ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", "undertaker-tests.ts" ] }
types/undertaker/tsconfig.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/7e7af62444b1db0a8cac7f22dfb409ee09448b1b
[ 0.00017619793652556837, 0.00017424765974283218, 0.00017258801381103694, 0.00017395698523614556, 0.000001488007114858192 ]
{ "id": 0, "code_window": [ " \"express\": \"^4.15.3\",\n", " \"file-loader\": \"^0.11.1\",\n", " \"find-cache-dir\": \"^1.0.0\",\n", " \"global\": \"^4.3.2\",\n", " \"html-webpack-plugin\": \"^2.30.1\",\n", " \"json-loader\": \"^0.5.4\",\n", " \"json-stringify-safe\": \"^5.0.1\",\n", " \"json5\": \"^0.5.1\",\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"html-loader\": \"^0.5.4\",\n" ], "file_path": "app/angular/package.json", "type": "add", "edit_start_line_idx": 54 }
{ "name": "@storybook/vue", "version": "3.4.0-alpha.0", "description": "Storybook for Vue: Develop Vue Component in isolation with Hot Reloading.", "homepage": "https://github.com/storybooks/storybook/tree/master/apps/vue", "bugs": { "url": "https://github.com/storybooks/storybook/issues" }, "license": "MIT", "main": "dist/client/index.js", "jsnext:main": "src/client/index.js", "bin": { "build-storybook": "./bin/build.js", "start-storybook": "./bin/index.js", "storybook-server": "./bin/index.js" }, "repository": { "type": "git", "url": "https://github.com/storybooks/storybook.git" }, "scripts": { "dev": "cross-env DEV_BUILD=1 nodemon --watch ./src --exec \"yarn prepare\"", "prepare": "node ../../scripts/prepare.js" }, "dependencies": { "@storybook/addon-actions": "^3.4.0-alpha.0", "@storybook/addon-links": "^3.4.0-alpha.0", "@storybook/addons": "^3.4.0-alpha.0", "@storybook/channel-postmessage": "^3.4.0-alpha.0", "@storybook/core": "^3.4.0-alpha.0", "@storybook/ui": "^3.4.0-alpha.0", "airbnb-js-shims": "^1.4.0", "autoprefixer": "^7.2.4", "babel-loader": "^7.1.2", "babel-plugin-react-docgen": "^1.8.0", "babel-plugin-transform-regenerator": "^6.26.0", "babel-plugin-transform-runtime": "^6.23.0", "babel-preset-env": "^1.6.0", "babel-preset-minify": "^0.2.0", "babel-preset-react": "^6.24.1", "babel-preset-react-app": "^3.1.0", "babel-preset-stage-0": "^6.24.1", "babel-runtime": "^6.26.0", "case-sensitive-paths-webpack-plugin": "^2.1.1", "chalk": "^2.3.0", "commander": "^2.12.2", "common-tags": "^1.6.0", "configstore": "^3.1.1", "core-js": "^2.5.3", "css-loader": "^0.28.8", "dotenv-webpack": "^1.5.4", "express": "^4.16.2", "file-loader": "^1.1.6", "find-cache-dir": "^1.0.0", "global": "^4.3.2", "html-webpack-plugin": "^2.30.1", "json-loader": "^0.5.7", "json-stringify-safe": "^5.0.1", "json5": "^0.5.1", "postcss-flexbugs-fixes": "^3.2.0", "postcss-loader": "^2.0.10", "prop-types": "^15.6.0", "qs": "^6.5.1", "react": "^16.2.0", "react-dom": "^16.2.0", "redux": "^3.7.2", "request": "^2.83.0", "serve-favicon": "^2.4.5", "shelljs": "^0.7.8", "style-loader": "^0.19.1", "uglifyjs-webpack-plugin": "^1.1.6", "url-loader": "^0.6.2", "util-deprecate": "^1.0.2", "uuid": "^3.1.0", "vue-hot-reload-api": "^2.2.4", "vue-style-loader": "^3.0.1", "webpack": "^3.10.0", "webpack-dev-middleware": "^1.12.2", "webpack-hot-middleware": "^2.21.0" }, "devDependencies": { "nodemon": "^1.14.9", "vue": "^2.5.13", "vue-loader": "^13.6.2", "vue-template-compiler": "^2.5.13" }, "peerDependencies": { "babel-core": "^6.26.0 || ^7.0.0-0", "vue": "2.5.13", "vue-loader": "13.6.2", "vue-template-compiler": "2.5.13" } }
app/vue/package.json
1
https://github.com/storybookjs/storybook/commit/c3a9c18ffecbc4f041205bdc5ef96c4f16f4f0c5
[ 0.9248529672622681, 0.09263710677623749, 0.0001650561607675627, 0.00016814620175864547, 0.2774052917957306 ]
{ "id": 0, "code_window": [ " \"express\": \"^4.15.3\",\n", " \"file-loader\": \"^0.11.1\",\n", " \"find-cache-dir\": \"^1.0.0\",\n", " \"global\": \"^4.3.2\",\n", " \"html-webpack-plugin\": \"^2.30.1\",\n", " \"json-loader\": \"^0.5.4\",\n", " \"json-stringify-safe\": \"^5.0.1\",\n", " \"json5\": \"^0.5.1\",\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"html-loader\": \"^0.5.4\",\n" ], "file_path": "app/angular/package.json", "type": "add", "edit_start_line_idx": 54 }
* * * id: 'addon-gallery' ## title: 'Addon Gallery' This is a list of available addons for Storybook. ## Addons maintained by storybook team. ### [Actions](https://github.com/storybooks/storybook/tree/master/addons/actions) With actions, you can inspect events related to your components. This is pretty neat when you are manually testing your components. Also, you can think of this as a way to document events in your components. ### [Links](https://github.com/storybooks/storybook/tree/master/addons/links) With links you can link stories together. With that, you can build demos and prototypes directly from your UI components. ### [Knobs](https://github.com/storybooks/storybook/tree/master/addons/knobs) Knobs allow you to edit React props dynamically using the Storybook UI. You can also use Knobs as dynamic variables inside your stories. ### [Notes](https://github.com/storybooks/storybook/tree/master/addons/notes) With this addon, you can write notes for each story in your component. This is pretty useful when you are working with a team. ### [Info](https://github.com/storybooks/storybook/tree/master/addons/info) If you are using Storybook as a style guide, then this addon will help you to build a nice-looking style guide with docs, automatic sample source code with a PropType explorer. ### [Options](https://github.com/storybooks/storybook/tree/master/addons/options) The Storybook webapp UI can be customised with this addon. It can be used to change the header, show/hide various UI elements and to enable full-screen mode by default. ### [Storyshots](https://github.com/storybooks/storybook/tree/master/addons/storyshots) Storyshots is a way to automatically jest-snapshot all your stories. [More info here](/testing/structural-testing/). ### [Console](https://github.com/storybooks/storybook-addon-console) Redirects console output (logs, errors, warnings) into Action Logger Panel. `withConsole` decorator notifies from what stories logs are coming. ## Community Addons You need to install these addons directly from NPM in order to use them. ### [Readme](https://github.com/tuchk4/storybook-readme) With this addon, you can add docs in markdown format for each story. It very useful because most projects and components already have README.md files. Now it is easy to add them into your Storybook. ### [Story-router](https://github.com/gvaldambrini/storybook-router) A [decorator](/addons/introduction) that allows you to use your routing-aware components in your stories. ### [Host](https://github.com/philcockfield/storybook-host) A [decorator](/addons/introduction) with powerful display options for hosting, sizing and framing your components. ### [Specs](https://github.com/mthuret/storybook-addon-specifications) This is a very special addon where it'll allow you to write test specs directly inside your stories. You can even run these tests inside a CI box. ### [Chapters](https://github.com/yangshun/react-storybook-addon-chapters) With this addon, you can showcase multiple components (or varying component states) within 1 story. Break your stories down into smaller categories (chapters) and subcategories (sections) for more organizational goodness. ### [Props Combinations](https://github.com/evgenykochetkov/react-storybook-addon-props-combinations) Given possible values for each prop, renders your component with all combinations of prop values. Useful for finding edge cases or just seeing all component states at once. ### [Backgrounds](https://github.com/NewSpring/react-storybook-addon-backgrounds) With this addon, you can switch between background colors and background images for your preview components. It is really helpful for styleguides. ### [Material-UI](https://github.com/sm-react/storybook-addon-material-ui) Wraps your story into MuiThemeProvider. It allows you to add your custom themes, switch between them, make changes in the visual editor and download as JSON file ### [i18n tools](https://github.com/joscha/storybook-addon-i18n-tools) With this addon, you can test your storybooks with a different text-direction. It is very useful if you are working on components that have to work both in LTR as well as in RTL languages. ### [JSX preview](https://github.com/Kilix/storybook-addon-jsx) This addon shows a preview of the JSX code for each story. It allows you to configure the display and copy the code with a single click. ### [Intl](https://github.com/truffls/storybook-addon-intl) With this addon you will have an additional panel at the bottom which provides you buttons to switch the locale and directly see the result in the preview. ### [Versions](https://github.com/buildit/storybook-addon-versions) This addon lets you navigate different versions of static Storybook builds. As such you can see how a component has changed over time. ### [Apollo](https://github.com/abhiaiyer91/apollo-storybook-decorator) Wrap your stories with the Apollo client for mocking GraphQL queries/mutations. ### [Screenshot](https://github.com/tsuyoshiwada/storybook-chrome-screenshot) Save the screenshot image of your stories. via [Puppeteer](https://github.com/GoogleChrome/puppeteer). ### [Styles](https://github.com/Sambego/storybook-styles) Add ability to customize styles in the story preview area ### [Figma](https://github.com/hharnisc/storybook-addon-figma) Embed [Figma](https://figma.com) designs in a storybook panel. ### [State](https://github.com/Sambego/storybook-state) Manage state inside a story. Update components when this state changes. ### [State](https://github.com/dump247/storybook-state/) Manage state inside a story. Update components when this state changes. Wrap the story in a function call to setup state management. The story can modify state properties with the provided store. The addon provides a panel to view and reset state.
docs/src/pages/addons/addon-gallery/index.md
0
https://github.com/storybookjs/storybook/commit/c3a9c18ffecbc4f041205bdc5ef96c4f16f4f0c5
[ 0.00017016810306813568, 0.00016663015412632376, 0.0001621601841179654, 0.00016693060752004385, 0.00000253001098826644 ]
{ "id": 0, "code_window": [ " \"express\": \"^4.15.3\",\n", " \"file-loader\": \"^0.11.1\",\n", " \"find-cache-dir\": \"^1.0.0\",\n", " \"global\": \"^4.3.2\",\n", " \"html-webpack-plugin\": \"^2.30.1\",\n", " \"json-loader\": \"^0.5.4\",\n", " \"json-stringify-safe\": \"^5.0.1\",\n", " \"json5\": \"^0.5.1\",\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"html-loader\": \"^0.5.4\",\n" ], "file_path": "app/angular/package.json", "type": "add", "edit_start_line_idx": 54 }
<?xml version="1.0" encoding="utf-8"?> <!-- Generator: Adobe Illustrator 15.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="246.085px" height="50px" viewBox="0 0 246.085 50" enable-background="new 0 0 246.085 50" xml:space="preserve"> <g> <path fill="#FFFFFF" d="M25.119-0.214C11.247-0.214,0,11.026,0,24.893C0,38.758,11.247,50,25.119,50s25.12-11.242,25.12-25.107 C50.24,11.026,38.992-0.214,25.119-0.214z M25.119,48.601C12.017,48.601,1.4,37.983,1.4,24.893 c0-13.094,10.617-23.709,23.719-23.709c13.097,0,23.72,10.615,23.72,23.709C48.839,37.983,38.216,48.601,25.119,48.601z"/> <path fill="#FFFFFF" d="M35.848,20.297c-0.831,0-1.567,0.424-2,1.069l-7.938-2.183c0.02-0.163,0.037-0.327,0.037-0.489 c0-1.953-1.583-3.535-3.532-3.535c-1.952,0-3.534,1.582-3.534,3.535c0,1.546,1.002,2.864,2.396,3.338l-0.681,4.266 c-0.346-0.075-0.702-0.115-1.073-0.115c-2.781,0-5.032,2.252-5.032,5.028c0,2.78,2.251,5.032,5.032,5.032 c2.777,0,5.034-2.252,5.034-5.032c0-0.719-0.154-1.4-0.428-2.021l9.751-5.106c0.434,0.62,1.156,1.028,1.968,1.028 c1.336,0,2.415-1.079,2.415-2.408C38.262,21.373,37.185,20.297,35.848,20.297z M23.719,28.439c-0.557-0.839-1.355-1.5-2.299-1.884 l0.695-4.346c0.099,0.008,0.195,0.012,0.3,0.012c1.486,0,2.755-0.916,3.273-2.212l7.816,2.149 c-0.036,0.174-0.062,0.355-0.062,0.544c0,0.208,0.03,0.409,0.079,0.604L23.719,28.439z"/> </g> <g> <g> <g> <defs> <rect id="SVGID_1_" x="62.506" y="6.883" width="183.579" height="36.234"/> </defs> <clipPath id="SVGID_2_"> <use xlink:href="#SVGID_1_" overflow="visible"/> </clipPath> <path clip-path="url(#SVGID_2_)" fill="#FFFFFF" d="M74.479,33.15c-3.066,1.382-7.519,1.133-9.413-1.23 c-1.205-1.501-1.277-5.82,3.552-6.801c4.922-1.001,8.167,0,8.167,0S77.694,31.701,74.479,33.15L74.479,33.15z M68.186,14.594 c-2.269,0.303-3.698,1.61-3.698,1.61l1.112,1.863c0,0,2.537-2.174,6.885-1.495c2.358,0.369,4.072,1.819,4.29,6.394 c0,0-13.167-1.82-14.153,4.881c-1.194,8.118,7.172,8.902,11.606,7.504c3.24-1.022,3.977-3.314,4.392-4.921 c0.635-2.45,0.454-6.275,0.025-9.465C78.462,19.608,78.106,13.268,68.186,14.594L68.186,14.594z"/> </g> </g> <path fill="#FFFFFF" d="M162.529,33.15c-3.064,1.382-7.52,1.133-9.411-1.23c-1.206-1.501-1.277-5.82,3.55-6.801 c4.924-1.001,8.168,0,8.168,0S165.745,31.701,162.529,33.15L162.529,33.15z M156.237,14.594c-2.269,0.303-3.697,1.61-3.697,1.61 l1.111,1.863c0,0,2.537-2.174,6.886-1.495c2.357,0.369,4.07,1.819,4.288,6.394c0,0-13.166-1.82-14.152,4.881 c-1.195,8.118,7.17,8.902,11.605,7.504c3.24-1.022,3.979-3.314,4.393-4.921c0.634-2.45,0.454-6.275,0.024-9.465 C166.517,19.608,166.157,13.268,156.237,14.594L156.237,14.594z"/> <path fill="#FFFFFF" d="M182.34,17.969c0,0-2.713-2.811-6.534-1.294c-1.741,0.689-2.469,2.502-2.116,3.856 c0.422,1.631,2.043,2.704,4.166,3.262c4.821,1.267,6.106,3.049,6.422,5.314c0.462,3.32-2.152,6.725-6,6.74 c-4.71,0.021-7.428-3.237-7.428-3.237l1.721-1.45c0,0,5.982,5.441,9.391,0.544c0.966-1.389,0.725-4.167-2.688-5.436 c-3.912-1.454-7.034-2.173-7.699-5.312c-1.197-5.658,6.341-8.879,12.079-4.413L182.34,17.969L182.34,17.969z"/> <path fill="#FFFFFF" d="M198.409,16.303c7.486,0.072,6.791,8.334,6.791,8.334h-14.062 C191.139,23.551,192.188,16.244,198.409,16.303L198.409,16.303z M205.187,32.452c-4.105,2.439-8.553,1.716-10.629,0.447 c-3.456-2.113-3.443-6.522-3.443-6.522l15.809,0.015c0.182-1.01,0.071-3.173,0-4.227c-0.311-4.594-3.343-7.628-8.476-7.685 c-5.496-0.062-8.555,4.166-9.16,8.031c-1.149,7.361,1.391,13.287,10.155,13.333c4.631,0.022,6.702-1.732,6.702-1.732 L205.187,32.452L205.187,32.452z"/> <path fill="#FFFFFF" d="M137.726,34.077c-5.229,0.35-6.426-4.234-6.537-5.214c-0.256-2.278-0.198-6.218-0.139-10.204 c0,0,1.701-2.396,6.586-2.065c4.029,0.271,6.679,2.783,6.541,8.57C144.058,30.206,142.788,33.74,137.726,34.077L137.726,34.077z M145.164,31.042c1.264-2.89,1.591-8.503-0.305-12.008c-1.497-2.763-4.019-4.426-7.758-4.426c-4.188,0-6.111,1.624-6.111,1.624 V7.245h-2.175v9.301c0,4.285,0,9.916,0,9.916c0,2.673,0.812,5.375,2.291,7.067c1.295,1.48,4.054,2.86,7.908,2.221 C142.383,35.189,144.06,33.563,145.164,31.042L145.164,31.042z"/> <path fill="#FFFFFF" d="M99.488,25.237c0.139,5.786-2.512,8.3-6.541,8.57c-4.884,0.329-6.586-2.065-6.586-2.065 c-0.062-3.985-0.117-7.926,0.138-10.204c0.111-0.979,1.309-5.564,6.537-5.214C98.099,16.662,99.367,20.194,99.488,25.237 L99.488,25.237z M94.355,14.653c-3.854-0.64-6.583,0.741-7.877,2.219c-1.479,1.691-2.231,4.394-2.231,7.067c0,0,0,5.633,0,9.916 v9.263h2.174v-8.948c0,0,1.863,1.624,6.051,1.624c3.739,0,6.202-1.664,7.696-4.427c1.896-3.506,1.569-9.12,0.305-12.007 C99.369,16.836,97.723,15.212,94.355,14.653L94.355,14.653z"/> <path fill="#FFFFFF" d="M121.591,25.237c0.14,5.786-2.512,8.3-6.54,8.57c-4.883,0.329-6.585-2.065-6.585-2.065 c-0.061-3.985-0.118-7.926,0.139-10.204c0.11-0.979,1.309-5.564,6.536-5.214C120.202,16.662,121.47,20.194,121.591,25.237 L121.591,25.237z M116.458,14.653c-3.854-0.64-6.583,0.741-7.877,2.219c-1.48,1.691-2.231,4.394-2.231,7.067c0,0,0,5.633,0,9.916 v9.263h2.174v-8.948c0,0,1.863,1.624,6.05,1.624c3.739,0,6.202-1.664,7.696-4.427c1.896-3.506,1.57-9.12,0.306-12.007 C121.472,16.836,119.827,15.212,116.458,14.653L116.458,14.653z"/> <polygon fill="#FFFFFF" points="221.579,6.883 221.579,10.869 220.131,10.869 220.131,6.883 "/> <polygon fill="#FFFFFF" points="214.332,31.885 214.332,35.871 212.884,35.871 212.884,31.885 "/> <polygon fill="#FFFFFF" points="220.131,14.492 220.131,35.871 221.579,35.871 221.579,14.492 "/> <path fill="#FFFFFF" d="M236.483,34.271c-4.529,0-8.2-4.063-8.2-9.074c0-5.012,3.669-9.074,8.2-9.074 c4.529,0,8.201,4.062,8.201,9.074C244.685,30.207,241.013,34.271,236.483,34.271L236.483,34.271z M236.483,14.49 c-5.304,0-9.604,4.756-9.604,10.623c0,5.867,4.3,10.624,9.604,10.624c5.302,0,9.602-4.757,9.602-10.624 C246.085,19.247,241.785,14.49,236.483,14.49L236.483,14.49z"/> </g> </svg>
docs/src/pages/logos/appbase.svg
0
https://github.com/storybookjs/storybook/commit/c3a9c18ffecbc4f041205bdc5ef96c4f16f4f0c5
[ 0.0011553042568266392, 0.0004418188182171434, 0.0001646291057113558, 0.0002652406692504883, 0.0003453706158325076 ]
{ "id": 0, "code_window": [ " \"express\": \"^4.15.3\",\n", " \"file-loader\": \"^0.11.1\",\n", " \"find-cache-dir\": \"^1.0.0\",\n", " \"global\": \"^4.3.2\",\n", " \"html-webpack-plugin\": \"^2.30.1\",\n", " \"json-loader\": \"^0.5.4\",\n", " \"json-stringify-safe\": \"^5.0.1\",\n", " \"json5\": \"^0.5.1\",\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"html-loader\": \"^0.5.4\",\n" ], "file_path": "app/angular/package.json", "type": "add", "edit_start_line_idx": 54 }
{ "compileOnSave": false, "compilerOptions": { "emitDecoratorMetadata": true, "experimentalDecorators": true, "skipLibCheck": true, "noImplicitAny": true, "lib": [ "es2016", "dom" ] } }
tsconfig.json
0
https://github.com/storybookjs/storybook/commit/c3a9c18ffecbc4f041205bdc5ef96c4f16f4f0c5
[ 0.00017374481831211597, 0.00017287858645431697, 0.00017201235459651798, 0.00017287858645431697, 8.662318577989936e-7 ]
{ "id": 1, "code_window": [ " \"json-stringify-safe\": \"^5.0.1\",\n", " \"json5\": \"^0.5.1\",\n", " \"lodash.pick\": \"^4.4.0\",\n", " \"postcss-flexbugs-fixes\": \"^3.0.0\",\n", " \"postcss-loader\": \"^2.0.10\",\n", " \"prop-types\": \"^15.5.10\",\n", " \"qs\": \"^6.5.1\",\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"markdown-loader\": \"^2.0.2\",\n" ], "file_path": "app/angular/package.json", "type": "add", "edit_start_line_idx": 59 }
{ "name": "@storybook/vue", "version": "3.4.0-alpha.0", "description": "Storybook for Vue: Develop Vue Component in isolation with Hot Reloading.", "homepage": "https://github.com/storybooks/storybook/tree/master/apps/vue", "bugs": { "url": "https://github.com/storybooks/storybook/issues" }, "license": "MIT", "main": "dist/client/index.js", "jsnext:main": "src/client/index.js", "bin": { "build-storybook": "./bin/build.js", "start-storybook": "./bin/index.js", "storybook-server": "./bin/index.js" }, "repository": { "type": "git", "url": "https://github.com/storybooks/storybook.git" }, "scripts": { "dev": "cross-env DEV_BUILD=1 nodemon --watch ./src --exec \"yarn prepare\"", "prepare": "node ../../scripts/prepare.js" }, "dependencies": { "@storybook/addon-actions": "^3.4.0-alpha.0", "@storybook/addon-links": "^3.4.0-alpha.0", "@storybook/addons": "^3.4.0-alpha.0", "@storybook/channel-postmessage": "^3.4.0-alpha.0", "@storybook/core": "^3.4.0-alpha.0", "@storybook/ui": "^3.4.0-alpha.0", "airbnb-js-shims": "^1.4.0", "autoprefixer": "^7.2.4", "babel-loader": "^7.1.2", "babel-plugin-react-docgen": "^1.8.0", "babel-plugin-transform-regenerator": "^6.26.0", "babel-plugin-transform-runtime": "^6.23.0", "babel-preset-env": "^1.6.0", "babel-preset-minify": "^0.2.0", "babel-preset-react": "^6.24.1", "babel-preset-react-app": "^3.1.0", "babel-preset-stage-0": "^6.24.1", "babel-runtime": "^6.26.0", "case-sensitive-paths-webpack-plugin": "^2.1.1", "chalk": "^2.3.0", "commander": "^2.12.2", "common-tags": "^1.6.0", "configstore": "^3.1.1", "core-js": "^2.5.3", "css-loader": "^0.28.8", "dotenv-webpack": "^1.5.4", "express": "^4.16.2", "file-loader": "^1.1.6", "find-cache-dir": "^1.0.0", "global": "^4.3.2", "html-webpack-plugin": "^2.30.1", "json-loader": "^0.5.7", "json-stringify-safe": "^5.0.1", "json5": "^0.5.1", "postcss-flexbugs-fixes": "^3.2.0", "postcss-loader": "^2.0.10", "prop-types": "^15.6.0", "qs": "^6.5.1", "react": "^16.2.0", "react-dom": "^16.2.0", "redux": "^3.7.2", "request": "^2.83.0", "serve-favicon": "^2.4.5", "shelljs": "^0.7.8", "style-loader": "^0.19.1", "uglifyjs-webpack-plugin": "^1.1.6", "url-loader": "^0.6.2", "util-deprecate": "^1.0.2", "uuid": "^3.1.0", "vue-hot-reload-api": "^2.2.4", "vue-style-loader": "^3.0.1", "webpack": "^3.10.0", "webpack-dev-middleware": "^1.12.2", "webpack-hot-middleware": "^2.21.0" }, "devDependencies": { "nodemon": "^1.14.9", "vue": "^2.5.13", "vue-loader": "^13.6.2", "vue-template-compiler": "^2.5.13" }, "peerDependencies": { "babel-core": "^6.26.0 || ^7.0.0-0", "vue": "2.5.13", "vue-loader": "13.6.2", "vue-template-compiler": "2.5.13" } }
app/vue/package.json
1
https://github.com/storybookjs/storybook/commit/c3a9c18ffecbc4f041205bdc5ef96c4f16f4f0c5
[ 0.4599215090274811, 0.060169607400894165, 0.00016743881860747933, 0.00018301614909432828, 0.1396438330411911 ]
{ "id": 1, "code_window": [ " \"json-stringify-safe\": \"^5.0.1\",\n", " \"json5\": \"^0.5.1\",\n", " \"lodash.pick\": \"^4.4.0\",\n", " \"postcss-flexbugs-fixes\": \"^3.0.0\",\n", " \"postcss-loader\": \"^2.0.10\",\n", " \"prop-types\": \"^15.5.10\",\n", " \"qs\": \"^6.5.1\",\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"markdown-loader\": \"^2.0.2\",\n" ], "file_path": "app/angular/package.json", "type": "add", "edit_start_line_idx": 59 }
apply plugin: "com.android.application" import com.android.build.OutputFile /** * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets * and bundleReleaseJsAndAssets). * These basically call `react-native bundle` with the correct arguments during the Android build * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the * bundle directly from the development server. Below you can see all the possible configurations * and their defaults. If you decide to add a configuration block, make sure to add it before the * `apply from: "../../node_modules/react-native/react.gradle"` line. * * project.ext.react = [ * // the name of the generated asset file containing your JS bundle * bundleAssetName: "index.android.bundle", * * // the entry file for bundle generation * entryFile: "index.android.js", * * // whether to bundle JS and assets in debug mode * bundleInDebug: false, * * // whether to bundle JS and assets in release mode * bundleInRelease: true, * * // whether to bundle JS and assets in another build variant (if configured). * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants * // The configuration property can be in the following formats * // 'bundleIn${productFlavor}${buildType}' * // 'bundleIn${buildType}' * // bundleInFreeDebug: true, * // bundleInPaidRelease: true, * // bundleInBeta: true, * * // whether to disable dev mode in custom build variants (by default only disabled in release) * // for example: to disable dev mode in the staging build type (if configured) * devDisabledInStaging: true, * // The configuration property can be in the following formats * // 'devDisabledIn${productFlavor}${buildType}' * // 'devDisabledIn${buildType}' * * // the root of your project, i.e. where "package.json" lives * root: "../../", * * // where to put the JS bundle asset in debug mode * jsBundleDirDebug: "$buildDir/intermediates/assets/debug", * * // where to put the JS bundle asset in release mode * jsBundleDirRelease: "$buildDir/intermediates/assets/release", * * // where to put drawable resources / React Native assets, e.g. the ones you use via * // require('./image.png')), in debug mode * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug", * * // where to put drawable resources / React Native assets, e.g. the ones you use via * // require('./image.png')), in release mode * resourcesDirRelease: "$buildDir/intermediates/res/merged/release", * * // by default the gradle tasks are skipped if none of the JS files or assets change; this means * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to * // date; if you have any other folders that you want to ignore for performance reasons (gradle * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/ * // for example, you might want to remove it from here. * inputExcludes: ["android/**", "ios/**"], * * // override which node gets called and with what additional arguments * nodeExecutableAndArgs: ["node"], * * // supply additional arguments to the packager * extraPackagerArgs: [] * ] */ project.ext.react = [ entryFile: "index.js" ] apply from: "../../node_modules/react-native/react.gradle" /** * Set this to true to create two separate APKs instead of one: * - An APK that only works on ARM devices * - An APK that only works on x86 devices * The advantage is the size of the APK is reduced by about 4MB. * Upload all the APKs to the Play Store and people will download * the correct one based on the CPU architecture of their device. */ def enableSeparateBuildPerCPUArchitecture = false /** * Run Proguard to shrink the Java bytecode in release builds. */ def enableProguardInReleaseBuilds = false android { compileSdkVersion 23 buildToolsVersion "23.0.1" defaultConfig { applicationId "com.react-native-vanilla" minSdkVersion 16 targetSdkVersion 22 versionCode 1 versionName "1.0" ndk { abiFilters "armeabi-v7a", "x86" } } splits { abi { reset() enable enableSeparateBuildPerCPUArchitecture universalApk false // If true, also generate a universal APK include "armeabi-v7a", "x86" } } buildTypes { release { minifyEnabled enableProguardInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" } } // applicationVariants are e.g. debug, release applicationVariants.all { variant -> variant.outputs.each { output -> // For each separate APK per architecture, set a unique version code as described here: // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits def versionCodes = ["armeabi-v7a":1, "x86":2] def abi = output.getFilter(OutputFile.ABI) if (abi != null) { // null for the universal-debug, universal-release variants output.versionCodeOverride = versionCodes.get(abi) * 1048576 + defaultConfig.versionCode } } } } dependencies { compile fileTree(dir: "libs", include: ["*.jar"]) compile "com.android.support:appcompat-v7:23.0.1" compile "com.facebook.react:react-native:+" // From node_modules } // Run this once to be able to run the application with BUCK // puts all compile dependencies into folder libs for BUCK to use task copyDownloadableDepsToLibs(type: Copy) { from configurations.compile into 'libs' }
examples/react-native-vanilla/android/app/build.gradle
0
https://github.com/storybookjs/storybook/commit/c3a9c18ffecbc4f041205bdc5ef96c4f16f4f0c5
[ 0.00018036544497590512, 0.00016825986676849425, 0.00016295471868943423, 0.00016716084792278707, 0.000004082237410329981 ]
{ "id": 1, "code_window": [ " \"json-stringify-safe\": \"^5.0.1\",\n", " \"json5\": \"^0.5.1\",\n", " \"lodash.pick\": \"^4.4.0\",\n", " \"postcss-flexbugs-fixes\": \"^3.0.0\",\n", " \"postcss-loader\": \"^2.0.10\",\n", " \"prop-types\": \"^15.5.10\",\n", " \"qs\": \"^6.5.1\",\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"markdown-loader\": \"^2.0.2\",\n" ], "file_path": "app/angular/package.json", "type": "add", "edit_start_line_idx": 59 }
export default { main: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, };
examples/crna-kitchen-sink/storybook/stories/CenterView/style.js
0
https://github.com/storybookjs/storybook/commit/c3a9c18ffecbc4f041205bdc5ef96c4f16f4f0c5
[ 0.00016949557175394148, 0.00016949557175394148, 0.00016949557175394148, 0.00016949557175394148, 0 ]
{ "id": 1, "code_window": [ " \"json-stringify-safe\": \"^5.0.1\",\n", " \"json5\": \"^0.5.1\",\n", " \"lodash.pick\": \"^4.4.0\",\n", " \"postcss-flexbugs-fixes\": \"^3.0.0\",\n", " \"postcss-loader\": \"^2.0.10\",\n", " \"prop-types\": \"^15.5.10\",\n", " \"qs\": \"^6.5.1\",\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"markdown-loader\": \"^2.0.2\",\n" ], "file_path": "app/angular/package.json", "type": "add", "edit_start_line_idx": 59 }
declare module '@storybook/angular/demo' { export const Button: any; export const Welcome: any; }
app/angular/demo.d.ts
0
https://github.com/storybookjs/storybook/commit/c3a9c18ffecbc4f041205bdc5ef96c4f16f4f0c5
[ 0.0001727175695123151, 0.0001727175695123151, 0.0001727175695123151, 0.0001727175695123151, 0 ]
{ "id": 2, "code_window": [ " \"dotenv-webpack\": \"^1.5.4\",\n", " \"express\": \"^4.16.2\",\n", " \"file-loader\": \"^1.1.6\",\n", " \"find-cache-dir\": \"^1.0.0\",\n", " \"global\": \"^4.3.2\",\n", " \"html-webpack-plugin\": \"^2.30.1\",\n", " \"json-loader\": \"^0.5.7\",\n", " \"json-stringify-safe\": \"^5.0.1\",\n", " \"json5\": \"^0.5.1\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"html-loader\": \"^0.5.4\",\n" ], "file_path": "app/vue/package.json", "type": "add", "edit_start_line_idx": 55 }
{ "name": "@storybook/angular", "version": "3.4.0-alpha.0", "description": "Storybook for Angular: Develop Angular Components in isolation with Hot Reloading.", "homepage": "https://github.com/storybooks/storybook/tree/master/apps/angular", "bugs": { "url": "https://github.com/storybooks/storybook/issues" }, "license": "MIT", "main": "dist/client/index.js", "jsnext:main": "src/client/index.js", "bin": { "build-storybook": "./bin/build.js", "start-storybook": "./bin/index.js", "storybook-server": "./bin/index.js" }, "repository": { "type": "git", "url": "https://github.com/storybooks/storybook.git" }, "scripts": { "dev": "cross-env DEV_BUILD=1 nodemon -e js,ts --watch ./src --exec \"yarn prepare\"", "prepare": "node ../../scripts/prepare.js" }, "dependencies": { "@storybook/addon-actions": "^3.4.0-alpha.0", "@storybook/addon-links": "^3.4.0-alpha.0", "@storybook/addons": "^3.4.0-alpha.0", "@storybook/channel-postmessage": "^3.4.0-alpha.0", "@storybook/core": "^3.4.0-alpha.0", "@storybook/ui": "^3.4.0-alpha.0", "airbnb-js-shims": "^1.1.1", "angular2-template-loader": "^0.6.2", "autoprefixer": "^7.2.4", "babel-core": "^6.26.0", "babel-loader": "^7.0.0", "babel-plugin-react-docgen": "^1.6.0", "babel-preset-env": "^1.6.0", "babel-preset-react": "^6.24.1", "babel-preset-react-app": "^3.0.0", "babel-preset-stage-0": "^6.24.1", "babel-runtime": "^6.23.0", "case-sensitive-paths-webpack-plugin": "^2.0.0", "chalk": "^2.1.0", "commander": "^2.11.0", "common-tags": "^1.4.0", "configstore": "^3.1.0", "core-js": "^2.4.1", "cross-env": "^5.1.1", "css-loader": "^0.28.8", "express": "^4.15.3", "file-loader": "^0.11.1", "find-cache-dir": "^1.0.0", "global": "^4.3.2", "html-webpack-plugin": "^2.30.1", "json-loader": "^0.5.4", "json-stringify-safe": "^5.0.1", "json5": "^0.5.1", "lodash.pick": "^4.4.0", "postcss-flexbugs-fixes": "^3.0.0", "postcss-loader": "^2.0.10", "prop-types": "^15.5.10", "qs": "^6.5.1", "raw-loader": "^0.5.1", "react": "^16.0.0", "react-dom": "^16.0.0", "react-modal": "^2.2.4", "redux": "^3.6.0", "request": "^2.81.0", "rxjs": "^5.4.2", "serve-favicon": "^2.4.3", "shelljs": "^0.7.8", "style-loader": "^0.18.2", "ts-loader": "^2.2.2", "uglifyjs-webpack-plugin": "^1.1.6", "url-loader": "^0.5.8", "util-deprecate": "^1.0.2", "uuid": "^3.1.0", "webpack": "^2.5.1 || ^3.0.0", "webpack-dev-middleware": "^1.10.2", "webpack-hot-middleware": "^2.18.0", "zone.js": "^0.8.19" }, "devDependencies": { "babel-cli": "^6.26.0", "babel-plugin-transform-decorators": "^6.24.1", "babel-plugin-transform-decorators-legacy": "^1.3.4", "codelyzer": "^3.1.2", "mock-fs": "^4.3.0", "nodemon": "^1.14.9", "typescript": "^2.4.0" }, "peerDependencies": { "@angular/common": ">=4.0.0", "@angular/compiler": ">=4.0.0", "@angular/core": ">=4.0.0", "@angular/platform-browser": ">=4.0.0", "@angular/platform-browser-dynamic": ">=4.0.0" } }
app/angular/package.json
1
https://github.com/storybookjs/storybook/commit/c3a9c18ffecbc4f041205bdc5ef96c4f16f4f0c5
[ 0.24788087606430054, 0.022700224071741104, 0.0001639537513256073, 0.00016934130690060556, 0.07120838761329651 ]
{ "id": 2, "code_window": [ " \"dotenv-webpack\": \"^1.5.4\",\n", " \"express\": \"^4.16.2\",\n", " \"file-loader\": \"^1.1.6\",\n", " \"find-cache-dir\": \"^1.0.0\",\n", " \"global\": \"^4.3.2\",\n", " \"html-webpack-plugin\": \"^2.30.1\",\n", " \"json-loader\": \"^0.5.7\",\n", " \"json-stringify-safe\": \"^5.0.1\",\n", " \"json5\": \"^0.5.1\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"html-loader\": \"^0.5.4\",\n" ], "file_path": "app/vue/package.json", "type": "add", "edit_start_line_idx": 55 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"> <g fill="#61DAFB"> <path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/> <circle cx="420.9" cy="296.5" r="45.7"/> <path d="M520.5 78.1z"/> </g> </svg>
lib/cli/test/fixtures/react_scripts/src/logo.svg
0
https://github.com/storybookjs/storybook/commit/c3a9c18ffecbc4f041205bdc5ef96c4f16f4f0c5
[ 0.008260422386229038, 0.008260422386229038, 0.008260422386229038, 0.008260422386229038, 0 ]
{ "id": 2, "code_window": [ " \"dotenv-webpack\": \"^1.5.4\",\n", " \"express\": \"^4.16.2\",\n", " \"file-loader\": \"^1.1.6\",\n", " \"find-cache-dir\": \"^1.0.0\",\n", " \"global\": \"^4.3.2\",\n", " \"html-webpack-plugin\": \"^2.30.1\",\n", " \"json-loader\": \"^0.5.7\",\n", " \"json-stringify-safe\": \"^5.0.1\",\n", " \"json5\": \"^0.5.1\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"html-loader\": \"^0.5.4\",\n" ], "file_path": "app/vue/package.json", "type": "add", "edit_start_line_idx": 55 }
/* global document */ import renderStorybookUI from '@storybook/ui'; import Provider from './provider'; const rootEl = document.getElementById('root'); renderStorybookUI(rootEl, new Provider());
app/vue/src/client/manager/index.js
0
https://github.com/storybookjs/storybook/commit/c3a9c18ffecbc4f041205bdc5ef96c4f16f4f0c5
[ 0.0001745403278619051, 0.0001745403278619051, 0.0001745403278619051, 0.0001745403278619051, 0 ]
{ "id": 2, "code_window": [ " \"dotenv-webpack\": \"^1.5.4\",\n", " \"express\": \"^4.16.2\",\n", " \"file-loader\": \"^1.1.6\",\n", " \"find-cache-dir\": \"^1.0.0\",\n", " \"global\": \"^4.3.2\",\n", " \"html-webpack-plugin\": \"^2.30.1\",\n", " \"json-loader\": \"^0.5.7\",\n", " \"json-stringify-safe\": \"^5.0.1\",\n", " \"json5\": \"^0.5.1\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"html-loader\": \"^0.5.4\",\n" ], "file_path": "app/vue/package.json", "type": "add", "edit_start_line_idx": 55 }
--- path: /404.html --- # NOT FOUND You just hit a route that doesn't exist... the sadness. We're working on improving this page, sorry. [Go to the main page](/)
docs/src/pages/404.md
0
https://github.com/storybookjs/storybook/commit/c3a9c18ffecbc4f041205bdc5ef96c4f16f4f0c5
[ 0.00017099728574976325, 0.00016847639926709235, 0.00016595552733633667, 0.00016847639926709235, 0.000002520879206713289 ]
{ "id": 3, "code_window": [ " \"html-webpack-plugin\": \"^2.30.1\",\n", " \"json-loader\": \"^0.5.7\",\n", " \"json-stringify-safe\": \"^5.0.1\",\n", " \"json5\": \"^0.5.1\",\n", " \"postcss-flexbugs-fixes\": \"^3.2.0\",\n", " \"postcss-loader\": \"^2.0.10\",\n", " \"prop-types\": \"^15.6.0\",\n", " \"qs\": \"^6.5.1\",\n", " \"react\": \"^16.2.0\",\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"markdown-loader\": \"^2.0.2\",\n" ], "file_path": "app/vue/package.json", "type": "add", "edit_start_line_idx": 59 }
{ "name": "@storybook/vue", "version": "3.4.0-alpha.0", "description": "Storybook for Vue: Develop Vue Component in isolation with Hot Reloading.", "homepage": "https://github.com/storybooks/storybook/tree/master/apps/vue", "bugs": { "url": "https://github.com/storybooks/storybook/issues" }, "license": "MIT", "main": "dist/client/index.js", "jsnext:main": "src/client/index.js", "bin": { "build-storybook": "./bin/build.js", "start-storybook": "./bin/index.js", "storybook-server": "./bin/index.js" }, "repository": { "type": "git", "url": "https://github.com/storybooks/storybook.git" }, "scripts": { "dev": "cross-env DEV_BUILD=1 nodemon --watch ./src --exec \"yarn prepare\"", "prepare": "node ../../scripts/prepare.js" }, "dependencies": { "@storybook/addon-actions": "^3.4.0-alpha.0", "@storybook/addon-links": "^3.4.0-alpha.0", "@storybook/addons": "^3.4.0-alpha.0", "@storybook/channel-postmessage": "^3.4.0-alpha.0", "@storybook/core": "^3.4.0-alpha.0", "@storybook/ui": "^3.4.0-alpha.0", "airbnb-js-shims": "^1.4.0", "autoprefixer": "^7.2.4", "babel-loader": "^7.1.2", "babel-plugin-react-docgen": "^1.8.0", "babel-plugin-transform-regenerator": "^6.26.0", "babel-plugin-transform-runtime": "^6.23.0", "babel-preset-env": "^1.6.0", "babel-preset-minify": "^0.2.0", "babel-preset-react": "^6.24.1", "babel-preset-react-app": "^3.1.0", "babel-preset-stage-0": "^6.24.1", "babel-runtime": "^6.26.0", "case-sensitive-paths-webpack-plugin": "^2.1.1", "chalk": "^2.3.0", "commander": "^2.12.2", "common-tags": "^1.6.0", "configstore": "^3.1.1", "core-js": "^2.5.3", "css-loader": "^0.28.8", "dotenv-webpack": "^1.5.4", "express": "^4.16.2", "file-loader": "^1.1.6", "find-cache-dir": "^1.0.0", "global": "^4.3.2", "html-webpack-plugin": "^2.30.1", "json-loader": "^0.5.7", "json-stringify-safe": "^5.0.1", "json5": "^0.5.1", "postcss-flexbugs-fixes": "^3.2.0", "postcss-loader": "^2.0.10", "prop-types": "^15.6.0", "qs": "^6.5.1", "react": "^16.2.0", "react-dom": "^16.2.0", "redux": "^3.7.2", "request": "^2.83.0", "serve-favicon": "^2.4.5", "shelljs": "^0.7.8", "style-loader": "^0.19.1", "uglifyjs-webpack-plugin": "^1.1.6", "url-loader": "^0.6.2", "util-deprecate": "^1.0.2", "uuid": "^3.1.0", "vue-hot-reload-api": "^2.2.4", "vue-style-loader": "^3.0.1", "webpack": "^3.10.0", "webpack-dev-middleware": "^1.12.2", "webpack-hot-middleware": "^2.21.0" }, "devDependencies": { "nodemon": "^1.14.9", "vue": "^2.5.13", "vue-loader": "^13.6.2", "vue-template-compiler": "^2.5.13" }, "peerDependencies": { "babel-core": "^6.26.0 || ^7.0.0-0", "vue": "2.5.13", "vue-loader": "13.6.2", "vue-template-compiler": "2.5.13" } }
app/vue/package.json
1
https://github.com/storybookjs/storybook/commit/c3a9c18ffecbc4f041205bdc5ef96c4f16f4f0c5
[ 0.9891209006309509, 0.1970309317111969, 0.00016665880684740841, 0.0001764008484315127, 0.3937014639377594 ]
{ "id": 3, "code_window": [ " \"html-webpack-plugin\": \"^2.30.1\",\n", " \"json-loader\": \"^0.5.7\",\n", " \"json-stringify-safe\": \"^5.0.1\",\n", " \"json5\": \"^0.5.1\",\n", " \"postcss-flexbugs-fixes\": \"^3.2.0\",\n", " \"postcss-loader\": \"^2.0.10\",\n", " \"prop-types\": \"^15.6.0\",\n", " \"qs\": \"^6.5.1\",\n", " \"react\": \"^16.2.0\",\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"markdown-loader\": \"^2.0.2\",\n" ], "file_path": "app/vue/package.json", "type": "add", "edit_start_line_idx": 59 }
export const environment = { production: true };
lib/cli/test/fixtures/angular-cli/src/environments/environment.prod.ts
0
https://github.com/storybookjs/storybook/commit/c3a9c18ffecbc4f041205bdc5ef96c4f16f4f0c5
[ 0.00017236829444300383, 0.00017236829444300383, 0.00017236829444300383, 0.00017236829444300383, 0 ]
{ "id": 3, "code_window": [ " \"html-webpack-plugin\": \"^2.30.1\",\n", " \"json-loader\": \"^0.5.7\",\n", " \"json-stringify-safe\": \"^5.0.1\",\n", " \"json5\": \"^0.5.1\",\n", " \"postcss-flexbugs-fixes\": \"^3.2.0\",\n", " \"postcss-loader\": \"^2.0.10\",\n", " \"prop-types\": \"^15.6.0\",\n", " \"qs\": \"^6.5.1\",\n", " \"react\": \"^16.2.0\",\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"markdown-loader\": \"^2.0.2\",\n" ], "file_path": "app/vue/package.json", "type": "add", "edit_start_line_idx": 59 }
import React from 'react'; import PropTypes from 'prop-types'; import Grid from '../Grid'; import './style.css'; const Examples = ({ items }) => ( <div className="examples"> <div className="heading"> <h1>Storybook Examples</h1> <a className="edit-link" href="https://github.com/storybooks/storybook/blob/master/docs/src/pages/examples/_examples.yml" target="_blank" rel="noopener noreferrer" > Edit this list </a> </div> <Grid columnWidth={350} items={items} /> </div> ); Examples.propTypes = { items: PropTypes.array, // eslint-disable-line react/forbid-prop-types }; Examples.defaultProps = { items: [], }; export { Examples as default };
docs/src/components/Grid/Examples/index.js
0
https://github.com/storybookjs/storybook/commit/c3a9c18ffecbc4f041205bdc5ef96c4f16f4f0c5
[ 0.00017357755859848112, 0.0001718619023449719, 0.00017004254914354533, 0.00017196561384480447, 0.0000014450234857577016 ]
{ "id": 3, "code_window": [ " \"html-webpack-plugin\": \"^2.30.1\",\n", " \"json-loader\": \"^0.5.7\",\n", " \"json-stringify-safe\": \"^5.0.1\",\n", " \"json5\": \"^0.5.1\",\n", " \"postcss-flexbugs-fixes\": \"^3.2.0\",\n", " \"postcss-loader\": \"^2.0.10\",\n", " \"prop-types\": \"^15.6.0\",\n", " \"qs\": \"^6.5.1\",\n", " \"react\": \"^16.2.0\",\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"markdown-loader\": \"^2.0.2\",\n" ], "file_path": "app/vue/package.json", "type": "add", "edit_start_line_idx": 59 }
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (nonatomic, strong) UIWindow *window; @end
lib/cli/test/snapshots/react_native/ios/react_native/AppDelegate.h
0
https://github.com/storybookjs/storybook/commit/c3a9c18ffecbc4f041205bdc5ef96c4f16f4f0c5
[ 0.00017282251792494208, 0.00016835704445838928, 0.00016389155643992126, 0.00016835704445838928, 0.000004465480742510408 ]
{ "id": 0, "code_window": [ "\t\tif (exitCode) {\n", "\t\t\texitCodeMessage = nls.localize('terminal.integrated.exitedWithCode', 'The terminal process terminated with exit code: {0}', exitCode);\n", "\t\t}\n", "\n", "\t\tthis._logService.debug(`Terminal process exit (id: ${this.id})${this._processManager ? ' state ' + this._processManager.processState : ''}`);\n", "\n", "\t\t// Only trigger wait on exit when the exit was *not* triggered by the\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (exitCode! < 0) {\n", "\t\t\texitCodeMessage = nls.localize('terminal.integrated.exitedWithInvalidPath', 'The terminal process terminated as it could not find the specified path : {0}', this._shellLaunchConfig.executable);\n", "\t\t}\n", "\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalInstance.ts", "type": "add", "edit_start_line_idx": 978 }
/*--------------------------------------------------------------------------------------------- * 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 'vs/base/common/path'; import * as dom from 'vs/base/browser/dom'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { debounce } from 'vs/base/common/decorators'; import { Emitter, Event } from 'vs/base/common/event'; import { KeyCode } from 'vs/base/common/keyCodes'; import * as lifecycle from 'vs/base/common/lifecycle'; import * as platform from 'vs/base/common/platform'; import { TabFocus } from 'vs/editor/common/config/commonEditorConfig'; import * as nls from 'vs/nls'; import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService'; import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { ILogService } from 'vs/platform/log/common/log'; import { INotificationService, IPromptChoice, Severity } from 'vs/platform/notification/common/notification'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { activeContrastBorder, scrollbarSliderActiveBackground, scrollbarSliderBackground, scrollbarSliderHoverBackground } from 'vs/platform/theme/common/colorRegistry'; import { ICssStyleCollector, ITheme, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService'; import { PANEL_BACKGROUND } from 'vs/workbench/common/theme'; import { TerminalWidgetManager } from 'vs/workbench/contrib/terminal/browser/terminalWidgetManager'; import { IShellLaunchConfig, ITerminalDimensions, ITerminalInstance, ITerminalProcessManager, KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED, NEVER_MEASURE_RENDER_TIME_STORAGE_KEY, ProcessState, TERMINAL_PANEL_ID, IWindowsShellHelper } from 'vs/workbench/contrib/terminal/common/terminal'; import { ansiColorIdentifiers, TERMINAL_BACKGROUND_COLOR, TERMINAL_CURSOR_BACKGROUND_COLOR, TERMINAL_CURSOR_FOREGROUND_COLOR, TERMINAL_FOREGROUND_COLOR, TERMINAL_SELECTION_BACKGROUND_COLOR } from 'vs/workbench/contrib/terminal/common/terminalColorRegistry'; import { TERMINAL_COMMAND_ID } from 'vs/workbench/contrib/terminal/common/terminalCommands'; import { TerminalConfigHelper } from 'vs/workbench/contrib/terminal/browser/terminalConfigHelper'; import { TerminalLinkHandler } from 'vs/workbench/contrib/terminal/browser/terminalLinkHandler'; import { TerminalCommandTracker } from 'vs/workbench/contrib/terminal/browser/terminalCommandTracker'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { ISearchOptions, Terminal as XTermTerminal } from 'vscode-xterm'; import { IAccessibilityService, AccessibilitySupport } from 'vs/platform/accessibility/common/accessibility'; import { ITerminalInstanceService } from 'vs/workbench/contrib/terminal/browser/terminal'; // How long in milliseconds should an average frame take to render for a notification to appear // which suggests the fallback DOM-based renderer const SLOW_CANVAS_RENDER_THRESHOLD = 50; const NUMBER_OF_FRAMES_TO_MEASURE = 20; export const DEFAULT_COMMANDS_TO_SKIP_SHELL: string[] = [ TERMINAL_COMMAND_ID.CLEAR_SELECTION, TERMINAL_COMMAND_ID.CLEAR, TERMINAL_COMMAND_ID.COPY_SELECTION, TERMINAL_COMMAND_ID.DELETE_TO_LINE_START, TERMINAL_COMMAND_ID.DELETE_WORD_LEFT, TERMINAL_COMMAND_ID.DELETE_WORD_RIGHT, TERMINAL_COMMAND_ID.FIND_WIDGET_FOCUS, TERMINAL_COMMAND_ID.FIND_WIDGET_HIDE, TERMINAL_COMMAND_ID.FIND_NEXT_TERMINAL_FOCUS, TERMINAL_COMMAND_ID.FIND_PREVIOUS_TERMINAL_FOCUS, TERMINAL_COMMAND_ID.TOGGLE_FIND_REGEX_TERMINAL_FOCUS, TERMINAL_COMMAND_ID.TOGGLE_FIND_WHOLE_WORD_TERMINAL_FOCUS, TERMINAL_COMMAND_ID.TOGGLE_FIND_CASE_SENSITIVE_TERMINAL_FOCUS, TERMINAL_COMMAND_ID.FOCUS_NEXT_PANE, TERMINAL_COMMAND_ID.FOCUS_NEXT, TERMINAL_COMMAND_ID.FOCUS_PREVIOUS_PANE, TERMINAL_COMMAND_ID.FOCUS_PREVIOUS, TERMINAL_COMMAND_ID.FOCUS, TERMINAL_COMMAND_ID.KILL, TERMINAL_COMMAND_ID.MOVE_TO_LINE_END, TERMINAL_COMMAND_ID.MOVE_TO_LINE_START, TERMINAL_COMMAND_ID.NEW_IN_ACTIVE_WORKSPACE, TERMINAL_COMMAND_ID.NEW, TERMINAL_COMMAND_ID.PASTE, TERMINAL_COMMAND_ID.RESIZE_PANE_DOWN, TERMINAL_COMMAND_ID.RESIZE_PANE_LEFT, TERMINAL_COMMAND_ID.RESIZE_PANE_RIGHT, TERMINAL_COMMAND_ID.RESIZE_PANE_UP, TERMINAL_COMMAND_ID.RUN_ACTIVE_FILE, TERMINAL_COMMAND_ID.RUN_SELECTED_TEXT, TERMINAL_COMMAND_ID.SCROLL_DOWN_LINE, TERMINAL_COMMAND_ID.SCROLL_DOWN_PAGE, TERMINAL_COMMAND_ID.SCROLL_TO_BOTTOM, TERMINAL_COMMAND_ID.SCROLL_TO_NEXT_COMMAND, TERMINAL_COMMAND_ID.SCROLL_TO_PREVIOUS_COMMAND, TERMINAL_COMMAND_ID.SCROLL_TO_TOP, TERMINAL_COMMAND_ID.SCROLL_UP_LINE, TERMINAL_COMMAND_ID.SCROLL_UP_PAGE, TERMINAL_COMMAND_ID.SEND_SEQUENCE, TERMINAL_COMMAND_ID.SELECT_ALL, TERMINAL_COMMAND_ID.SELECT_TO_NEXT_COMMAND, TERMINAL_COMMAND_ID.SELECT_TO_NEXT_LINE, TERMINAL_COMMAND_ID.SELECT_TO_PREVIOUS_COMMAND, TERMINAL_COMMAND_ID.SELECT_TO_PREVIOUS_LINE, TERMINAL_COMMAND_ID.SPLIT_IN_ACTIVE_WORKSPACE, TERMINAL_COMMAND_ID.SPLIT, TERMINAL_COMMAND_ID.TOGGLE, 'editor.action.toggleTabFocusMode', 'workbench.action.quickOpen', 'workbench.action.quickOpenPreviousEditor', 'workbench.action.showCommands', 'workbench.action.tasks.build', 'workbench.action.tasks.restartTask', 'workbench.action.tasks.runTask', 'workbench.action.tasks.reRunTask', 'workbench.action.tasks.showLog', 'workbench.action.tasks.showTasks', 'workbench.action.tasks.terminate', 'workbench.action.tasks.test', 'workbench.action.toggleFullScreen', 'workbench.action.terminal.focusAtIndex1', 'workbench.action.terminal.focusAtIndex2', 'workbench.action.terminal.focusAtIndex3', 'workbench.action.terminal.focusAtIndex4', 'workbench.action.terminal.focusAtIndex5', 'workbench.action.terminal.focusAtIndex6', 'workbench.action.terminal.focusAtIndex7', 'workbench.action.terminal.focusAtIndex8', 'workbench.action.terminal.focusAtIndex9', 'workbench.action.focusSecondEditorGroup', 'workbench.action.focusThirdEditorGroup', 'workbench.action.focusFourthEditorGroup', 'workbench.action.focusFifthEditorGroup', 'workbench.action.focusSixthEditorGroup', 'workbench.action.focusSeventhEditorGroup', 'workbench.action.focusEighthEditorGroup', 'workbench.action.nextPanelView', 'workbench.action.previousPanelView', 'workbench.action.nextSideBarView', 'workbench.action.previousSideBarView', 'workbench.action.debug.start', 'workbench.action.debug.stop', 'workbench.action.debug.run', 'workbench.action.debug.restart', 'workbench.action.debug.continue', 'workbench.action.debug.pause', 'workbench.action.debug.stepInto', 'workbench.action.debug.stepOut', 'workbench.action.debug.stepOver', 'workbench.action.openNextRecentlyUsedEditorInGroup', 'workbench.action.openPreviousRecentlyUsedEditorInGroup', 'workbench.action.focusActiveEditorGroup', 'workbench.action.focusFirstEditorGroup', 'workbench.action.focusLastEditorGroup', 'workbench.action.firstEditorInGroup', 'workbench.action.lastEditorInGroup', 'workbench.action.navigateUp', 'workbench.action.navigateDown', 'workbench.action.navigateRight', 'workbench.action.navigateLeft', 'workbench.action.togglePanel', 'workbench.action.quickOpenView', 'workbench.action.toggleMaximizedPanel' ]; export class TerminalInstance implements ITerminalInstance { private static readonly EOL_REGEX = /\r?\n/g; private static _lastKnownDimensions: dom.Dimension | null = null; private static _idCounter = 1; private _processManager: ITerminalProcessManager | undefined; private _pressAnyKeyToCloseListener: lifecycle.IDisposable | undefined; private _id: number; private _isExiting: boolean; private _hadFocusOnExit: boolean; private _isVisible: boolean; private _isDisposed: boolean; private _skipTerminalCommands: string[]; private _title: string; private _wrapperElement: HTMLDivElement; private _xterm: XTermTerminal; private _xtermElement: HTMLDivElement; private _terminalHasTextContextKey: IContextKey<boolean>; private _cols: number; private _rows: number; private _dimensionsOverride: ITerminalDimensions; private _windowsShellHelper: IWindowsShellHelper | undefined; private _xtermReadyPromise: Promise<void>; private _titleReadyPromise: Promise<string>; private _titleReadyComplete: (title: string) => any; private _disposables: lifecycle.IDisposable[]; private _messageTitleDisposable: lifecycle.IDisposable | undefined; private _widgetManager: TerminalWidgetManager; private _linkHandler: TerminalLinkHandler; private _commandTracker: TerminalCommandTracker; public disableLayout: boolean; public get id(): number { return this._id; } public get cols(): number { if (this._dimensionsOverride && this._dimensionsOverride.cols) { return Math.min(Math.max(this._dimensionsOverride.cols, 2), this._cols); } return this._cols; } public get rows(): number { if (this._dimensionsOverride && this._dimensionsOverride.rows) { return Math.min(Math.max(this._dimensionsOverride.rows, 2), this._rows); } return this._rows; } // TODO: Ideally processId would be merged into processReady public get processId(): number | undefined { return this._processManager ? this._processManager.shellProcessId : undefined; } // TODO: How does this work with detached processes? // TODO: Should this be an event as it can fire twice? public get processReady(): Promise<void> { return this._processManager ? this._processManager.ptyProcessReady : Promise.resolve(undefined); } public get title(): string { return this._title; } public get hadFocusOnExit(): boolean { return this._hadFocusOnExit; } public get isTitleSetByProcess(): boolean { return !!this._messageTitleDisposable; } public get shellLaunchConfig(): IShellLaunchConfig { return this._shellLaunchConfig; } public get commandTracker(): TerminalCommandTracker { return this._commandTracker; } private readonly _onExit = new Emitter<number>(); public get onExit(): Event<number> { return this._onExit.event; } private readonly _onDisposed = new Emitter<ITerminalInstance>(); public get onDisposed(): Event<ITerminalInstance> { return this._onDisposed.event; } private readonly _onFocused = new Emitter<ITerminalInstance>(); public get onFocused(): Event<ITerminalInstance> { return this._onFocused.event; } private readonly _onProcessIdReady = new Emitter<ITerminalInstance>(); public get onProcessIdReady(): Event<ITerminalInstance> { return this._onProcessIdReady.event; } private readonly _onTitleChanged = new Emitter<ITerminalInstance>(); public get onTitleChanged(): Event<ITerminalInstance> { return this._onTitleChanged.event; } private readonly _onData = new Emitter<string>(); public get onData(): Event<string> { return this._onData.event; } private readonly _onLineData = new Emitter<string>(); public get onLineData(): Event<string> { return this._onLineData.event; } private readonly _onRendererInput = new Emitter<string>(); public get onRendererInput(): Event<string> { return this._onRendererInput.event; } private readonly _onRequestExtHostProcess = new Emitter<ITerminalInstance>(); public get onRequestExtHostProcess(): Event<ITerminalInstance> { return this._onRequestExtHostProcess.event; } private readonly _onDimensionsChanged = new Emitter<void>(); public get onDimensionsChanged(): Event<void> { return this._onDimensionsChanged.event; } private readonly _onFocus = new Emitter<ITerminalInstance>(); public get onFocus(): Event<ITerminalInstance> { return this._onFocus.event; } public constructor( private readonly _terminalFocusContextKey: IContextKey<boolean>, private readonly _configHelper: TerminalConfigHelper, private _container: HTMLElement, private _shellLaunchConfig: IShellLaunchConfig, @ITerminalInstanceService private readonly _terminalInstanceService: ITerminalInstanceService, @IContextKeyService private readonly _contextKeyService: IContextKeyService, @IKeybindingService private readonly _keybindingService: IKeybindingService, @INotificationService private readonly _notificationService: INotificationService, @IPanelService private readonly _panelService: IPanelService, @IInstantiationService private readonly _instantiationService: IInstantiationService, @IClipboardService private readonly _clipboardService: IClipboardService, @IThemeService private readonly _themeService: IThemeService, @IConfigurationService private readonly _configurationService: IConfigurationService, @ILogService private readonly _logService: ILogService, @IStorageService private readonly _storageService: IStorageService, @IAccessibilityService private readonly _accessibilityService: IAccessibilityService ) { this._disposables = []; this._skipTerminalCommands = []; this._isExiting = false; this._hadFocusOnExit = false; this._isVisible = false; this._isDisposed = false; this._id = TerminalInstance._idCounter++; this._titleReadyPromise = new Promise<string>(c => { this._titleReadyComplete = c; }); this._terminalHasTextContextKey = KEYBINDING_CONTEXT_TERMINAL_TEXT_SELECTED.bindTo(this._contextKeyService); this.disableLayout = false; this._logService.trace(`terminalInstance#ctor (id: ${this.id})`, this._shellLaunchConfig); this._initDimensions(); if (!this.shellLaunchConfig.isRendererOnly) { this._createProcess(); } else { this.setTitle(this._shellLaunchConfig.name, false); } this._xtermReadyPromise = this._createXterm(); this._xtermReadyPromise.then(() => { // Only attach xterm.js to the DOM if the terminal panel has been opened before. if (_container) { this._attachToElement(_container); } }); this.addDisposable(this._configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('terminal.integrated')) { this.updateConfig(); // HACK: Trigger another async layout to ensure xterm's CharMeasure is ready to use, // this hack can be removed when https://github.com/xtermjs/xterm.js/issues/702 is // supported. this.setVisible(this._isVisible); } if (e.affectsConfiguration('editor.accessibilitySupport')) { this.updateAccessibilitySupport(); } })); } public addDisposable(disposable: lifecycle.IDisposable): void { this._disposables.push(disposable); } private _initDimensions(): void { // The terminal panel needs to have been created if (!this._container) { return; } const computedStyle = window.getComputedStyle(this._container.parentElement!); const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10); const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10); this._evaluateColsAndRows(width, height); } /** * Evaluates and sets the cols and rows of the terminal if possible. * @param width The width of the container. * @param height The height of the container. * @return The terminal's width if it requires a layout. */ private _evaluateColsAndRows(width: number, height: number): number | null { // Ignore if dimensions are undefined or 0 if (!width || !height) { return null; } const dimension = this._getDimension(width, height); if (!dimension) { return null; } const font = this._configHelper.getFont(this._xterm); if (!font.charWidth || !font.charHeight) { return null; } // Because xterm.js converts from CSS pixels to actual pixels through // the use of canvas, window.devicePixelRatio needs to be used here in // order to be precise. font.charWidth/charHeight alone as insufficient // when window.devicePixelRatio changes. const scaledWidthAvailable = dimension.width * window.devicePixelRatio; let scaledCharWidth: number; if (this._configHelper.config.rendererType === 'dom') { scaledCharWidth = font.charWidth * window.devicePixelRatio; } else { scaledCharWidth = Math.floor(font.charWidth * window.devicePixelRatio) + font.letterSpacing; } this._cols = Math.max(Math.floor(scaledWidthAvailable / scaledCharWidth), 1); const scaledHeightAvailable = dimension.height * window.devicePixelRatio; const scaledCharHeight = Math.ceil(font.charHeight * window.devicePixelRatio); const scaledLineHeight = Math.floor(scaledCharHeight * font.lineHeight); this._rows = Math.max(Math.floor(scaledHeightAvailable / scaledLineHeight), 1); return dimension.width; } private _getDimension(width: number, height: number): dom.Dimension | null { // The font needs to have been initialized const font = this._configHelper.getFont(this._xterm); if (!font || !font.charWidth || !font.charHeight) { return null; } // The panel is minimized if (!this._isVisible) { return TerminalInstance._lastKnownDimensions; } else { // Trigger scroll event manually so that the viewport's scroll area is synced. This // needs to happen otherwise its scrollTop value is invalid when the panel is toggled as // it gets removed and then added back to the DOM (resetting scrollTop to 0). // Upstream issue: https://github.com/sourcelair/xterm.js/issues/291 if (this._xterm) { this._xterm.emit('scroll', this._xterm._core.buffer.ydisp); } } if (!this._wrapperElement) { return null; } const wrapperElementStyle = getComputedStyle(this._wrapperElement); const marginLeft = parseInt(wrapperElementStyle.marginLeft!.split('px')[0], 10); const marginRight = parseInt(wrapperElementStyle.marginRight!.split('px')[0], 10); const bottom = parseInt(wrapperElementStyle.bottom!.split('px')[0], 10); const innerWidth = width - marginLeft - marginRight; const innerHeight = height - bottom; TerminalInstance._lastKnownDimensions = new dom.Dimension(innerWidth, innerHeight); return TerminalInstance._lastKnownDimensions; } /** * Create xterm.js instance and attach data listeners. */ protected async _createXterm(): Promise<void> { const Terminal = await this._terminalInstanceService.getXtermConstructor(); const font = this._configHelper.getFont(undefined, true); const config = this._configHelper.config; this._xterm = new Terminal({ scrollback: config.scrollback, theme: this._getXtermTheme(), drawBoldTextInBrightColors: config.drawBoldTextInBrightColors, fontFamily: font.fontFamily, fontWeight: config.fontWeight, fontWeightBold: config.fontWeightBold, fontSize: font.fontSize, letterSpacing: font.letterSpacing, lineHeight: font.lineHeight, bellStyle: config.enableBell ? 'sound' : 'none', screenReaderMode: this._isScreenReaderOptimized(), macOptionIsMeta: config.macOptionIsMeta, macOptionClickForcesSelection: config.macOptionClickForcesSelection, rightClickSelectsWord: config.rightClickBehavior === 'selectWord', // TODO: Guess whether to use canvas or dom better rendererType: config.rendererType === 'auto' ? 'canvas' : config.rendererType, // TODO: Remove this once the setting is removed upstream experimentalCharAtlas: 'dynamic', experimentalBufferLineImpl: 'TypedArray' }); if (this._shellLaunchConfig.initialText) { this._xterm.writeln(this._shellLaunchConfig.initialText); } this._xterm.on('linefeed', () => this._onLineFeed()); this._xterm.on('key', (key, ev) => this._onKey(key, ev)); if (this._processManager) { this._processManager.onProcessData(data => this._onProcessData(data)); this._xterm.on('data', data => this._processManager!.write(data)); // TODO: How does the cwd work on detached processes? this.processReady.then(async () => { this._linkHandler.processCwd = await this._processManager!.getInitialCwd(); }); // Init winpty compat and link handler after process creation as they rely on the // underlying process OS this._processManager.onProcessReady(() => { if (!this._processManager) { return; } if (this._processManager.os === platform.OperatingSystem.Windows) { this._xterm.winptyCompatInit(); } this._linkHandler = this._instantiationService.createInstance(TerminalLinkHandler, this._xterm, platform.platform, this._processManager); }); } else if (this.shellLaunchConfig.isRendererOnly) { this._linkHandler = this._instantiationService.createInstance(TerminalLinkHandler, this._xterm, undefined, undefined); } this._xterm.on('focus', () => this._onFocus.fire(this)); // Register listener to trigger the onInput ext API if the terminal is a renderer only if (this._shellLaunchConfig.isRendererOnly) { this._xterm.on('data', (data) => this._sendRendererInput(data)); } this._commandTracker = new TerminalCommandTracker(this._xterm); this._disposables.push(this._themeService.onThemeChange(theme => this._updateTheme(theme))); } private _isScreenReaderOptimized(): boolean { const detected = this._accessibilityService.getAccessibilitySupport() === AccessibilitySupport.Enabled; const config = this._configurationService.getValue('editor.accessibilitySupport'); return config === 'on' || (config === 'auto' && detected); } public reattachToElement(container: HTMLElement): void { if (!this._wrapperElement) { throw new Error('The terminal instance has not been attached to a container yet'); } if (this._wrapperElement.parentNode) { this._wrapperElement.parentNode.removeChild(this._wrapperElement); } this._container = container; this._container.appendChild(this._wrapperElement); } public attachToElement(container: HTMLElement): void { // The container did not change, do nothing if (this._container === container) { return; } // Attach has not occured yet if (!this._wrapperElement) { this._attachToElement(container); return; } // The container changed, reattach this._container.removeChild(this._wrapperElement); this._container = container; this._container.appendChild(this._wrapperElement); } public _attachToElement(container: HTMLElement): void { this._xtermReadyPromise.then(() => { if (this._wrapperElement) { throw new Error('The terminal instance has already been attached to a container'); } this._container = container; this._wrapperElement = document.createElement('div'); dom.addClass(this._wrapperElement, 'terminal-wrapper'); this._xtermElement = document.createElement('div'); // Attach the xterm object to the DOM, exposing it to the smoke tests (<any>this._wrapperElement).xterm = this._xterm; this._xterm.open(this._xtermElement); this._xterm.attachCustomKeyEventHandler((event: KeyboardEvent): boolean => { // Disable all input if the terminal is exiting if (this._isExiting) { return false; } // Skip processing by xterm.js of keyboard events that resolve to commands described // within commandsToSkipShell const standardKeyboardEvent = new StandardKeyboardEvent(event); const resolveResult = this._keybindingService.softDispatch(standardKeyboardEvent, standardKeyboardEvent.target); if (resolveResult && this._skipTerminalCommands.some(k => k === resolveResult.commandId)) { event.preventDefault(); return false; } // If tab focus mode is on, tab is not passed to the terminal if (TabFocus.getTabFocusMode() && event.keyCode === 9) { return false; } // Always have alt+F4 skip the terminal on Windows and allow it to be handled by the // system if (platform.isWindows && event.altKey && event.key === 'F4' && !event.ctrlKey) { return false; } return true; }); this._disposables.push(dom.addDisposableListener(this._xterm.element, 'mousedown', () => { // We need to listen to the mouseup event on the document since the user may release // the mouse button anywhere outside of _xterm.element. const listener = dom.addDisposableListener(document, 'mouseup', () => { // Delay with a setTimeout to allow the mouseup to propagate through the DOM // before evaluating the new selection state. setTimeout(() => this._refreshSelectionContextKey(), 0); listener.dispose(); }); })); // xterm.js currently drops selection on keyup as we need to handle this case. this._disposables.push(dom.addDisposableListener(this._xterm.element, 'keyup', () => { // Wait until keyup has propagated through the DOM before evaluating // the new selection state. setTimeout(() => this._refreshSelectionContextKey(), 0); })); const xtermHelper: HTMLElement = <HTMLElement>this._xterm.element.querySelector('.xterm-helpers'); const focusTrap: HTMLElement = document.createElement('div'); focusTrap.setAttribute('tabindex', '0'); dom.addClass(focusTrap, 'focus-trap'); this._disposables.push(dom.addDisposableListener(focusTrap, 'focus', () => { let currentElement = focusTrap; while (!dom.hasClass(currentElement, 'part')) { currentElement = currentElement.parentElement!; } const hidePanelElement = <HTMLElement>currentElement.querySelector('.hide-panel-action'); hidePanelElement.focus(); })); xtermHelper.insertBefore(focusTrap, this._xterm.textarea); this._disposables.push(dom.addDisposableListener(this._xterm.textarea, 'focus', () => { this._terminalFocusContextKey.set(true); this._onFocused.fire(this); })); this._disposables.push(dom.addDisposableListener(this._xterm.textarea, 'blur', () => { this._terminalFocusContextKey.reset(); this._refreshSelectionContextKey(); })); this._disposables.push(dom.addDisposableListener(this._xterm.element, 'focus', () => { this._terminalFocusContextKey.set(true); })); this._disposables.push(dom.addDisposableListener(this._xterm.element, 'blur', () => { this._terminalFocusContextKey.reset(); this._refreshSelectionContextKey(); })); this._wrapperElement.appendChild(this._xtermElement); this._container.appendChild(this._wrapperElement); if (this._processManager) { this._widgetManager = new TerminalWidgetManager(this._wrapperElement); this._processManager.onProcessReady(() => this._linkHandler.setWidgetManager(this._widgetManager)); this._processManager.onProcessReady(() => { if (this._configHelper.config.enableLatencyMitigation) { if (!this._processManager) { return; } this._processManager.getLatency().then(latency => { if (latency > 20 && (this._xterm as any).typeAheadInit) { (this._xterm as any).typeAheadInit(this._processManager, this._themeService); } }); } }); } else if (this._shellLaunchConfig.isRendererOnly) { this._widgetManager = new TerminalWidgetManager(this._wrapperElement); this._linkHandler.setWidgetManager(this._widgetManager); } const computedStyle = window.getComputedStyle(this._container); const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10); const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10); this.layout(new dom.Dimension(width, height)); this.setVisible(this._isVisible); this.updateConfig(); // If IShellLaunchConfig.waitOnExit was true and the process finished before the terminal // panel was initialized. if (this._xterm.getOption('disableStdin')) { this._attachPressAnyKeyToCloseListener(); } const neverMeasureRenderTime = this._storageService.getBoolean(NEVER_MEASURE_RENDER_TIME_STORAGE_KEY, StorageScope.GLOBAL, false); if (!neverMeasureRenderTime && this._configHelper.config.rendererType === 'auto') { this._measureRenderTime(); } }); } private _measureRenderTime(): void { const frameTimes: number[] = []; const textRenderLayer = this._xterm._core.renderer._renderLayers[0]; const originalOnGridChanged = textRenderLayer.onGridChanged; const evaluateCanvasRenderer = () => { // Discard first frame time as it's normal to take longer frameTimes.shift(); const medianTime = frameTimes.sort()[Math.floor(frameTimes.length / 2)]; if (medianTime > SLOW_CANVAS_RENDER_THRESHOLD) { const promptChoices: IPromptChoice[] = [ { label: nls.localize('yes', "Yes"), run: () => { this._configurationService.updateValue('terminal.integrated.rendererType', 'dom', ConfigurationTarget.USER).then(() => { this._notificationService.info(nls.localize('terminal.rendererInAllNewTerminals', "The terminal is now using the fallback renderer.")); }); } } as IPromptChoice, { label: nls.localize('no', "No"), run: () => { } } as IPromptChoice, { label: nls.localize('dontShowAgain', "Don't Show Again"), isSecondary: true, run: () => this._storageService.store(NEVER_MEASURE_RENDER_TIME_STORAGE_KEY, true, StorageScope.GLOBAL) } as IPromptChoice ]; this._notificationService.prompt( Severity.Warning, nls.localize('terminal.slowRendering', 'The standard renderer for the integrated terminal appears to be slow on your computer. Would you like to switch to the alternative DOM-based renderer which may improve performance? [Read more about terminal settings](https://code.visualstudio.com/docs/editor/integrated-terminal#_changing-how-the-terminal-is-rendered).'), promptChoices ); } }; textRenderLayer.onGridChanged = (terminal: XTermTerminal, firstRow: number, lastRow: number) => { const startTime = performance.now(); originalOnGridChanged.call(textRenderLayer, terminal, firstRow, lastRow); frameTimes.push(performance.now() - startTime); if (frameTimes.length === NUMBER_OF_FRAMES_TO_MEASURE) { evaluateCanvasRenderer(); // Restore original function textRenderLayer.onGridChanged = originalOnGridChanged; } }; } public registerLinkMatcher(regex: RegExp, handler: (url: string) => void, matchIndex?: number, validationCallback?: (uri: string, callback: (isValid: boolean) => void) => void): number { return this._linkHandler.registerCustomLinkHandler(regex, handler, matchIndex, validationCallback); } public deregisterLinkMatcher(linkMatcherId: number): void { this._xterm.deregisterLinkMatcher(linkMatcherId); } public hasSelection(): boolean { return this._xterm && this._xterm.hasSelection(); } public copySelection(): void { if (this.hasSelection()) { this._clipboardService.writeText(this._xterm.getSelection()); } else { this._notificationService.warn(nls.localize('terminal.integrated.copySelection.noSelection', 'The terminal has no selection to copy')); } } public get selection(): string | undefined { return this.hasSelection() ? this._xterm.getSelection() : undefined; } public clearSelection(): void { this._xterm.clearSelection(); } public selectAll(): void { // Focus here to ensure the terminal context key is set this._xterm.focus(); this._xterm.selectAll(); } public findNext(term: string, searchOptions: ISearchOptions): boolean { return this._xterm.findNext(term, searchOptions); } public findPrevious(term: string, searchOptions: ISearchOptions): boolean { return this._xterm.findPrevious(term, searchOptions); } public notifyFindWidgetFocusChanged(isFocused: boolean): void { const terminalFocused = !isFocused && (document.activeElement === this._xterm.textarea || document.activeElement === this._xterm.element); this._terminalFocusContextKey.set(terminalFocused); } public dispose(immediate?: boolean): void { this._logService.trace(`terminalInstance#dispose (id: ${this.id})`); lifecycle.dispose(this._windowsShellHelper); this._windowsShellHelper = undefined; this._linkHandler = lifecycle.dispose(this._linkHandler); this._commandTracker = lifecycle.dispose(this._commandTracker); this._widgetManager = lifecycle.dispose(this._widgetManager); if (this._xterm && this._xterm.element) { this._hadFocusOnExit = dom.hasClass(this._xterm.element, 'focus'); } if (this._wrapperElement) { if ((<any>this._wrapperElement).xterm) { (<any>this._wrapperElement).xterm = null; } if (this._wrapperElement.parentElement) { this._container.removeChild(this._wrapperElement); } } if (this._xterm) { const buffer = (<any>this._xterm._core.buffer); this._sendLineData(buffer, buffer.ybase + buffer.y); this._xterm.dispose(); } if (this._pressAnyKeyToCloseListener) { this._pressAnyKeyToCloseListener.dispose(); this._pressAnyKeyToCloseListener = undefined; } if (this._processManager) { this._processManager.dispose(immediate); } else { // In cases where there is no associated process (for example executing an extension callback task) // consumers still expect on onExit event to be fired. An example of this is terminating the extension callback // task. this._onExit.fire(0); } if (!this._isDisposed) { this._isDisposed = true; this._onDisposed.fire(this); } this._disposables = lifecycle.dispose(this._disposables); } public rendererExit(exitCode: number): void { // The use of this API is for cases where there is no backing process behind a terminal // instance (eg. a custom execution task). if (!this.shellLaunchConfig.isRendererOnly) { throw new Error('rendererExit is only expected to be called on a renderer only terminal'); } return this._onProcessExit(exitCode); } public forceRedraw(): void { if (this._configHelper.config.experimentalRefreshOnResume) { if (this._xterm.getOption('rendererType') !== 'dom') { this._xterm.setOption('rendererType', 'dom'); // Do this asynchronously to clear our the texture atlas as all terminals will not // be using canvas setTimeout(() => this._xterm.setOption('rendererType', 'canvas'), 0); } } this._xterm.refresh(0, this._xterm.rows - 1); } public focus(force?: boolean): void { if (!this._xterm) { return; } const selection = window.getSelection(); if (!selection) { return; } const text = selection.toString(); if (!text || force) { this._xterm.focus(); } } public focusWhenReady(force?: boolean): Promise<void> { return this._xtermReadyPromise.then(() => this.focus(force)); } public paste(): void { this.focus(); document.execCommand('paste'); } public write(text: string): void { this._xtermReadyPromise.then(() => { if (!this._xterm) { return; } this._xterm.write(text); if (this._shellLaunchConfig.isRendererOnly) { // Fire onData API in the extension host this._onData.fire(text); } }); } public sendText(text: string, addNewLine: boolean): void { // Normalize line endings to 'enter' press. text = text.replace(TerminalInstance.EOL_REGEX, '\r'); if (addNewLine && text.substr(text.length - 1) !== '\r') { text += '\r'; } if (this._shellLaunchConfig.isRendererOnly) { // If the terminal is a renderer only, fire the onInput ext API this._sendRendererInput(text); } else { // If the terminal has a process, send it to the process if (this._processManager) { this._processManager.ptyProcessReady.then(() => { this._processManager!.write(text); }); } } } public setVisible(visible: boolean): void { this._isVisible = visible; if (this._wrapperElement) { dom.toggleClass(this._wrapperElement, 'active', visible); } if (visible && this._xterm) { // Trigger a manual scroll event which will sync the viewport and scroll bar. This is // necessary if the number of rows in the terminal has decreased while it was in the // background since scrollTop changes take no effect but the terminal's position does // change since the number of visible rows decreases. this._xterm.emit('scroll', this._xterm._core.buffer.ydisp); if (this._container && this._container.parentElement) { // Force a layout when the instance becomes invisible. This is particularly important // for ensuring that terminals that are created in the background by an extension will // correctly get correct character measurements in order to render to the screen (see // #34554). const computedStyle = window.getComputedStyle(this._container.parentElement); const width = parseInt(computedStyle.getPropertyValue('width').replace('px', ''), 10); const height = parseInt(computedStyle.getPropertyValue('height').replace('px', ''), 10); this.layout(new dom.Dimension(width, height)); // HACK: Trigger another async layout to ensure xterm's CharMeasure is ready to use, // this hack can be removed when https://github.com/xtermjs/xterm.js/issues/702 is // supported. setTimeout(() => this.layout(new dom.Dimension(width, height)), 0); } } } public scrollDownLine(): void { this._xterm.scrollLines(1); } public scrollDownPage(): void { this._xterm.scrollPages(1); } public scrollToBottom(): void { this._xterm.scrollToBottom(); } public scrollUpLine(): void { this._xterm.scrollLines(-1); } public scrollUpPage(): void { this._xterm.scrollPages(-1); } public scrollToTop(): void { this._xterm.scrollToTop(); } public clear(): void { this._xterm.clear(); } private _refreshSelectionContextKey() { const activePanel = this._panelService.getActivePanel(); const isActive = !!activePanel && activePanel.getId() === TERMINAL_PANEL_ID; this._terminalHasTextContextKey.set(isActive && this.hasSelection()); } protected _createProcess(): void { this._processManager = this._terminalInstanceService.createTerminalProcessManager(this._id, this._configHelper); this._processManager.onProcessReady(() => this._onProcessIdReady.fire(this)); this._processManager.onProcessExit(exitCode => this._onProcessExit(exitCode)); this._processManager.onProcessData(data => this._onData.fire(data)); if (this._shellLaunchConfig.name) { this.setTitle(this._shellLaunchConfig.name, false); } else { // Only listen for process title changes when a name is not provided this.setTitle(this._shellLaunchConfig.executable, true); this._messageTitleDisposable = this._processManager.onProcessTitle(title => this.setTitle(title ? title : '', true)); } if (platform.isWindows) { this._processManager.ptyProcessReady.then(() => { if (this._processManager!.remoteAuthority) { return; } this._xtermReadyPromise.then(() => { if (!this._isDisposed) { this._windowsShellHelper = this._terminalInstanceService.createWindowsShellHelper(this._processManager!.shellProcessId, this, this._xterm); } }); }); } // Create the process asynchronously to allow the terminal's container // to be created so dimensions are accurate setTimeout(() => { this._processManager!.createProcess(this._shellLaunchConfig, this._cols, this._rows); }, 0); } private _onProcessData(data: string): void { if (this._widgetManager) { this._widgetManager.closeMessage(); } if (this._xterm) { this._xterm.write(data); } } /** * Called when either a process tied to a terminal has exited or when a terminal renderer * simulates a process exiting (eg. custom execution task). * @param exitCode The exit code of the process, this is undefined when the terminal was exited * through user action. */ private _onProcessExit(exitCode?: number): void { this._logService.debug(`Terminal process exit (id: ${this.id}) with code ${exitCode}`); // Prevent dispose functions being triggered multiple times if (this._isExiting) { return; } this._isExiting = true; let exitCodeMessage: string; if (exitCode) { exitCodeMessage = nls.localize('terminal.integrated.exitedWithCode', 'The terminal process terminated with exit code: {0}', exitCode); } this._logService.debug(`Terminal process exit (id: ${this.id})${this._processManager ? ' state ' + this._processManager.processState : ''}`); // Only trigger wait on exit when the exit was *not* triggered by the // user (via the `workbench.action.terminal.kill` command). if (this._shellLaunchConfig.waitOnExit && (!this._processManager || this._processManager.processState !== ProcessState.KILLED_BY_USER)) { if (exitCode) { this._xterm.writeln(exitCodeMessage!); } if (typeof this._shellLaunchConfig.waitOnExit === 'string') { let message = this._shellLaunchConfig.waitOnExit; // Bold the message and add an extra new line to make it stand out from the rest of the output message = `\r\n\x1b[1m${message}\x1b[0m`; this._xterm.writeln(message); } // Disable all input if the terminal is exiting and listen for next keypress this._xterm.setOption('disableStdin', true); if (this._xterm.textarea) { this._attachPressAnyKeyToCloseListener(); } } else { this.dispose(); if (exitCode) { if (this._processManager && this._processManager.processState === ProcessState.KILLED_DURING_LAUNCH) { let args = ''; if (typeof this._shellLaunchConfig.args === 'string') { args = this._shellLaunchConfig.args; } else if (this._shellLaunchConfig.args && this._shellLaunchConfig.args.length) { args = ' ' + this._shellLaunchConfig.args.map(a => { if (typeof a === 'string' && a.indexOf(' ') !== -1) { return `'${a}'`; } return a; }).join(' '); } if (this._shellLaunchConfig.executable) { this._notificationService.error(nls.localize('terminal.integrated.launchFailed', 'The terminal process command \'{0}{1}\' failed to launch (exit code: {2})', this._shellLaunchConfig.executable, args, exitCode)); } else { this._notificationService.error(nls.localize('terminal.integrated.launchFailedExtHost', 'The terminal process failed to launch (exit code: {0})', exitCode)); } } else { if (this._configHelper.config.showExitAlert) { this._notificationService.error(exitCodeMessage!); } else { console.warn(exitCodeMessage!); } } } } this._onExit.fire(exitCode || 0); } private _attachPressAnyKeyToCloseListener() { if (!this._pressAnyKeyToCloseListener) { this._pressAnyKeyToCloseListener = dom.addDisposableListener(this._xterm.textarea, 'keypress', (event: KeyboardEvent) => { if (this._pressAnyKeyToCloseListener) { this._pressAnyKeyToCloseListener.dispose(); this._pressAnyKeyToCloseListener = undefined; this.dispose(); event.preventDefault(); } }); } } public reuseTerminal(shell: IShellLaunchConfig): void { // Unsubscribe any key listener we may have. if (this._pressAnyKeyToCloseListener) { this._pressAnyKeyToCloseListener.dispose(); this._pressAnyKeyToCloseListener = undefined; } // Kill and clear up the process, making the process manager ready for a new process if (this._processManager) { this._processManager.dispose(); this._processManager = undefined; } // Ensure new processes' output starts at start of new line this._xterm.write('\n\x1b[G'); // Print initialText if specified if (shell.initialText) { this._xterm.writeln(shell.initialText); } const oldTitle = this._title; // Clean up waitOnExit state if (this._isExiting && this._shellLaunchConfig.waitOnExit) { this._xterm.setOption('disableStdin', false); this._isExiting = false; } // Set the new shell launch config this._shellLaunchConfig = shell; // Must be done before calling _createProcess() // Launch the process unless this is only a renderer. // In the renderer only cases, we still need to set the title correctly. if (!this._shellLaunchConfig.isRendererOnly) { this._createProcess(); } else if (this._shellLaunchConfig.name) { this.setTitle(this._shellLaunchConfig.name, false); } if (oldTitle !== this._title) { this.setTitle(this._title, true); } if (this._processManager) { // The "!" operator is required here because _processManager is set to undefiend earlier // and TS does not know that createProcess sets it. this._processManager!.onProcessData(data => this._onProcessData(data)); } } private _sendRendererInput(input: string): void { if (this._processManager) { throw new Error('onRendererInput attempted to be used on a regular terminal'); } // For terminal renderers onData fires on keystrokes and when sendText is called. this._onRendererInput.fire(input); } private _onLineFeed(): void { const buffer = (<any>this._xterm._core.buffer); const newLine = buffer.lines.get(buffer.ybase + buffer.y); if (!newLine.isWrapped) { this._sendLineData(buffer, buffer.ybase + buffer.y - 1); } } private _sendLineData(buffer: any, lineIndex: number): void { let lineData = buffer.translateBufferLineToString(lineIndex, true); while (lineIndex >= 0 && buffer.lines.get(lineIndex--).isWrapped) { lineData = buffer.translateBufferLineToString(lineIndex, false) + lineData; } this._onLineData.fire(lineData); } private _onKey(key: string, ev: KeyboardEvent): void { const event = new StandardKeyboardEvent(ev); if (event.equals(KeyCode.Enter)) { this._updateProcessCwd(); } } @debounce(2000) private async _updateProcessCwd(): Promise<string> { // reset cwd if it has changed, so file based url paths can be resolved const cwd = await this.getCwd(); if (cwd) { this._linkHandler.processCwd = cwd; } return cwd; } public updateConfig(): void { const config = this._configHelper.config; this._setCursorBlink(config.cursorBlinking); this._setCursorStyle(config.cursorStyle); this._setCommandsToSkipShell(config.commandsToSkipShell); this._setEnableBell(config.enableBell); this._safeSetOption('scrollback', config.scrollback); this._safeSetOption('macOptionIsMeta', config.macOptionIsMeta); this._safeSetOption('macOptionClickForcesSelection', config.macOptionClickForcesSelection); this._safeSetOption('rightClickSelectsWord', config.rightClickBehavior === 'selectWord'); this._safeSetOption('rendererType', config.rendererType === 'auto' ? 'canvas' : config.rendererType); } public updateAccessibilitySupport(): void { this._xterm.setOption('screenReaderMode', this._isScreenReaderOptimized()); } private _setCursorBlink(blink: boolean): void { if (this._xterm && this._xterm.getOption('cursorBlink') !== blink) { this._xterm.setOption('cursorBlink', blink); this._xterm.refresh(0, this._xterm.rows - 1); } } private _setCursorStyle(style: string): void { if (this._xterm && this._xterm.getOption('cursorStyle') !== style) { // 'line' is used instead of bar in VS Code to be consistent with editor.cursorStyle const xtermOption = style === 'line' ? 'bar' : style; this._xterm.setOption('cursorStyle', xtermOption); } } private _setCommandsToSkipShell(commands: string[]): void { const excludeCommands = commands.filter(command => command[0] === '-').map(command => command.slice(1)); this._skipTerminalCommands = DEFAULT_COMMANDS_TO_SKIP_SHELL.filter(defaultCommand => { return excludeCommands.indexOf(defaultCommand) === -1; }).concat(commands); } private _setEnableBell(isEnabled: boolean): void { if (this._xterm) { if (this._xterm.getOption('bellStyle') === 'sound') { if (!this._configHelper.config.enableBell) { this._xterm.setOption('bellStyle', 'none'); } } else { if (this._configHelper.config.enableBell) { this._xterm.setOption('bellStyle', 'sound'); } } } } private _safeSetOption(key: string, value: any): void { if (!this._xterm) { return; } if (this._xterm.getOption(key) !== value) { this._xterm.setOption(key, value); } } public layout(dimension: dom.Dimension): void { if (this.disableLayout) { return; } const terminalWidth = this._evaluateColsAndRows(dimension.width, dimension.height); if (!terminalWidth) { return; } if (this._xterm) { this._xterm.element.style.width = terminalWidth + 'px'; } this._resize(); } @debounce(50) private _resize(): void { let cols = this.cols; let rows = this.rows; if (this._xterm) { // Only apply these settings when the terminal is visible so that // the characters are measured correctly. if (this._isVisible) { const font = this._configHelper.getFont(this._xterm); const config = this._configHelper.config; this._safeSetOption('letterSpacing', font.letterSpacing); this._safeSetOption('lineHeight', font.lineHeight); this._safeSetOption('fontSize', font.fontSize); this._safeSetOption('fontFamily', font.fontFamily); this._safeSetOption('fontWeight', config.fontWeight); this._safeSetOption('fontWeightBold', config.fontWeightBold); this._safeSetOption('drawBoldTextInBrightColors', config.drawBoldTextInBrightColors); } if (cols !== this._xterm.cols || rows !== this._xterm.rows) { this._onDimensionsChanged.fire(); } this._xterm.resize(cols, rows); if (this._isVisible) { // HACK: Force the renderer to unpause by simulating an IntersectionObserver event. // This is to fix an issue where dragging the window to the top of the screen to // maximize on Windows/Linux would fire an event saying that the terminal was not // visible. if (this._xterm.getOption('rendererType') === 'canvas') { this._xterm._core.renderer.onIntersectionChange({ intersectionRatio: 1 }); // HACK: Force a refresh of the screen to ensure links are refresh corrected. // This can probably be removed when the above hack is fixed in Chromium. this._xterm.refresh(0, this._xterm.rows - 1); } } } if (this._processManager) { this._processManager.ptyProcessReady.then(() => this._processManager!.setDimensions(cols, rows)); } } public setTitle(title: string | undefined, eventFromProcess: boolean): void { if (!title) { return; } if (eventFromProcess) { title = path.basename(title); if (platform.isWindows) { // Remove the .exe extension title = title.split('.exe')[0]; } } else { // If the title has not been set by the API or the rename command, unregister the handler that // automatically updates the terminal name if (this._messageTitleDisposable) { lifecycle.dispose(this._messageTitleDisposable); lifecycle.dispose(this._windowsShellHelper); this._messageTitleDisposable = undefined; this._windowsShellHelper = undefined; } } const didTitleChange = title !== this._title; const oldTitle = this._title; this._title = title; if (didTitleChange) { if (!oldTitle) { this._titleReadyComplete(title); } this._onTitleChanged.fire(this); } } public waitForTitle(): Promise<string> { return this._titleReadyPromise; } public setDimensions(dimensions: ITerminalDimensions): void { this._dimensionsOverride = dimensions; this._resize(); } private _getXtermTheme(theme?: ITheme): any { if (!theme) { theme = this._themeService.getTheme(); } const foregroundColor = theme.getColor(TERMINAL_FOREGROUND_COLOR); const backgroundColor = theme.getColor(TERMINAL_BACKGROUND_COLOR) || theme.getColor(PANEL_BACKGROUND); const cursorColor = theme.getColor(TERMINAL_CURSOR_FOREGROUND_COLOR) || foregroundColor; const cursorAccentColor = theme.getColor(TERMINAL_CURSOR_BACKGROUND_COLOR) || backgroundColor; const selectionColor = theme.getColor(TERMINAL_SELECTION_BACKGROUND_COLOR); return { background: backgroundColor ? backgroundColor.toString() : null, foreground: foregroundColor ? foregroundColor.toString() : null, cursor: cursorColor ? cursorColor.toString() : null, cursorAccent: cursorAccentColor ? cursorAccentColor.toString() : null, selection: selectionColor ? selectionColor.toString() : null, black: theme.getColor(ansiColorIdentifiers[0])!.toString(), red: theme.getColor(ansiColorIdentifiers[1])!.toString(), green: theme.getColor(ansiColorIdentifiers[2])!.toString(), yellow: theme.getColor(ansiColorIdentifiers[3])!.toString(), blue: theme.getColor(ansiColorIdentifiers[4])!.toString(), magenta: theme.getColor(ansiColorIdentifiers[5])!.toString(), cyan: theme.getColor(ansiColorIdentifiers[6])!.toString(), white: theme.getColor(ansiColorIdentifiers[7])!.toString(), brightBlack: theme.getColor(ansiColorIdentifiers[8])!.toString(), brightRed: theme.getColor(ansiColorIdentifiers[9])!.toString(), brightGreen: theme.getColor(ansiColorIdentifiers[10])!.toString(), brightYellow: theme.getColor(ansiColorIdentifiers[11])!.toString(), brightBlue: theme.getColor(ansiColorIdentifiers[12])!.toString(), brightMagenta: theme.getColor(ansiColorIdentifiers[13])!.toString(), brightCyan: theme.getColor(ansiColorIdentifiers[14])!.toString(), brightWhite: theme.getColor(ansiColorIdentifiers[15])!.toString() }; } private _updateTheme(theme?: ITheme): void { this._xterm.setOption('theme', this._getXtermTheme(theme)); } public toggleEscapeSequenceLogging(): void { this._xterm._core.debug = !this._xterm._core.debug; this._xterm.setOption('debug', this._xterm._core.debug); } public getInitialCwd(): Promise<string> { if (!this._processManager) { return Promise.resolve(''); } return this._processManager.getInitialCwd(); } public getCwd(): Promise<string> { if (!this._processManager) { return Promise.resolve(''); } return this._processManager.getCwd(); } } registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => { // Border const border = theme.getColor(activeContrastBorder); if (border) { collector.addRule(` .hc-black .monaco-workbench .panel.integrated-terminal .xterm.focus::before, .hc-black .monaco-workbench .panel.integrated-terminal .xterm:focus::before { border-color: ${border}; }` ); } // Scrollbar const scrollbarSliderBackgroundColor = theme.getColor(scrollbarSliderBackground); if (scrollbarSliderBackgroundColor) { collector.addRule(` .monaco-workbench .panel.integrated-terminal .find-focused .xterm .xterm-viewport, .monaco-workbench .panel.integrated-terminal .xterm.focus .xterm-viewport, .monaco-workbench .panel.integrated-terminal .xterm:focus .xterm-viewport, .monaco-workbench .panel.integrated-terminal .xterm:hover .xterm-viewport { background-color: ${scrollbarSliderBackgroundColor} !important; }` ); } const scrollbarSliderHoverBackgroundColor = theme.getColor(scrollbarSliderHoverBackground); if (scrollbarSliderHoverBackgroundColor) { collector.addRule(`.monaco-workbench .panel.integrated-terminal .xterm .xterm-viewport::-webkit-scrollbar-thumb:hover { background-color: ${scrollbarSliderHoverBackgroundColor}; }`); } const scrollbarSliderActiveBackgroundColor = theme.getColor(scrollbarSliderActiveBackground); if (scrollbarSliderActiveBackgroundColor) { collector.addRule(`.monaco-workbench .panel.integrated-terminal .xterm .xterm-viewport::-webkit-scrollbar-thumb:active { background-color: ${scrollbarSliderActiveBackgroundColor}; }`); } });
src/vs/workbench/contrib/terminal/browser/terminalInstance.ts
1
https://github.com/microsoft/vscode/commit/d76b2030095513e31b61ecf7adb92964050f2a19
[ 0.9954621195793152, 0.008216538466513157, 0.00016276822134386748, 0.00017462456889916211, 0.08390336483716965 ]
{ "id": 0, "code_window": [ "\t\tif (exitCode) {\n", "\t\t\texitCodeMessage = nls.localize('terminal.integrated.exitedWithCode', 'The terminal process terminated with exit code: {0}', exitCode);\n", "\t\t}\n", "\n", "\t\tthis._logService.debug(`Terminal process exit (id: ${this.id})${this._processManager ? ' state ' + this._processManager.processState : ''}`);\n", "\n", "\t\t// Only trigger wait on exit when the exit was *not* triggered by the\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (exitCode! < 0) {\n", "\t\t\texitCodeMessage = nls.localize('terminal.integrated.exitedWithInvalidPath', 'The terminal process terminated as it could not find the specified path : {0}', this._shellLaunchConfig.executable);\n", "\t\t}\n", "\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalInstance.ts", "type": "add", "edit_start_line_idx": 978 }
{ "Region Start": { "prefix": "#region", "body": [ "#region" ], "description": "Folding Region Start" }, "Region End": { "prefix": "#endregion", "body": [ "#endregion" ], "description": "Folding Region End" } }
extensions/coffeescript/snippets/coffeescript.snippets.json
0
https://github.com/microsoft/vscode/commit/d76b2030095513e31b61ecf7adb92964050f2a19
[ 0.00017563534493092448, 0.00017506946460343897, 0.00017450356972403824, 0.00017506946460343897, 5.65887603443116e-7 ]
{ "id": 0, "code_window": [ "\t\tif (exitCode) {\n", "\t\t\texitCodeMessage = nls.localize('terminal.integrated.exitedWithCode', 'The terminal process terminated with exit code: {0}', exitCode);\n", "\t\t}\n", "\n", "\t\tthis._logService.debug(`Terminal process exit (id: ${this.id})${this._processManager ? ' state ' + this._processManager.processState : ''}`);\n", "\n", "\t\t// Only trigger wait on exit when the exit was *not* triggered by the\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (exitCode! < 0) {\n", "\t\t\texitCodeMessage = nls.localize('terminal.integrated.exitedWithInvalidPath', 'The terminal process terminated as it could not find the specified path : {0}', this._shellLaunchConfig.executable);\n", "\t\t}\n", "\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalInstance.ts", "type": "add", "edit_start_line_idx": 978 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { ViewEvent } from 'vs/editor/common/view/viewEvents'; import { ViewEventHandler } from 'vs/editor/common/viewModel/viewEventHandler'; export class ViewEventDispatcher { private readonly _eventHandlerGateKeeper: (callback: () => void) => void; private readonly _eventHandlers: ViewEventHandler[]; private _eventQueue: ViewEvent[] | null; private _isConsumingQueue: boolean; constructor(eventHandlerGateKeeper: (callback: () => void) => void) { this._eventHandlerGateKeeper = eventHandlerGateKeeper; this._eventHandlers = []; this._eventQueue = null; this._isConsumingQueue = false; } public addEventHandler(eventHandler: ViewEventHandler): void { for (let i = 0, len = this._eventHandlers.length; i < len; i++) { if (this._eventHandlers[i] === eventHandler) { console.warn('Detected duplicate listener in ViewEventDispatcher', eventHandler); } } this._eventHandlers.push(eventHandler); } public removeEventHandler(eventHandler: ViewEventHandler): void { for (let i = 0; i < this._eventHandlers.length; i++) { if (this._eventHandlers[i] === eventHandler) { this._eventHandlers.splice(i, 1); break; } } } public emit(event: ViewEvent): void { if (this._eventQueue) { this._eventQueue.push(event); } else { this._eventQueue = [event]; } if (!this._isConsumingQueue) { this.consumeQueue(); } } public emitMany(events: ViewEvent[]): void { if (this._eventQueue) { this._eventQueue = this._eventQueue.concat(events); } else { this._eventQueue = events; } if (!this._isConsumingQueue) { this.consumeQueue(); } } private consumeQueue(): void { this._eventHandlerGateKeeper(() => { try { this._isConsumingQueue = true; this._doConsumeQueue(); } finally { this._isConsumingQueue = false; } }); } private _doConsumeQueue(): void { while (this._eventQueue) { // Empty event queue, as events might come in while sending these off let events = this._eventQueue; this._eventQueue = null; // Use a clone of the event handlers list, as they might remove themselves let eventHandlers = this._eventHandlers.slice(0); for (let i = 0, len = eventHandlers.length; i < len; i++) { eventHandlers[i].handleEvents(events); } } } }
src/vs/editor/common/view/viewEventDispatcher.ts
0
https://github.com/microsoft/vscode/commit/d76b2030095513e31b61ecf7adb92964050f2a19
[ 0.00017533016216475517, 0.0001683649024926126, 0.00016532598237972707, 0.00016737295663915575, 0.000003187067250109976 ]
{ "id": 0, "code_window": [ "\t\tif (exitCode) {\n", "\t\t\texitCodeMessage = nls.localize('terminal.integrated.exitedWithCode', 'The terminal process terminated with exit code: {0}', exitCode);\n", "\t\t}\n", "\n", "\t\tthis._logService.debug(`Terminal process exit (id: ${this.id})${this._processManager ? ' state ' + this._processManager.processState : ''}`);\n", "\n", "\t\t// Only trigger wait on exit when the exit was *not* triggered by the\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (exitCode! < 0) {\n", "\t\t\texitCodeMessage = nls.localize('terminal.integrated.exitedWithInvalidPath', 'The terminal process terminated as it could not find the specified path : {0}', this._shellLaunchConfig.executable);\n", "\t\t}\n", "\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalInstance.ts", "type": "add", "edit_start_line_idx": 978 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /// <reference path='../../../../src/vs/vscode.d.ts'/> /// <reference path='../../../../src/vs/vscode.proposed.d.ts'/> /// <reference types='@types/node'/>
extensions/markdown-language-features/src/typings/ref.d.ts
0
https://github.com/microsoft/vscode/commit/d76b2030095513e31b61ecf7adb92964050f2a19
[ 0.00017327131354250014, 0.00017327131354250014, 0.00017327131354250014, 0.00017327131354250014, 0 ]
{ "id": 1, "code_window": [ "\t\t\trows,\n", "\t\t\texperimentalUseConpty: useConpty\n", "\t\t};\n", "\n", "\t\ttry {\n", "\t\t\tthis._ptyProcess = pty.spawn(shellLaunchConfig.executable!, shellLaunchConfig.args || [], options);\n", "\t\t\tthis._processStartupComplete = new Promise<void>(c => {\n", "\t\t\t\tthis.onProcessIdReady((pid) => {\n", "\t\t\t\t\tc();\n", "\t\t\t\t});\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\tconst filePath = path.basename(shellLaunchConfig.executable!);\n", "\t\t\tif (fs.existsSync(filePath)) {\n", "\t\t\t\tthis._ptyProcess = pty.spawn(shellLaunchConfig.executable!, shellLaunchConfig.args || [], options);\n", "\t\t\t\tthis._processStartupComplete = new Promise<void>(c => {\n", "\t\t\t\t\tthis.onProcessIdReady((pid) => {\n", "\t\t\t\t\t\tc();\n", "\t\t\t\t\t});\n" ], "file_path": "src/vs/workbench/contrib/terminal/node/terminalProcess.ts", "type": "replace", "edit_start_line_idx": 72 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as os from 'os'; import * as path from 'vs/base/common/path'; import * as platform from 'vs/base/common/platform'; import * as pty from 'node-pty'; import * as fs from 'fs'; import { Event, Emitter } from 'vs/base/common/event'; import { getWindowsBuildNumber } from 'vs/workbench/contrib/terminal/node/terminal'; import { IDisposable } from 'vs/base/common/lifecycle'; import { IShellLaunchConfig, ITerminalChildProcess } from 'vs/workbench/contrib/terminal/common/terminal'; import { exec } from 'child_process'; export class TerminalProcess implements ITerminalChildProcess, IDisposable { private _exitCode: number; private _closeTimeout: any; private _ptyProcess: pty.IPty; private _currentTitle: string = ''; private _processStartupComplete: Promise<void>; private _isDisposed: boolean = false; private _titleInterval: NodeJS.Timer | null = null; private _initialCwd: string; private readonly _onProcessData = new Emitter<string>(); public get onProcessData(): Event<string> { return this._onProcessData.event; } private readonly _onProcessExit = new Emitter<number>(); public get onProcessExit(): Event<number> { return this._onProcessExit.event; } private readonly _onProcessIdReady = new Emitter<number>(); public get onProcessIdReady(): Event<number> { return this._onProcessIdReady.event; } private readonly _onProcessTitleChanged = new Emitter<string>(); public get onProcessTitleChanged(): Event<string> { return this._onProcessTitleChanged.event; } constructor( shellLaunchConfig: IShellLaunchConfig, cwd: string, cols: number, rows: number, env: platform.IProcessEnvironment, windowsEnableConpty: boolean ) { let shellName: string; if (os.platform() === 'win32') { shellName = path.basename(shellLaunchConfig.executable || ''); } else { // Using 'xterm-256color' here helps ensure that the majority of Linux distributions will use a // color prompt as defined in the default ~/.bashrc file. shellName = 'xterm-256color'; } this._initialCwd = cwd; // Only use ConPTY when the client is non WoW64 (see #72190) and the Windows build number is at least 18309 (for // stability/performance reasons) const is32ProcessOn64Windows = process.env.hasOwnProperty('PROCESSOR_ARCHITEW6432'); const useConpty = windowsEnableConpty && process.platform === 'win32' && !is32ProcessOn64Windows && getWindowsBuildNumber() >= 18309; const options: pty.IPtyForkOptions = { name: shellName, cwd, env, cols, rows, experimentalUseConpty: useConpty }; try { this._ptyProcess = pty.spawn(shellLaunchConfig.executable!, shellLaunchConfig.args || [], options); this._processStartupComplete = new Promise<void>(c => { this.onProcessIdReady((pid) => { c(); }); }); } catch (error) { // The only time this is expected to happen is when the file specified to launch with does not exist. this._exitCode = 2; this._queueProcessExit(); this._processStartupComplete = Promise.resolve(undefined); return; } this._ptyProcess.on('data', (data) => { this._onProcessData.fire(data); if (this._closeTimeout) { clearTimeout(this._closeTimeout); this._queueProcessExit(); } }); this._ptyProcess.on('exit', (code) => { this._exitCode = code; this._queueProcessExit(); }); // TODO: We should no longer need to delay this since pty.spawn is sync setTimeout(() => { this._sendProcessId(); }, 500); this._setupTitlePolling(); } public dispose(): void { this._isDisposed = true; if (this._titleInterval) { clearInterval(this._titleInterval); } this._titleInterval = null; this._onProcessData.dispose(); this._onProcessExit.dispose(); this._onProcessIdReady.dispose(); this._onProcessTitleChanged.dispose(); } private _setupTitlePolling() { // Send initial timeout async to give event listeners a chance to init setTimeout(() => { this._sendProcessTitle(); }, 0); // Setup polling this._titleInterval = setInterval(() => { if (this._currentTitle !== this._ptyProcess.process) { this._sendProcessTitle(); } }, 200); } // Allow any trailing data events to be sent before the exit event is sent. // See https://github.com/Tyriar/node-pty/issues/72 private _queueProcessExit() { if (this._closeTimeout) { clearTimeout(this._closeTimeout); } this._closeTimeout = setTimeout(() => this._kill(), 250); } private _kill(): void { // Wait to kill to process until the start up code has run. This prevents us from firing a process exit before a // process start. this._processStartupComplete.then(() => { if (this._isDisposed) { return; } // Attempt to kill the pty, it may have already been killed at this // point but we want to make sure try { this._ptyProcess.kill(); } catch (ex) { // Swallow, the pty has already been killed } this._onProcessExit.fire(this._exitCode); this.dispose(); }); } private _sendProcessId() { this._onProcessIdReady.fire(this._ptyProcess.pid); } private _sendProcessTitle(): void { if (this._isDisposed) { return; } this._currentTitle = this._ptyProcess.process; this._onProcessTitleChanged.fire(this._currentTitle); } public shutdown(immediate: boolean): void { if (immediate) { this._kill(); } else { this._queueProcessExit(); } } public input(data: string): void { if (this._isDisposed) { return; } this._ptyProcess.write(data); } public resize(cols: number, rows: number): void { if (this._isDisposed) { return; } // Ensure that cols and rows are always >= 1, this prevents a native // exception in winpty. this._ptyProcess.resize(Math.max(cols, 1), Math.max(rows, 1)); } public getInitialCwd(): Promise<string> { return Promise.resolve(this._initialCwd); } public getCwd(): Promise<string> { if (platform.isMacintosh) { return new Promise<string>(resolve => { exec('lsof -p ' + this._ptyProcess.pid + ' | grep cwd', (error, stdout, stderr) => { if (stdout !== '') { resolve(stdout.substring(stdout.indexOf('/'), stdout.length - 1)); } }); }); } if (platform.isLinux) { return new Promise<string>(resolve => { fs.readlink('/proc/' + this._ptyProcess.pid + '/cwd', (err, linkedstr) => { if (err) { resolve(this._initialCwd); } resolve(linkedstr); }); }); } return new Promise<string>(resolve => { resolve(this._initialCwd); }); } public getLatency(): Promise<number> { return Promise.resolve(0); } }
src/vs/workbench/contrib/terminal/node/terminalProcess.ts
1
https://github.com/microsoft/vscode/commit/d76b2030095513e31b61ecf7adb92964050f2a19
[ 0.9983774423599243, 0.4110824763774872, 0.00016629578021820635, 0.0508633628487587, 0.45375245809555054 ]
{ "id": 1, "code_window": [ "\t\t\trows,\n", "\t\t\texperimentalUseConpty: useConpty\n", "\t\t};\n", "\n", "\t\ttry {\n", "\t\t\tthis._ptyProcess = pty.spawn(shellLaunchConfig.executable!, shellLaunchConfig.args || [], options);\n", "\t\t\tthis._processStartupComplete = new Promise<void>(c => {\n", "\t\t\t\tthis.onProcessIdReady((pid) => {\n", "\t\t\t\t\tc();\n", "\t\t\t\t});\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\tconst filePath = path.basename(shellLaunchConfig.executable!);\n", "\t\t\tif (fs.existsSync(filePath)) {\n", "\t\t\t\tthis._ptyProcess = pty.spawn(shellLaunchConfig.executable!, shellLaunchConfig.args || [], options);\n", "\t\t\t\tthis._processStartupComplete = new Promise<void>(c => {\n", "\t\t\t\t\tthis.onProcessIdReady((pid) => {\n", "\t\t\t\t\t\tc();\n", "\t\t\t\t\t});\n" ], "file_path": "src/vs/workbench/contrib/terminal/node/terminalProcess.ts", "type": "replace", "edit_start_line_idx": 72 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /** * A position in the editor. This interface is suitable for serialization. */ export interface IPosition { /** * line number (starts at 1) */ readonly lineNumber: number; /** * column (the first character in a line is between column 1 and column 2) */ readonly column: number; } /** * A position in the editor. */ export class Position { /** * line number (starts at 1) */ public readonly lineNumber: number; /** * column (the first character in a line is between column 1 and column 2) */ public readonly column: number; constructor(lineNumber: number, column: number) { this.lineNumber = lineNumber; this.column = column; } /** * Create a new postion from this position. * * @param newLineNumber new line number * @param newColumn new column */ with(newLineNumber: number = this.lineNumber, newColumn: number = this.column): Position { if (newLineNumber === this.lineNumber && newColumn === this.column) { return this; } else { return new Position(newLineNumber, newColumn); } } /** * Derive a new position from this position. * * @param deltaLineNumber line number delta * @param deltaColumn column delta */ delta(deltaLineNumber: number = 0, deltaColumn: number = 0): Position { return this.with(this.lineNumber + deltaLineNumber, this.column + deltaColumn); } /** * Test if this position equals other position */ public equals(other: IPosition): boolean { return Position.equals(this, other); } /** * Test if position `a` equals position `b` */ public static equals(a: IPosition | null, b: IPosition | null): boolean { if (!a && !b) { return true; } return ( !!a && !!b && a.lineNumber === b.lineNumber && a.column === b.column ); } /** * Test if this position is before other position. * If the two positions are equal, the result will be false. */ public isBefore(other: IPosition): boolean { return Position.isBefore(this, other); } /** * Test if position `a` is before position `b`. * If the two positions are equal, the result will be false. */ public static isBefore(a: IPosition, b: IPosition): boolean { if (a.lineNumber < b.lineNumber) { return true; } if (b.lineNumber < a.lineNumber) { return false; } return a.column < b.column; } /** * Test if this position is before other position. * If the two positions are equal, the result will be true. */ public isBeforeOrEqual(other: IPosition): boolean { return Position.isBeforeOrEqual(this, other); } /** * Test if position `a` is before position `b`. * If the two positions are equal, the result will be true. */ public static isBeforeOrEqual(a: IPosition, b: IPosition): boolean { if (a.lineNumber < b.lineNumber) { return true; } if (b.lineNumber < a.lineNumber) { return false; } return a.column <= b.column; } /** * A function that compares positions, useful for sorting */ public static compare(a: IPosition, b: IPosition): number { let aLineNumber = a.lineNumber | 0; let bLineNumber = b.lineNumber | 0; if (aLineNumber === bLineNumber) { let aColumn = a.column | 0; let bColumn = b.column | 0; return aColumn - bColumn; } return aLineNumber - bLineNumber; } /** * Clone this position. */ public clone(): Position { return new Position(this.lineNumber, this.column); } /** * Convert to a human-readable representation. */ public toString(): string { return '(' + this.lineNumber + ',' + this.column + ')'; } // --- /** * Create a `Position` from an `IPosition`. */ public static lift(pos: IPosition): Position { return new Position(pos.lineNumber, pos.column); } /** * Test if `obj` is an `IPosition`. */ public static isIPosition(obj: any): obj is IPosition { return ( obj && (typeof obj.lineNumber === 'number') && (typeof obj.column === 'number') ); } }
src/vs/editor/common/core/position.ts
0
https://github.com/microsoft/vscode/commit/d76b2030095513e31b61ecf7adb92964050f2a19
[ 0.00017816084437072277, 0.00017532367201056331, 0.00017127567843999714, 0.0001757904828991741, 0.0000019539540971891256 ]
{ "id": 1, "code_window": [ "\t\t\trows,\n", "\t\t\texperimentalUseConpty: useConpty\n", "\t\t};\n", "\n", "\t\ttry {\n", "\t\t\tthis._ptyProcess = pty.spawn(shellLaunchConfig.executable!, shellLaunchConfig.args || [], options);\n", "\t\t\tthis._processStartupComplete = new Promise<void>(c => {\n", "\t\t\t\tthis.onProcessIdReady((pid) => {\n", "\t\t\t\t\tc();\n", "\t\t\t\t});\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\tconst filePath = path.basename(shellLaunchConfig.executable!);\n", "\t\t\tif (fs.existsSync(filePath)) {\n", "\t\t\t\tthis._ptyProcess = pty.spawn(shellLaunchConfig.executable!, shellLaunchConfig.args || [], options);\n", "\t\t\t\tthis._processStartupComplete = new Promise<void>(c => {\n", "\t\t\t\t\tthis.onProcessIdReady((pid) => {\n", "\t\t\t\t\t\tc();\n", "\t\t\t\t\t});\n" ], "file_path": "src/vs/workbench/contrib/terminal/node/terminalProcess.ts", "type": "replace", "edit_start_line_idx": 72 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as strings from 'vs/base/common/strings'; import { ReplaceCommand } from 'vs/editor/common/commands/replaceCommand'; import { CursorColumns, CursorConfiguration, EditOperationResult, EditOperationType, ICursorSimpleModel, isQuote } from 'vs/editor/common/controller/cursorCommon'; import { MoveOperations } from 'vs/editor/common/controller/cursorMoveOperations'; import { Range } from 'vs/editor/common/core/range'; import { Selection } from 'vs/editor/common/core/selection'; import { ICommand } from 'vs/editor/common/editorCommon'; export class DeleteOperations { public static deleteRight(prevEditOperationType: EditOperationType, config: CursorConfiguration, model: ICursorSimpleModel, selections: Selection[]): [boolean, Array<ICommand | null>] { let commands: Array<ICommand | null> = []; let shouldPushStackElementBefore = (prevEditOperationType !== EditOperationType.DeletingRight); for (let i = 0, len = selections.length; i < len; i++) { const selection = selections[i]; let deleteSelection: Range = selection; if (deleteSelection.isEmpty()) { let position = selection.getPosition(); let rightOfPosition = MoveOperations.right(config, model, position.lineNumber, position.column); deleteSelection = new Range( rightOfPosition.lineNumber, rightOfPosition.column, position.lineNumber, position.column ); } if (deleteSelection.isEmpty()) { // Probably at end of file => ignore commands[i] = null; continue; } if (deleteSelection.startLineNumber !== deleteSelection.endLineNumber) { shouldPushStackElementBefore = true; } commands[i] = new ReplaceCommand(deleteSelection, ''); } return [shouldPushStackElementBefore, commands]; } private static _isAutoClosingPairDelete(config: CursorConfiguration, model: ICursorSimpleModel, selections: Selection[]): boolean { if (config.autoClosingBrackets === 'never' && config.autoClosingQuotes === 'never') { return false; } for (let i = 0, len = selections.length; i < len; i++) { const selection = selections[i]; const position = selection.getPosition(); if (!selection.isEmpty()) { return false; } const lineText = model.getLineContent(position.lineNumber); const character = lineText[position.column - 2]; if (!config.autoClosingPairsOpen.hasOwnProperty(character)) { return false; } if (isQuote(character)) { if (config.autoClosingQuotes === 'never') { return false; } } else { if (config.autoClosingBrackets === 'never') { return false; } } const afterCharacter = lineText[position.column - 1]; const closeCharacter = config.autoClosingPairsOpen[character]; if (afterCharacter !== closeCharacter) { return false; } } return true; } private static _runAutoClosingPairDelete(config: CursorConfiguration, model: ICursorSimpleModel, selections: Selection[]): [boolean, ICommand[]] { let commands: ICommand[] = []; for (let i = 0, len = selections.length; i < len; i++) { const position = selections[i].getPosition(); const deleteSelection = new Range( position.lineNumber, position.column - 1, position.lineNumber, position.column + 1 ); commands[i] = new ReplaceCommand(deleteSelection, ''); } return [true, commands]; } public static deleteLeft(prevEditOperationType: EditOperationType, config: CursorConfiguration, model: ICursorSimpleModel, selections: Selection[]): [boolean, Array<ICommand | null>] { if (this._isAutoClosingPairDelete(config, model, selections)) { return this._runAutoClosingPairDelete(config, model, selections); } let commands: Array<ICommand | null> = []; let shouldPushStackElementBefore = (prevEditOperationType !== EditOperationType.DeletingLeft); for (let i = 0, len = selections.length; i < len; i++) { const selection = selections[i]; let deleteSelection: Range = selection; if (deleteSelection.isEmpty()) { let position = selection.getPosition(); if (config.useTabStops && position.column > 1) { let lineContent = model.getLineContent(position.lineNumber); let firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineContent); let lastIndentationColumn = ( firstNonWhitespaceIndex === -1 ? /* entire string is whitespace */lineContent.length + 1 : firstNonWhitespaceIndex + 1 ); if (position.column <= lastIndentationColumn) { let fromVisibleColumn = CursorColumns.visibleColumnFromColumn2(config, model, position); let toVisibleColumn = CursorColumns.prevIndentTabStop(fromVisibleColumn, config.indentSize); let toColumn = CursorColumns.columnFromVisibleColumn2(config, model, position.lineNumber, toVisibleColumn); deleteSelection = new Range(position.lineNumber, toColumn, position.lineNumber, position.column); } else { deleteSelection = new Range(position.lineNumber, position.column - 1, position.lineNumber, position.column); } } else { let leftOfPosition = MoveOperations.left(config, model, position.lineNumber, position.column); deleteSelection = new Range( leftOfPosition.lineNumber, leftOfPosition.column, position.lineNumber, position.column ); } } if (deleteSelection.isEmpty()) { // Probably at beginning of file => ignore commands[i] = null; continue; } if (deleteSelection.startLineNumber !== deleteSelection.endLineNumber) { shouldPushStackElementBefore = true; } commands[i] = new ReplaceCommand(deleteSelection, ''); } return [shouldPushStackElementBefore, commands]; } public static cut(config: CursorConfiguration, model: ICursorSimpleModel, selections: Selection[]): EditOperationResult { let commands: Array<ICommand | null> = []; for (let i = 0, len = selections.length; i < len; i++) { const selection = selections[i]; if (selection.isEmpty()) { if (config.emptySelectionClipboard) { // This is a full line cut let position = selection.getPosition(); let startLineNumber: number, startColumn: number, endLineNumber: number, endColumn: number; if (position.lineNumber < model.getLineCount()) { // Cutting a line in the middle of the model startLineNumber = position.lineNumber; startColumn = 1; endLineNumber = position.lineNumber + 1; endColumn = 1; } else if (position.lineNumber > 1) { // Cutting the last line & there are more than 1 lines in the model startLineNumber = position.lineNumber - 1; startColumn = model.getLineMaxColumn(position.lineNumber - 1); endLineNumber = position.lineNumber; endColumn = model.getLineMaxColumn(position.lineNumber); } else { // Cutting the single line that the model contains startLineNumber = position.lineNumber; startColumn = 1; endLineNumber = position.lineNumber; endColumn = model.getLineMaxColumn(position.lineNumber); } let deleteSelection = new Range( startLineNumber, startColumn, endLineNumber, endColumn ); if (!deleteSelection.isEmpty()) { commands[i] = new ReplaceCommand(deleteSelection, ''); } else { commands[i] = null; } } else { // Cannot cut empty selection commands[i] = null; } } else { commands[i] = new ReplaceCommand(selection, ''); } } return new EditOperationResult(EditOperationType.Other, commands, { shouldPushStackElementBefore: true, shouldPushStackElementAfter: true }); } }
src/vs/editor/common/controller/cursorDeleteOperations.ts
0
https://github.com/microsoft/vscode/commit/d76b2030095513e31b61ecf7adb92964050f2a19
[ 0.0001777115830918774, 0.00017538641986902803, 0.00017077538359444588, 0.00017590199422556907, 0.0000019128353869746206 ]
{ "id": 1, "code_window": [ "\t\t\trows,\n", "\t\t\texperimentalUseConpty: useConpty\n", "\t\t};\n", "\n", "\t\ttry {\n", "\t\t\tthis._ptyProcess = pty.spawn(shellLaunchConfig.executable!, shellLaunchConfig.args || [], options);\n", "\t\t\tthis._processStartupComplete = new Promise<void>(c => {\n", "\t\t\t\tthis.onProcessIdReady((pid) => {\n", "\t\t\t\t\tc();\n", "\t\t\t\t});\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\t\tconst filePath = path.basename(shellLaunchConfig.executable!);\n", "\t\t\tif (fs.existsSync(filePath)) {\n", "\t\t\t\tthis._ptyProcess = pty.spawn(shellLaunchConfig.executable!, shellLaunchConfig.args || [], options);\n", "\t\t\t\tthis._processStartupComplete = new Promise<void>(c => {\n", "\t\t\t\t\tthis.onProcessIdReady((pid) => {\n", "\t\t\t\t\t\tc();\n", "\t\t\t\t\t});\n" ], "file_path": "src/vs/workbench/contrib/terminal/node/terminalProcess.ts", "type": "replace", "edit_start_line_idx": 72 }
{ "displayName": "Powershell Language Basics", "description": "Provides snippets, syntax highlighting, bracket matching and folding in Powershell files." }
extensions/powershell/package.nls.json
0
https://github.com/microsoft/vscode/commit/d76b2030095513e31b61ecf7adb92964050f2a19
[ 0.00016931515710894018, 0.00016931515710894018, 0.00016931515710894018, 0.00016931515710894018, 0 ]
{ "id": 2, "code_window": [ "\t\t\t\t});\n", "\t\t\t});\n", "\t\t} catch (error) {\n", "\t\t\t// The only time this is expected to happen is when the file specified to launch with does not exist.\n", "\t\t\tthis._exitCode = 2;\n", "\t\t\tthis._queueProcessExit();\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t}\n", "\t\t\telse {\n", "\t\t\t\t// file path does not exist , handle it with negative exit code\n", "\t\t\t\tthis._exitCode = -1;\n", "\t\t\t\tthis._queueProcessExit();\n", "\t\t\t\tthis._processStartupComplete = Promise.resolve(undefined);\n", "\t\t\t\treturn;\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/contrib/terminal/node/terminalProcess.ts", "type": "replace", "edit_start_line_idx": 77 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as os from 'os'; import * as path from 'vs/base/common/path'; import * as platform from 'vs/base/common/platform'; import * as pty from 'node-pty'; import * as fs from 'fs'; import { Event, Emitter } from 'vs/base/common/event'; import { getWindowsBuildNumber } from 'vs/workbench/contrib/terminal/node/terminal'; import { IDisposable } from 'vs/base/common/lifecycle'; import { IShellLaunchConfig, ITerminalChildProcess } from 'vs/workbench/contrib/terminal/common/terminal'; import { exec } from 'child_process'; export class TerminalProcess implements ITerminalChildProcess, IDisposable { private _exitCode: number; private _closeTimeout: any; private _ptyProcess: pty.IPty; private _currentTitle: string = ''; private _processStartupComplete: Promise<void>; private _isDisposed: boolean = false; private _titleInterval: NodeJS.Timer | null = null; private _initialCwd: string; private readonly _onProcessData = new Emitter<string>(); public get onProcessData(): Event<string> { return this._onProcessData.event; } private readonly _onProcessExit = new Emitter<number>(); public get onProcessExit(): Event<number> { return this._onProcessExit.event; } private readonly _onProcessIdReady = new Emitter<number>(); public get onProcessIdReady(): Event<number> { return this._onProcessIdReady.event; } private readonly _onProcessTitleChanged = new Emitter<string>(); public get onProcessTitleChanged(): Event<string> { return this._onProcessTitleChanged.event; } constructor( shellLaunchConfig: IShellLaunchConfig, cwd: string, cols: number, rows: number, env: platform.IProcessEnvironment, windowsEnableConpty: boolean ) { let shellName: string; if (os.platform() === 'win32') { shellName = path.basename(shellLaunchConfig.executable || ''); } else { // Using 'xterm-256color' here helps ensure that the majority of Linux distributions will use a // color prompt as defined in the default ~/.bashrc file. shellName = 'xterm-256color'; } this._initialCwd = cwd; // Only use ConPTY when the client is non WoW64 (see #72190) and the Windows build number is at least 18309 (for // stability/performance reasons) const is32ProcessOn64Windows = process.env.hasOwnProperty('PROCESSOR_ARCHITEW6432'); const useConpty = windowsEnableConpty && process.platform === 'win32' && !is32ProcessOn64Windows && getWindowsBuildNumber() >= 18309; const options: pty.IPtyForkOptions = { name: shellName, cwd, env, cols, rows, experimentalUseConpty: useConpty }; try { this._ptyProcess = pty.spawn(shellLaunchConfig.executable!, shellLaunchConfig.args || [], options); this._processStartupComplete = new Promise<void>(c => { this.onProcessIdReady((pid) => { c(); }); }); } catch (error) { // The only time this is expected to happen is when the file specified to launch with does not exist. this._exitCode = 2; this._queueProcessExit(); this._processStartupComplete = Promise.resolve(undefined); return; } this._ptyProcess.on('data', (data) => { this._onProcessData.fire(data); if (this._closeTimeout) { clearTimeout(this._closeTimeout); this._queueProcessExit(); } }); this._ptyProcess.on('exit', (code) => { this._exitCode = code; this._queueProcessExit(); }); // TODO: We should no longer need to delay this since pty.spawn is sync setTimeout(() => { this._sendProcessId(); }, 500); this._setupTitlePolling(); } public dispose(): void { this._isDisposed = true; if (this._titleInterval) { clearInterval(this._titleInterval); } this._titleInterval = null; this._onProcessData.dispose(); this._onProcessExit.dispose(); this._onProcessIdReady.dispose(); this._onProcessTitleChanged.dispose(); } private _setupTitlePolling() { // Send initial timeout async to give event listeners a chance to init setTimeout(() => { this._sendProcessTitle(); }, 0); // Setup polling this._titleInterval = setInterval(() => { if (this._currentTitle !== this._ptyProcess.process) { this._sendProcessTitle(); } }, 200); } // Allow any trailing data events to be sent before the exit event is sent. // See https://github.com/Tyriar/node-pty/issues/72 private _queueProcessExit() { if (this._closeTimeout) { clearTimeout(this._closeTimeout); } this._closeTimeout = setTimeout(() => this._kill(), 250); } private _kill(): void { // Wait to kill to process until the start up code has run. This prevents us from firing a process exit before a // process start. this._processStartupComplete.then(() => { if (this._isDisposed) { return; } // Attempt to kill the pty, it may have already been killed at this // point but we want to make sure try { this._ptyProcess.kill(); } catch (ex) { // Swallow, the pty has already been killed } this._onProcessExit.fire(this._exitCode); this.dispose(); }); } private _sendProcessId() { this._onProcessIdReady.fire(this._ptyProcess.pid); } private _sendProcessTitle(): void { if (this._isDisposed) { return; } this._currentTitle = this._ptyProcess.process; this._onProcessTitleChanged.fire(this._currentTitle); } public shutdown(immediate: boolean): void { if (immediate) { this._kill(); } else { this._queueProcessExit(); } } public input(data: string): void { if (this._isDisposed) { return; } this._ptyProcess.write(data); } public resize(cols: number, rows: number): void { if (this._isDisposed) { return; } // Ensure that cols and rows are always >= 1, this prevents a native // exception in winpty. this._ptyProcess.resize(Math.max(cols, 1), Math.max(rows, 1)); } public getInitialCwd(): Promise<string> { return Promise.resolve(this._initialCwd); } public getCwd(): Promise<string> { if (platform.isMacintosh) { return new Promise<string>(resolve => { exec('lsof -p ' + this._ptyProcess.pid + ' | grep cwd', (error, stdout, stderr) => { if (stdout !== '') { resolve(stdout.substring(stdout.indexOf('/'), stdout.length - 1)); } }); }); } if (platform.isLinux) { return new Promise<string>(resolve => { fs.readlink('/proc/' + this._ptyProcess.pid + '/cwd', (err, linkedstr) => { if (err) { resolve(this._initialCwd); } resolve(linkedstr); }); }); } return new Promise<string>(resolve => { resolve(this._initialCwd); }); } public getLatency(): Promise<number> { return Promise.resolve(0); } }
src/vs/workbench/contrib/terminal/node/terminalProcess.ts
1
https://github.com/microsoft/vscode/commit/d76b2030095513e31b61ecf7adb92964050f2a19
[ 0.9318397641181946, 0.0786043182015419, 0.00016598400543443859, 0.00018409219046588987, 0.2458294928073883 ]
{ "id": 2, "code_window": [ "\t\t\t\t});\n", "\t\t\t});\n", "\t\t} catch (error) {\n", "\t\t\t// The only time this is expected to happen is when the file specified to launch with does not exist.\n", "\t\t\tthis._exitCode = 2;\n", "\t\t\tthis._queueProcessExit();\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t}\n", "\t\t\telse {\n", "\t\t\t\t// file path does not exist , handle it with negative exit code\n", "\t\t\t\tthis._exitCode = -1;\n", "\t\t\t\tthis._queueProcessExit();\n", "\t\t\t\tthis._processStartupComplete = Promise.resolve(undefined);\n", "\t\t\t\treturn;\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/contrib/terminal/node/terminalProcess.ts", "type": "replace", "edit_start_line_idx": 77 }
"use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", { value: true }); const Lint = require("tslint"); const fs = require("fs"); class Rule extends Lint.Rules.AbstractRule { apply(sourceFile) { return this.applyWithWalker(new TranslationRemindRuleWalker(sourceFile, this.getOptions())); } } exports.Rule = Rule; class TranslationRemindRuleWalker extends Lint.RuleWalker { constructor(file, opts) { super(file, opts); } visitImportDeclaration(node) { const declaration = node.moduleSpecifier.getText(); if (declaration !== `'${TranslationRemindRuleWalker.NLS_MODULE}'`) { return; } this.visitImportLikeDeclaration(node); } visitImportEqualsDeclaration(node) { const reference = node.moduleReference.getText(); if (reference !== `require('${TranslationRemindRuleWalker.NLS_MODULE}')`) { return; } this.visitImportLikeDeclaration(node); } visitImportLikeDeclaration(node) { const currentFile = node.getSourceFile().fileName; const matchService = currentFile.match(/vs\/workbench\/services\/\w+/); const matchPart = currentFile.match(/vs\/workbench\/contrib\/\w+/); if (!matchService && !matchPart) { return; } const resource = matchService ? matchService[0] : matchPart[0]; let resourceDefined = false; let json; try { json = fs.readFileSync('./build/lib/i18n.resources.json', 'utf8'); } catch (e) { console.error('[translation-remind rule]: File with resources to pull from Transifex was not found. Aborting translation resource check for newly defined workbench part/service.'); return; } const workbenchResources = JSON.parse(json).workbench; workbenchResources.forEach((existingResource) => { if (existingResource.name === resource) { resourceDefined = true; return; } }); if (!resourceDefined) { this.addFailureAtNode(node, `Please add '${resource}' to ./build/lib/i18n.resources.json file to use translations here.`); } } } TranslationRemindRuleWalker.NLS_MODULE = 'vs/nls';
build/lib/tslint/translationRemindRule.js
0
https://github.com/microsoft/vscode/commit/d76b2030095513e31b61ecf7adb92964050f2a19
[ 0.00017515654326416552, 0.00017120760458055884, 0.0001674021186772734, 0.00017083871352951974, 0.0000027161122488905676 ]
{ "id": 2, "code_window": [ "\t\t\t\t});\n", "\t\t\t});\n", "\t\t} catch (error) {\n", "\t\t\t// The only time this is expected to happen is when the file specified to launch with does not exist.\n", "\t\t\tthis._exitCode = 2;\n", "\t\t\tthis._queueProcessExit();\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t}\n", "\t\t\telse {\n", "\t\t\t\t// file path does not exist , handle it with negative exit code\n", "\t\t\t\tthis._exitCode = -1;\n", "\t\t\t\tthis._queueProcessExit();\n", "\t\t\t\tthis._processStartupComplete = Promise.resolve(undefined);\n", "\t\t\t\treturn;\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/contrib/terminal/node/terminalProcess.ts", "type": "replace", "edit_start_line_idx": 77 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); const path = require("path"); const fs = require("fs"); /** * Returns the sha1 commit version of a repository or undefined in case of failure. */ function getVersion(repo) { const git = path.join(repo, '.git'); const headPath = path.join(git, 'HEAD'); let head; try { head = fs.readFileSync(headPath, 'utf8').trim(); } catch (e) { return undefined; } if (/^[0-9a-f]{40}$/i.test(head)) { return head; } const refMatch = /^ref: (.*)$/.exec(head); if (!refMatch) { return undefined; } const ref = refMatch[1]; const refPath = path.join(git, ref); try { return fs.readFileSync(refPath, 'utf8').trim(); } catch (e) { // noop } const packedRefsPath = path.join(git, 'packed-refs'); let refsRaw; try { refsRaw = fs.readFileSync(packedRefsPath, 'utf8').trim(); } catch (e) { return undefined; } const refsRegex = /^([0-9a-f]{40})\s+(.+)$/gm; let refsMatch; let refs = {}; while (refsMatch = refsRegex.exec(refsRaw)) { refs[refsMatch[2]] = refsMatch[1]; } return refs[ref]; } exports.getVersion = getVersion;
build/lib/git.js
0
https://github.com/microsoft/vscode/commit/d76b2030095513e31b61ecf7adb92964050f2a19
[ 0.00017577676044311374, 0.00017261448374483734, 0.0001693080412223935, 0.0001720770524116233, 0.000002185672428822727 ]
{ "id": 2, "code_window": [ "\t\t\t\t});\n", "\t\t\t});\n", "\t\t} catch (error) {\n", "\t\t\t// The only time this is expected to happen is when the file specified to launch with does not exist.\n", "\t\t\tthis._exitCode = 2;\n", "\t\t\tthis._queueProcessExit();\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t}\n", "\t\t\telse {\n", "\t\t\t\t// file path does not exist , handle it with negative exit code\n", "\t\t\t\tthis._exitCode = -1;\n", "\t\t\t\tthis._queueProcessExit();\n", "\t\t\t\tthis._processStartupComplete = Promise.resolve(undefined);\n", "\t\t\t\treturn;\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/contrib/terminal/node/terminalProcess.ts", "type": "replace", "edit_start_line_idx": 77 }
/*--------------------------------------------------------------------------------------------- * 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 { workspace, WorkspaceFolder, extensions } from 'vscode'; interface ExperimentalConfig { experimental?: { customData?: string[]; }; } export function getCustomDataPathsInAllWorkspaces(workspaceFolders: WorkspaceFolder[] | undefined): string[] { const dataPaths: string[] = []; if (!workspaceFolders) { return dataPaths; } workspaceFolders.forEach(wf => { const allCssConfig = workspace.getConfiguration(undefined, wf.uri); const wfCSSConfig = allCssConfig.inspect<ExperimentalConfig>('css'); if ( wfCSSConfig && wfCSSConfig.workspaceFolderValue && wfCSSConfig.workspaceFolderValue.experimental && wfCSSConfig.workspaceFolderValue.experimental.customData ) { const customData = wfCSSConfig.workspaceFolderValue.experimental.customData; if (Array.isArray(customData)) { customData.forEach(t => { if (typeof t === 'string') { dataPaths.push(path.resolve(wf.uri.fsPath, t)); } }); } } }); return dataPaths; } export function getCustomDataPathsFromAllExtensions(): string[] { const dataPaths: string[] = []; for (const extension of extensions.all) { const contributes = extension.packageJSON && extension.packageJSON.contributes; if (contributes && contributes.css && contributes.css.experimental.customData && Array.isArray(contributes.css.experimental.customData)) { const relativePaths: string[] = contributes.css.experimental.customData; relativePaths.forEach(rp => { dataPaths.push(path.resolve(extension.extensionPath, rp)); }); } } return dataPaths; }
extensions/css-language-features/client/src/customData.ts
0
https://github.com/microsoft/vscode/commit/d76b2030095513e31b61ecf7adb92964050f2a19
[ 0.00021637461031787097, 0.00017862884851638228, 0.00016660685651004314, 0.00017472216859459877, 0.000015832503777346574 ]
{ "id": 0, "code_window": [ " '/guides/guide-react-native/',\n", " '/guides/guide-vue/',\n", " '/guides/guide-angular/',\n", " '/guides/guide-mithril/',\n", " '/guides/guide-ember/',\n", " '/guides/guide-riot/',\n", " '/guides/guide-svelte/',\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " '/guides/guide-marko/',\n" ], "file_path": "docs/gatsby-config.js", "type": "add", "edit_start_line_idx": 24 }
// eslint-disable import/prefer-default-export const gitHubOrg = `https://github.com/storybooks`; const homepageUrl = `https://storybook.js.org`; const docsUrl = `${homepageUrl}/docs`; const npmApiBase = `https://api.npmjs.org/downloads/point/last-month`; export const metadata = { title: 'Storybook', description: `Storybook is an open source tool for developing UI components in isolation for React, Vue, and Angular`, ogImage: '/images/social/open-graph.png', googleSiteVerification: '', latestVersion: 'v5.1', }; export const url = { gitHub: { repo: `${gitHubOrg}/storybook`, frontpage: `${gitHubOrg}/frontpage`, issues: `${gitHubOrg}/storybook/issues`, releases: `${gitHubOrg}/storybook/releases`, contributors: `${gitHubOrg}/storybook/graphs/contributors`, brand: `${gitHubOrg}/press`, }, npm: `https://www.npmjs.com/package/@storybook/react`, openCollective: `https://opencollective.com/storybook`, npmApi: { react: `${npmApiBase}/@storybook/react`, reactNative: `${npmApiBase}/@storybook/react-native`, vue: `${npmApiBase}/@storybook/vue`, angular: `${npmApiBase}/@storybook/angular`, ember: `${npmApiBase}/@storybook/ember`, html: `${npmApiBase}/@storybook/html`, svelte: `${npmApiBase}/@storybook/svelte`, mithril: `${npmApiBase}/@storybook/mithril`, riot: `${npmApiBase}/@storybook/riot`, polymer: `${npmApiBase}/@storybook/polymer`, preact: `${npmApiBase}/@storybook/preact`, }, // Navigation home: `${homepageUrl}`, docs: { home: `${docsUrl}/basics/introduction/`, addonInstruction: `${docsUrl}/addons/writing-addons/`, }, tutorials: `https://www.learnstorybook.com/`, addons: `${homepageUrl}/addons/`, community: `${homepageUrl}/community/`, useCases: `${homepageUrl}/use-cases/`, support: `${homepageUrl}/support/`, team: `${homepageUrl}/team/`, // Social blog: `https://medium.com/storybookjs`, twitter: `https://twitter.com/storybookjs`, chat: `https://discord.gg/UUt2PJb`, youtube: `https://www.youtube.com/channel/UCr7Quur3eIyA_oe8FNYexfg`, // Brand brand: `${gitHubOrg}/brand`, designSystem: `https://storybooks-official.netlify.com`, badge: `${gitHubOrg}/brand/tree/master/badge`, presentation: `${gitHubOrg}/brand/tree/master/presentation`, video: `${gitHubOrg}/brand/tree/master/video`, // Framework docs framework: { react: `${docsUrl}/guides/guide-react/`, reactNative: `${docsUrl}/guides/guide-react-native/`, vue: `${docsUrl}/guides/guide-vue/`, angular: `${docsUrl}/guides/guide-angular/`, ember: `${docsUrl}/guides/guide-ember/`, html: `${docsUrl}/guides/guide-html/`, svelte: `${docsUrl}/guides/guide-svelte/`, mithril: `${docsUrl}/guides/guide-mithril/`, riot: `${docsUrl}/guides/guide-riot/`, }, // Official addons officialAddons: { knobs: `${gitHubOrg}/storybook/tree/master/addons/knobs`, actions: `${gitHubOrg}/storybook/tree/master/addons/actions`, source: `${gitHubOrg}/storybook/tree/master/addons/storysource`, info: `${gitHubOrg}/storybook/tree/master/addons/info`, viewport: `${gitHubOrg}/storybook/tree/master/addons/viewport`, storyshots: `${gitHubOrg}/storybook/tree/master/addons/storyshots`, backgrounds: `${gitHubOrg}/storybook/tree/master/addons/backgrounds`, accessibility: `${gitHubOrg}/storybook/tree/master/addons/a11y`, console: `${gitHubOrg}/storybook-addon-console`, links: `${gitHubOrg}/storybook/tree/master/addons/links`, }, };
docs/src/new-components/basics/shared/site.js
1
https://github.com/storybookjs/storybook/commit/dfe7e3b578a56328a20b0bcd676cc177891d40d1
[ 0.07208671420812607, 0.007372324354946613, 0.0001678635599091649, 0.00017601012950763106, 0.02157147414982319 ]
{ "id": 0, "code_window": [ " '/guides/guide-react-native/',\n", " '/guides/guide-vue/',\n", " '/guides/guide-angular/',\n", " '/guides/guide-mithril/',\n", " '/guides/guide-ember/',\n", " '/guides/guide-riot/',\n", " '/guides/guide-svelte/',\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " '/guides/guide-marko/',\n" ], "file_path": "docs/gatsby-config.js", "type": "add", "edit_start_line_idx": 24 }
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
lib/cli/test/fixtures/react_scripts/src/index.js
0
https://github.com/storybookjs/storybook/commit/dfe7e3b578a56328a20b0bcd676cc177891d40d1
[ 0.00017429536092095077, 0.00017429536092095077, 0.00017429536092095077, 0.00017429536092095077, 0 ]
{ "id": 0, "code_window": [ " '/guides/guide-react-native/',\n", " '/guides/guide-vue/',\n", " '/guides/guide-angular/',\n", " '/guides/guide-mithril/',\n", " '/guides/guide-ember/',\n", " '/guides/guide-riot/',\n", " '/guides/guide-svelte/',\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " '/guides/guide-marko/',\n" ], "file_path": "docs/gatsby-config.js", "type": "add", "edit_start_line_idx": 24 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Storyshots Addons|GraphQL get Pickachu 1`] = ` <div> hello </div> `;
examples/official-storybook/stories/__snapshots__/addon-graphql.stories.storyshot
0
https://github.com/storybookjs/storybook/commit/dfe7e3b578a56328a20b0bcd676cc177891d40d1
[ 0.00017518743698019534, 0.00017518743698019534, 0.00017518743698019534, 0.00017518743698019534, 0 ]
{ "id": 0, "code_window": [ " '/guides/guide-react-native/',\n", " '/guides/guide-vue/',\n", " '/guides/guide-angular/',\n", " '/guides/guide-mithril/',\n", " '/guides/guide-ember/',\n", " '/guides/guide-riot/',\n", " '/guides/guide-svelte/',\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " '/guides/guide-marko/',\n" ], "file_path": "docs/gatsby-config.js", "type": "add", "edit_start_line_idx": 24 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`PropTable multiLineText should exclude excluded propTypes 1`] = ` <small> No propTypes defined! </small> `; exports[`PropTable multiLineText should have 2 br tags for 3 lines of text 1`] = ` Array [ <span> foo </span>, <span> <br /> bar </span>, <span> <br /> baz </span>, ] `; exports[`PropTable multiLineText should include all propTypes by default 1`] = ` <Table> <Thead> <Tr> <Th> property </Th> <Th> propType </Th> <Th> required </Th> <Th> default </Th> <Th> description </Th> </Tr> </Thead> <Tbody> <Tr key="foo" > <Td> foo </Td> <Td> <PrettyPropType depth={1} propType={ Object { "name": "string", } } /> </Td> <Td> - </Td> <Td> - </Td> <Td /> </Tr> </Tbody> </Table> `;
addons/info/src/components/__snapshots__/PropTable.test.js.snap
0
https://github.com/storybookjs/storybook/commit/dfe7e3b578a56328a20b0bcd676cc177891d40d1
[ 0.00017573987133800983, 0.00017451203893870115, 0.00017324835062026978, 0.0001745699846651405, 7.682542104703316e-7 ]
{ "id": 1, "code_window": [ " angular: `${npmApiBase}/@storybook/angular`,\n", " ember: `${npmApiBase}/@storybook/ember`,\n", " html: `${npmApiBase}/@storybook/html`,\n", " svelte: `${npmApiBase}/@storybook/svelte`,\n", " mithril: `${npmApiBase}/@storybook/mithril`,\n", " riot: `${npmApiBase}/@storybook/riot`,\n", " polymer: `${npmApiBase}/@storybook/polymer`,\n", " preact: `${npmApiBase}/@storybook/preact`,\n", " },\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " marko: `${npmApiBase}/@storybook/marko`,\n" ], "file_path": "docs/src/new-components/basics/shared/site.js", "type": "add", "edit_start_line_idx": 37 }
// eslint-disable import/prefer-default-export const gitHubOrg = `https://github.com/storybooks`; const homepageUrl = `https://storybook.js.org`; const docsUrl = `${homepageUrl}/docs`; const npmApiBase = `https://api.npmjs.org/downloads/point/last-month`; export const metadata = { title: 'Storybook', description: `Storybook is an open source tool for developing UI components in isolation for React, Vue, and Angular`, ogImage: '/images/social/open-graph.png', googleSiteVerification: '', latestVersion: 'v5.1', }; export const url = { gitHub: { repo: `${gitHubOrg}/storybook`, frontpage: `${gitHubOrg}/frontpage`, issues: `${gitHubOrg}/storybook/issues`, releases: `${gitHubOrg}/storybook/releases`, contributors: `${gitHubOrg}/storybook/graphs/contributors`, brand: `${gitHubOrg}/press`, }, npm: `https://www.npmjs.com/package/@storybook/react`, openCollective: `https://opencollective.com/storybook`, npmApi: { react: `${npmApiBase}/@storybook/react`, reactNative: `${npmApiBase}/@storybook/react-native`, vue: `${npmApiBase}/@storybook/vue`, angular: `${npmApiBase}/@storybook/angular`, ember: `${npmApiBase}/@storybook/ember`, html: `${npmApiBase}/@storybook/html`, svelte: `${npmApiBase}/@storybook/svelte`, mithril: `${npmApiBase}/@storybook/mithril`, riot: `${npmApiBase}/@storybook/riot`, polymer: `${npmApiBase}/@storybook/polymer`, preact: `${npmApiBase}/@storybook/preact`, }, // Navigation home: `${homepageUrl}`, docs: { home: `${docsUrl}/basics/introduction/`, addonInstruction: `${docsUrl}/addons/writing-addons/`, }, tutorials: `https://www.learnstorybook.com/`, addons: `${homepageUrl}/addons/`, community: `${homepageUrl}/community/`, useCases: `${homepageUrl}/use-cases/`, support: `${homepageUrl}/support/`, team: `${homepageUrl}/team/`, // Social blog: `https://medium.com/storybookjs`, twitter: `https://twitter.com/storybookjs`, chat: `https://discord.gg/UUt2PJb`, youtube: `https://www.youtube.com/channel/UCr7Quur3eIyA_oe8FNYexfg`, // Brand brand: `${gitHubOrg}/brand`, designSystem: `https://storybooks-official.netlify.com`, badge: `${gitHubOrg}/brand/tree/master/badge`, presentation: `${gitHubOrg}/brand/tree/master/presentation`, video: `${gitHubOrg}/brand/tree/master/video`, // Framework docs framework: { react: `${docsUrl}/guides/guide-react/`, reactNative: `${docsUrl}/guides/guide-react-native/`, vue: `${docsUrl}/guides/guide-vue/`, angular: `${docsUrl}/guides/guide-angular/`, ember: `${docsUrl}/guides/guide-ember/`, html: `${docsUrl}/guides/guide-html/`, svelte: `${docsUrl}/guides/guide-svelte/`, mithril: `${docsUrl}/guides/guide-mithril/`, riot: `${docsUrl}/guides/guide-riot/`, }, // Official addons officialAddons: { knobs: `${gitHubOrg}/storybook/tree/master/addons/knobs`, actions: `${gitHubOrg}/storybook/tree/master/addons/actions`, source: `${gitHubOrg}/storybook/tree/master/addons/storysource`, info: `${gitHubOrg}/storybook/tree/master/addons/info`, viewport: `${gitHubOrg}/storybook/tree/master/addons/viewport`, storyshots: `${gitHubOrg}/storybook/tree/master/addons/storyshots`, backgrounds: `${gitHubOrg}/storybook/tree/master/addons/backgrounds`, accessibility: `${gitHubOrg}/storybook/tree/master/addons/a11y`, console: `${gitHubOrg}/storybook-addon-console`, links: `${gitHubOrg}/storybook/tree/master/addons/links`, }, };
docs/src/new-components/basics/shared/site.js
1
https://github.com/storybookjs/storybook/commit/dfe7e3b578a56328a20b0bcd676cc177891d40d1
[ 0.8518641591072083, 0.08650913089513779, 0.00016498190234415233, 0.00017383099475409836, 0.2551366090774536 ]
{ "id": 1, "code_window": [ " angular: `${npmApiBase}/@storybook/angular`,\n", " ember: `${npmApiBase}/@storybook/ember`,\n", " html: `${npmApiBase}/@storybook/html`,\n", " svelte: `${npmApiBase}/@storybook/svelte`,\n", " mithril: `${npmApiBase}/@storybook/mithril`,\n", " riot: `${npmApiBase}/@storybook/riot`,\n", " polymer: `${npmApiBase}/@storybook/polymer`,\n", " preact: `${npmApiBase}/@storybook/preact`,\n", " },\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " marko: `${npmApiBase}/@storybook/marko`,\n" ], "file_path": "docs/src/new-components/basics/shared/site.js", "type": "add", "edit_start_line_idx": 37 }
import { storiesOf, moduleMetadata } from '@storybook/angular'; import { withKnobs, text, object } from '@storybook/addon-knobs'; import { action } from '@storybook/addon-actions'; import { ChipsModule } from './chips.module'; import { ChipsGroupComponent } from './chips-group.component'; import { ChipComponent } from './chip.component'; import { CHIP_COLOR } from './chip-color.token'; storiesOf('Custom|Feature Module as Context', module) .addDecorator(withKnobs) .addDecorator( moduleMetadata({ imports: [ChipsModule], }) ) .add( 'Component with self and dependencies declared in its feature module', () => { const props: { [K in keyof ChipsGroupComponent]?: any } = { chips: object('Chips', [ { id: 1, text: 'Chip 1', }, { id: 2, text: 'Chip 2', }, ]), removeChipClick: action('Remove chip'), removeAllChipsClick: action('Remove all chips clicked'), }; return { component: ChipsGroupComponent, props, }; }, { notes: `This component includes a child component, a pipe, and a default provider, all which come from the specified feature module.`, } ) .add('Component with default providers', () => { const props: { [K in keyof ChipComponent]?: any } = { displayText: text('Display Text', 'My Chip'), removeClicked: action('Remove icon clicked'), }; return { component: ChipComponent, props, }; }) .add('Component with overridden provider', () => { const props: { [K in keyof ChipComponent]?: any } = { displayText: text('Display Text', 'My Chip'), removeClicked: action('Remove icon clicked'), }; return { component: ChipComponent, moduleMetadata: { providers: [ { provide: CHIP_COLOR, useValue: 'yellow', }, ], }, props, }; });
examples/angular-cli/src/stories/module-context/module-context.stories.ts
0
https://github.com/storybookjs/storybook/commit/dfe7e3b578a56328a20b0bcd676cc177891d40d1
[ 0.0001758362486725673, 0.00017370490240864456, 0.00017044042760971934, 0.00017389027925673872, 0.0000017795389339880785 ]
{ "id": 1, "code_window": [ " angular: `${npmApiBase}/@storybook/angular`,\n", " ember: `${npmApiBase}/@storybook/ember`,\n", " html: `${npmApiBase}/@storybook/html`,\n", " svelte: `${npmApiBase}/@storybook/svelte`,\n", " mithril: `${npmApiBase}/@storybook/mithril`,\n", " riot: `${npmApiBase}/@storybook/riot`,\n", " polymer: `${npmApiBase}/@storybook/polymer`,\n", " preact: `${npmApiBase}/@storybook/preact`,\n", " },\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " marko: `${npmApiBase}/@storybook/marko`,\n" ], "file_path": "docs/src/new-components/basics/shared/site.js", "type": "add", "edit_start_line_idx": 37 }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>sfc_vue</title> </head> <body> <div id="app"></div> <!-- built files will be auto injected --> </body> </html>
lib/cli/test/fixtures/sfc_vue/index.html
0
https://github.com/storybookjs/storybook/commit/dfe7e3b578a56328a20b0bcd676cc177891d40d1
[ 0.0001728211937006563, 0.0001718325656838715, 0.00017084395221900195, 0.0001718325656838715, 9.88620740827173e-7 ]
{ "id": 1, "code_window": [ " angular: `${npmApiBase}/@storybook/angular`,\n", " ember: `${npmApiBase}/@storybook/ember`,\n", " html: `${npmApiBase}/@storybook/html`,\n", " svelte: `${npmApiBase}/@storybook/svelte`,\n", " mithril: `${npmApiBase}/@storybook/mithril`,\n", " riot: `${npmApiBase}/@storybook/riot`,\n", " polymer: `${npmApiBase}/@storybook/polymer`,\n", " preact: `${npmApiBase}/@storybook/preact`,\n", " },\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " marko: `${npmApiBase}/@storybook/marko`,\n" ], "file_path": "docs/src/new-components/basics/shared/site.js", "type": "add", "edit_start_line_idx": 37 }
const path = require('path'); module.exports = ({ config }) => { config.module.rules.push({ test: [/\.stories\.js$/], loaders: [require.resolve('@storybook/addon-storysource/loader')], include: [path.resolve(__dirname, '../src')], enforce: 'pre', }); return config; };
examples/preact-kitchen-sink/.storybook/webpack.config.js
0
https://github.com/storybookjs/storybook/commit/dfe7e3b578a56328a20b0bcd676cc177891d40d1
[ 0.00017252466932404786, 0.0001720734580885619, 0.00017162226140499115, 0.0001720734580885619, 4.512039595283568e-7 ]
{ "id": 2, "code_window": [ " html: `${docsUrl}/guides/guide-html/`,\n", " svelte: `${docsUrl}/guides/guide-svelte/`,\n", " mithril: `${docsUrl}/guides/guide-mithril/`,\n", " riot: `${docsUrl}/guides/guide-riot/`,\n", " },\n", "\n", " // Official addons\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " marko: `${docsUrl}/guides/guide-marko/`,\n" ], "file_path": "docs/src/new-components/basics/shared/site.js", "type": "add", "edit_start_line_idx": 78 }
// eslint-disable import/prefer-default-export const gitHubOrg = `https://github.com/storybooks`; const homepageUrl = `https://storybook.js.org`; const docsUrl = `${homepageUrl}/docs`; const npmApiBase = `https://api.npmjs.org/downloads/point/last-month`; export const metadata = { title: 'Storybook', description: `Storybook is an open source tool for developing UI components in isolation for React, Vue, and Angular`, ogImage: '/images/social/open-graph.png', googleSiteVerification: '', latestVersion: 'v5.1', }; export const url = { gitHub: { repo: `${gitHubOrg}/storybook`, frontpage: `${gitHubOrg}/frontpage`, issues: `${gitHubOrg}/storybook/issues`, releases: `${gitHubOrg}/storybook/releases`, contributors: `${gitHubOrg}/storybook/graphs/contributors`, brand: `${gitHubOrg}/press`, }, npm: `https://www.npmjs.com/package/@storybook/react`, openCollective: `https://opencollective.com/storybook`, npmApi: { react: `${npmApiBase}/@storybook/react`, reactNative: `${npmApiBase}/@storybook/react-native`, vue: `${npmApiBase}/@storybook/vue`, angular: `${npmApiBase}/@storybook/angular`, ember: `${npmApiBase}/@storybook/ember`, html: `${npmApiBase}/@storybook/html`, svelte: `${npmApiBase}/@storybook/svelte`, mithril: `${npmApiBase}/@storybook/mithril`, riot: `${npmApiBase}/@storybook/riot`, polymer: `${npmApiBase}/@storybook/polymer`, preact: `${npmApiBase}/@storybook/preact`, }, // Navigation home: `${homepageUrl}`, docs: { home: `${docsUrl}/basics/introduction/`, addonInstruction: `${docsUrl}/addons/writing-addons/`, }, tutorials: `https://www.learnstorybook.com/`, addons: `${homepageUrl}/addons/`, community: `${homepageUrl}/community/`, useCases: `${homepageUrl}/use-cases/`, support: `${homepageUrl}/support/`, team: `${homepageUrl}/team/`, // Social blog: `https://medium.com/storybookjs`, twitter: `https://twitter.com/storybookjs`, chat: `https://discord.gg/UUt2PJb`, youtube: `https://www.youtube.com/channel/UCr7Quur3eIyA_oe8FNYexfg`, // Brand brand: `${gitHubOrg}/brand`, designSystem: `https://storybooks-official.netlify.com`, badge: `${gitHubOrg}/brand/tree/master/badge`, presentation: `${gitHubOrg}/brand/tree/master/presentation`, video: `${gitHubOrg}/brand/tree/master/video`, // Framework docs framework: { react: `${docsUrl}/guides/guide-react/`, reactNative: `${docsUrl}/guides/guide-react-native/`, vue: `${docsUrl}/guides/guide-vue/`, angular: `${docsUrl}/guides/guide-angular/`, ember: `${docsUrl}/guides/guide-ember/`, html: `${docsUrl}/guides/guide-html/`, svelte: `${docsUrl}/guides/guide-svelte/`, mithril: `${docsUrl}/guides/guide-mithril/`, riot: `${docsUrl}/guides/guide-riot/`, }, // Official addons officialAddons: { knobs: `${gitHubOrg}/storybook/tree/master/addons/knobs`, actions: `${gitHubOrg}/storybook/tree/master/addons/actions`, source: `${gitHubOrg}/storybook/tree/master/addons/storysource`, info: `${gitHubOrg}/storybook/tree/master/addons/info`, viewport: `${gitHubOrg}/storybook/tree/master/addons/viewport`, storyshots: `${gitHubOrg}/storybook/tree/master/addons/storyshots`, backgrounds: `${gitHubOrg}/storybook/tree/master/addons/backgrounds`, accessibility: `${gitHubOrg}/storybook/tree/master/addons/a11y`, console: `${gitHubOrg}/storybook-addon-console`, links: `${gitHubOrg}/storybook/tree/master/addons/links`, }, };
docs/src/new-components/basics/shared/site.js
1
https://github.com/storybookjs/storybook/commit/dfe7e3b578a56328a20b0bcd676cc177891d40d1
[ 0.7521966695785522, 0.07566486299037933, 0.00016902013157960027, 0.00020395565661601722, 0.22551119327545166 ]
{ "id": 2, "code_window": [ " html: `${docsUrl}/guides/guide-html/`,\n", " svelte: `${docsUrl}/guides/guide-svelte/`,\n", " mithril: `${docsUrl}/guides/guide-mithril/`,\n", " riot: `${docsUrl}/guides/guide-riot/`,\n", " },\n", "\n", " // Official addons\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " marko: `${docsUrl}/guides/guide-marko/`,\n" ], "file_path": "docs/src/new-components/basics/shared/site.js", "type": "add", "edit_start_line_idx": 78 }
import '@storybook/addon-storysource/register'; import '@storybook/addon-actions/register'; import '@storybook/addon-knobs/register'; import '@storybook/addon-options/register'; import '@storybook/addon-a11y/register';
examples/marko-cli/.storybook/addons.js
0
https://github.com/storybookjs/storybook/commit/dfe7e3b578a56328a20b0bcd676cc177891d40d1
[ 0.0001762175961630419, 0.0001762175961630419, 0.0001762175961630419, 0.0001762175961630419, 0 ]
{ "id": 2, "code_window": [ " html: `${docsUrl}/guides/guide-html/`,\n", " svelte: `${docsUrl}/guides/guide-svelte/`,\n", " mithril: `${docsUrl}/guides/guide-mithril/`,\n", " riot: `${docsUrl}/guides/guide-riot/`,\n", " },\n", "\n", " // Official addons\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " marko: `${docsUrl}/guides/guide-marko/`,\n" ], "file_path": "docs/src/new-components/basics/shared/site.js", "type": "add", "edit_start_line_idx": 78 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`cra-config when used with react-scripts < 2.1.0 should apply styling webpack rules 1`] = ` Object { "devtool": "cheap-eval-source-map", "module": Object { "noParse": /jquery/, "rules": Array [ Object { "include": "app/baseSrc", "loader": "babel-loader", "options": Object {}, "test": /\\\\\\.js\\$/, }, Object { "exclude": /\\\\\\.module\\\\\\.css\\$/, "sideEffects": true, "test": /\\\\\\.css\\$/, "use": "style-loader", }, Object { "test": /\\\\\\.module\\\\\\.css\\$/, "use": "style-loader", }, Object { "exclude": /\\\\\\.module\\\\\\.\\(scss\\|sass\\)\\$/, "sideEffects": true, "test": /\\\\\\.\\(scss\\|sass\\)\\$/, "use": "sass-loader", }, Object { "test": /\\\\\\.module\\\\\\.\\(scss\\|sass\\)\\$/, "use": "sass-loader", }, ], }, "plugins": Array [ BaseTestPlugin1 {}, BaseTestPlugin2 {}, ], "resolve": Object { "alias": Object { "baseAlias": "base-alias", }, "extensions": Array [ ".js", ".jsx", ], "modules": Array [], }, "resolveLoader": Object { "modules": Array [ "node_modules", "/app/react/src/server/__mocks__/react-scripts-2-0-0/node_modules", ], }, } `; exports[`cra-config when used with react-scripts >= 2.1.0 should apply Babel, styling rules and merge plugins 1`] = ` Object { "devtool": "cheap-eval-source-map", "module": Object { "noParse": /jquery/, "rules": Array [ Object { "include": "app/baseSrc", "loader": "babel-loader", "options": Object {}, "test": /\\\\\\.js\\$/, }, Object { "exclude": /\\\\\\.module\\\\\\.css\\$/, "sideEffects": true, "test": /\\\\\\.css\\$/, "use": "style-loader", }, Object { "test": /\\\\\\.module\\\\\\.css\\$/, "use": "style-loader", }, Object { "exclude": /\\\\\\.module\\\\\\.\\(scss\\|sass\\)\\$/, "sideEffects": true, "test": /\\\\\\.\\(scss\\|sass\\)\\$/, "use": "sass-loader", }, Object { "test": /\\\\\\.module\\\\\\.\\(scss\\|sass\\)\\$/, "use": "sass-loader", }, Object { "include": Array [ "app/src", "/test-project", ], "loader": "babel-loader", "options": Object {}, "test": /\\\\\\.\\(js\\|mjs\\|jsx\\|ts\\|tsx\\)\\$/, }, ], }, "plugins": Array [ BaseTestPlugin1 {}, BaseTestPlugin2 {}, CRATestPlugin1 {}, CRATestPlugin2 {}, ], "resolve": Object { "alias": Object { "baseAlias": "base-alias", }, "extensions": Array [ ".js", ".jsx", ".ts", ".tsx", ], "modules": Array [], }, "resolveLoader": Object { "modules": Array [ "node_modules", "/app/react/src/server/__mocks__/react-scripts-2-1-0/node_modules", ], }, } `;
app/react/src/server/__snapshots__/cra-config.test.js.snap
0
https://github.com/storybookjs/storybook/commit/dfe7e3b578a56328a20b0bcd676cc177891d40d1
[ 0.00017338783072773367, 0.00017124730220530182, 0.00016771029913797975, 0.00017136862152256072, 0.0000014974860960137448 ]
{ "id": 2, "code_window": [ " html: `${docsUrl}/guides/guide-html/`,\n", " svelte: `${docsUrl}/guides/guide-svelte/`,\n", " mithril: `${docsUrl}/guides/guide-mithril/`,\n", " riot: `${docsUrl}/guides/guide-riot/`,\n", " },\n", "\n", " // Official addons\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " marko: `${docsUrl}/guides/guide-marko/`,\n" ], "file_path": "docs/src/new-components/basics/shared/site.js", "type": "add", "edit_start_line_idx": 78 }
{"version":"5.1.9","info":{"plain":"### Bug Fixes\n\n* Core: Fix JSON babel config error reporting ([#7104](https://github.com/storybookjs/storybook/pull/7104))\n* UI: Fix about page version check message ([#7105](https://github.com/storybookjs/storybook/pull/7105))\n\n### Dependency Upgrades\n\n* Add missing dependencies to ui/react ([#7081](https://github.com/storybookjs/storybook/pull/7081))\n* UPGRADE lazy-universal-dotenv ([#7151](https://github.com/storybookjs/storybook/pull/7151))\n* Make compatible with yarn Pnp ([#6922](https://github.com/storybookjs/storybook/pull/6922))"}}
docs/src/versions/latest.json
0
https://github.com/storybookjs/storybook/commit/dfe7e3b578a56328a20b0bcd676cc177891d40d1
[ 0.00016847081133164465, 0.00016847081133164465, 0.00016847081133164465, 0.00016847081133164465, 0 ]
{ "id": 0, "code_window": [ "\tstatic readonly TestItemGutter = new MenuId('TestItemGutter');\n", "\tstatic readonly TestPeekElement = new MenuId('TestPeekElement');\n", "\tstatic readonly TestPeekTitle = new MenuId('TestPeekTitle');\n", "\tstatic readonly TouchBarContext = new MenuId('TouchBarContext');\n", "\tstatic readonly TitleBarContext = new MenuId('TitleBarContext');\n", "\tstatic readonly TunnelContext = new MenuId('TunnelContext');\n", "\tstatic readonly TunnelPrivacy = new MenuId('TunnelPrivacy');\n", "\tstatic readonly TunnelProtocol = new MenuId('TunnelProtocol');\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tstatic readonly TitleBarTitleContext = new MenuId('TitleBarTitleContext');\n" ], "file_path": "src/vs/platform/actions/common/actions.ts", "type": "replace", "edit_start_line_idx": 110 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./media/titlebarpart'; import { localize } from 'vs/nls'; import { Part } from 'vs/workbench/browser/part'; import { ITitleService, ITitleProperties } from 'vs/workbench/services/title/common/titleService'; import { getZoomFactor } from 'vs/base/browser/browser'; import { MenuBarVisibility, getTitleBarStyle, getMenuBarVisibility } from 'vs/platform/window/common/window'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import { IAction, toAction } from 'vs/base/common/actions'; import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration'; import { DisposableStore, dispose } from 'vs/base/common/lifecycle'; import { IBrowserWorkbenchEnvironmentService } from 'vs/workbench/services/environment/browser/environmentService'; import { IThemeService, registerThemingParticipant, ThemeIcon } from 'vs/platform/theme/common/themeService'; import { TITLE_BAR_ACTIVE_BACKGROUND, TITLE_BAR_ACTIVE_FOREGROUND, TITLE_BAR_INACTIVE_FOREGROUND, TITLE_BAR_INACTIVE_BACKGROUND, TITLE_BAR_BORDER, WORKBENCH_BACKGROUND } from 'vs/workbench/common/theme'; import { isMacintosh, isWindows, isLinux, isWeb } from 'vs/base/common/platform'; import { Color } from 'vs/base/common/color'; import { EventType, EventHelper, Dimension, isAncestor, append, $, addDisposableListener, runAtThisOrScheduleAtNextAnimationFrame, prepend, reset } from 'vs/base/browser/dom'; import { CustomMenubarControl } from 'vs/workbench/browser/parts/titlebar/menubarControl'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { Emitter, Event } from 'vs/base/common/event'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { Parts, IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService'; import { createActionViewItem, createAndFillInContextMenuActions } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { IMenuService, IMenu, MenuId } from 'vs/platform/actions/common/actions'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IHostService } from 'vs/workbench/services/host/browser/host'; import { Codicon } from 'vs/base/common/codicons'; import { getIconRegistry } from 'vs/platform/theme/common/iconRegistry'; import { ToolBar } from 'vs/base/browser/ui/toolbar/toolbar'; import { WindowTitle } from 'vs/workbench/browser/parts/titlebar/windowTitle'; import { CommandCenterControl } from 'vs/workbench/browser/parts/titlebar/commandCenterControl'; import { IHoverDelegate } from 'vs/base/browser/ui/iconLabel/iconHoverDelegate'; import { IHoverService } from 'vs/workbench/services/hover/browser/hover'; export class TitlebarPart extends Part implements ITitleService { private static readonly configCommandCenter = 'window.commandCenter'; declare readonly _serviceBrand: undefined; //#region IView readonly minimumWidth: number = 0; readonly maximumWidth: number = Number.POSITIVE_INFINITY; get minimumHeight(): number { const value = this.isCommandCenterVisible ? 35 : 30; return value / (this.currentMenubarVisibility === 'hidden' || getZoomFactor() < 1 ? getZoomFactor() : 1); } get maximumHeight(): number { return this.minimumHeight; } //#endregion private _onMenubarVisibilityChange = this._register(new Emitter<boolean>()); readonly onMenubarVisibilityChange = this._onMenubarVisibilityChange.event; private readonly _onDidChangeCommandCenterVisibility = new Emitter<void>(); readonly onDidChangeCommandCenterVisibility: Event<void> = this._onDidChangeCommandCenterVisibility.event; protected rootContainer!: HTMLElement; protected windowControls: HTMLElement | undefined; protected title!: HTMLElement; protected customMenubar: CustomMenubarControl | undefined; protected appIcon: HTMLElement | undefined; private appIconBadge: HTMLElement | undefined; protected menubar?: HTMLElement; protected layoutControls: HTMLElement | undefined; private layoutToolbar: ToolBar | undefined; protected lastLayoutDimensions: Dimension | undefined; private hoverDelegate: IHoverDelegate; private readonly titleDisposables = this._register(new DisposableStore()); private titleBarStyle: 'native' | 'custom'; private isInactive: boolean = false; private readonly windowTitle: WindowTitle; private readonly contextMenu: IMenu; constructor( @IContextMenuService private readonly contextMenuService: IContextMenuService, @IConfigurationService protected readonly configurationService: IConfigurationService, @IBrowserWorkbenchEnvironmentService protected readonly environmentService: IBrowserWorkbenchEnvironmentService, @IInstantiationService protected readonly instantiationService: IInstantiationService, @IThemeService themeService: IThemeService, @IStorageService storageService: IStorageService, @IWorkbenchLayoutService layoutService: IWorkbenchLayoutService, @IMenuService private readonly menuService: IMenuService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IHostService private readonly hostService: IHostService, @IHoverService hoverService: IHoverService, ) { super(Parts.TITLEBAR_PART, { hasTitle: false }, themeService, storageService, layoutService); this.windowTitle = this._register(instantiationService.createInstance(WindowTitle)); this.contextMenu = this._register(menuService.createMenu(MenuId.TitleBarContext, contextKeyService)); this.titleBarStyle = getTitleBarStyle(this.configurationService); this.hoverDelegate = new class implements IHoverDelegate { private _lastHoverHideTime: number = 0; readonly showHover = hoverService.showHover.bind(hoverService); readonly placement = 'element'; get delay(): number { return Date.now() - this._lastHoverHideTime < 200 ? 0 // show instantly when a hover was recently shown : configurationService.getValue<number>('workbench.hover.delay'); } onDidHideHover() { this._lastHoverHideTime = Date.now(); } }; this.registerListeners(); } updateProperties(properties: ITitleProperties): void { this.windowTitle.updateProperties(properties); } get isCommandCenterVisible() { return this.configurationService.getValue<boolean>(TitlebarPart.configCommandCenter); } private registerListeners(): void { this._register(this.hostService.onDidChangeFocus(focused => focused ? this.onFocus() : this.onBlur())); this._register(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationChanged(e))); } private onBlur(): void { this.isInactive = true; this.updateStyles(); } private onFocus(): void { this.isInactive = false; this.updateStyles(); } protected onConfigurationChanged(event: IConfigurationChangeEvent): void { if (this.titleBarStyle !== 'native' && (!isMacintosh || isWeb)) { if (event.affectsConfiguration('window.menuBarVisibility')) { if (this.currentMenubarVisibility === 'compact') { this.uninstallMenubar(); } else { this.installMenubar(); } } } if (this.titleBarStyle !== 'native' && this.layoutControls && event.affectsConfiguration('workbench.layoutControl.enabled')) { this.layoutControls.classList.toggle('show-layout-control', this.layoutControlEnabled); } if (event.affectsConfiguration(TitlebarPart.configCommandCenter)) { this.updateTitle(); this.adjustTitleMarginToCenter(); this._onDidChangeCommandCenterVisibility.fire(); } } protected onMenubarVisibilityChanged(visible: boolean): void { if (isWeb || isWindows || isLinux) { if (this.lastLayoutDimensions) { this.layout(this.lastLayoutDimensions.width, this.lastLayoutDimensions.height); } this._onMenubarVisibilityChange.fire(visible); } } private uninstallMenubar(): void { if (this.customMenubar) { this.customMenubar.dispose(); this.customMenubar = undefined; } if (this.menubar) { this.menubar.remove(); this.menubar = undefined; } this.onMenubarVisibilityChanged(false); } protected installMenubar(): void { // If the menubar is already installed, skip if (this.menubar) { return; } this.customMenubar = this._register(this.instantiationService.createInstance(CustomMenubarControl)); this.menubar = this.rootContainer.insertBefore($('div.menubar'), this.title); this.menubar.setAttribute('role', 'menubar'); this._register(this.customMenubar.onVisibilityChange(e => this.onMenubarVisibilityChanged(e))); this.customMenubar.create(this.menubar); } private updateTitle(): void { this.titleDisposables.clear(); if (!this.isCommandCenterVisible) { // Text Title this.title.innerText = this.windowTitle.value; this.titleDisposables.add(this.windowTitle.onDidChange(() => { this.title.innerText = this.windowTitle.value; this.adjustTitleMarginToCenter(); })); } else { // Menu Title const commandCenter = this.instantiationService.createInstance(CommandCenterControl, this.windowTitle, this.hoverDelegate); reset(this.title, commandCenter.element); this.titleDisposables.add(commandCenter); this.titleDisposables.add(commandCenter.onDidChangeVisibility(this.adjustTitleMarginToCenter, this)); } } override createContentArea(parent: HTMLElement): HTMLElement { this.element = parent; this.rootContainer = append(parent, $('.titlebar-container')); // App Icon (Native Windows/Linux and Web) if (!isMacintosh || isWeb) { this.appIcon = prepend(this.rootContainer, $('a.window-appicon')); // Web-only home indicator and menu if (isWeb) { const homeIndicator = this.environmentService.options?.homeIndicator; if (homeIndicator) { const icon: ThemeIcon = getIconRegistry().getIcon(homeIndicator.icon) ? { id: homeIndicator.icon } : Codicon.code; this.appIcon.setAttribute('href', homeIndicator.href); this.appIcon.classList.add(...ThemeIcon.asClassNameArray(icon)); this.appIconBadge = document.createElement('div'); this.appIconBadge.classList.add('home-bar-icon-badge'); this.appIcon.appendChild(this.appIconBadge); } } } // Menubar: install a custom menu bar depending on configuration // and when not in activity bar if (this.titleBarStyle !== 'native' && (!isMacintosh || isWeb) && this.currentMenubarVisibility !== 'compact') { this.installMenubar(); } // Title this.title = append(this.rootContainer, $('div.window-title')); this.updateTitle(); if (this.titleBarStyle !== 'native') { this.layoutControls = append(this.rootContainer, $('div.layout-controls-container')); this.layoutControls.classList.toggle('show-layout-control', this.layoutControlEnabled); this.layoutToolbar = new ToolBar(this.layoutControls, this.contextMenuService, { actionViewItemProvider: action => { return createActionViewItem(this.instantiationService, action, { hoverDelegate: this.hoverDelegate }); }, allowContextMenu: true }); this._register(addDisposableListener(this.layoutControls, EventType.CONTEXT_MENU, e => { EventHelper.stop(e); this.onLayoutControlContextMenu(e, this.layoutControls!); })); const menu = this._register(this.menuService.createMenu(MenuId.LayoutControlMenu, this.contextKeyService)); const updateLayoutMenu = () => { if (!this.layoutToolbar) { return; } const actions: IAction[] = []; const toDispose = createAndFillInContextMenuActions(menu, undefined, { primary: [], secondary: actions }); this.layoutToolbar.setActions(actions); toDispose.dispose(); }; menu.onDidChange(updateLayoutMenu); updateLayoutMenu(); } this.windowControls = append(this.element, $('div.window-controls-container')); // Context menu on title [EventType.CONTEXT_MENU, EventType.MOUSE_DOWN].forEach(event => { this._register(addDisposableListener(this.title, event, e => { if (e.type === EventType.CONTEXT_MENU || e.metaKey) { EventHelper.stop(e); this.onContextMenu(e); } })); }); // Since the title area is used to drag the window, we do not want to steal focus from the // currently active element. So we restore focus after a timeout back to where it was. this._register(addDisposableListener(this.element, EventType.MOUSE_DOWN, e => { if (e.target && this.menubar && isAncestor(e.target as HTMLElement, this.menubar)) { return; } if (e.target && this.layoutToolbar && isAncestor(e.target as HTMLElement, this.layoutToolbar.getElement())) { return; } if (e.target && isAncestor(e.target as HTMLElement, this.title)) { return; } const active = document.activeElement; setTimeout(() => { if (active instanceof HTMLElement) { active.focus(); } }, 0 /* need a timeout because we are in capture phase */); }, true /* use capture to know the currently active element properly */)); this.updateStyles(); return this.element; } override updateStyles(): void { super.updateStyles(); // Part container if (this.element) { if (this.isInactive) { this.element.classList.add('inactive'); } else { this.element.classList.remove('inactive'); } const titleBackground = this.getColor(this.isInactive ? TITLE_BAR_INACTIVE_BACKGROUND : TITLE_BAR_ACTIVE_BACKGROUND, (color, theme) => { // LCD Rendering Support: the title bar part is a defining its own GPU layer. // To benefit from LCD font rendering, we must ensure that we always set an // opaque background color. As such, we compute an opaque color given we know // the background color is the workbench background. return color.isOpaque() ? color : color.makeOpaque(WORKBENCH_BACKGROUND(theme)); }) || ''; this.element.style.backgroundColor = titleBackground; if (this.appIconBadge) { this.appIconBadge.style.backgroundColor = titleBackground; } if (titleBackground && Color.fromHex(titleBackground).isLighter()) { this.element.classList.add('light'); } else { this.element.classList.remove('light'); } const titleForeground = this.getColor(this.isInactive ? TITLE_BAR_INACTIVE_FOREGROUND : TITLE_BAR_ACTIVE_FOREGROUND); this.element.style.color = titleForeground || ''; const titleBorder = this.getColor(TITLE_BAR_BORDER); this.element.style.borderBottom = titleBorder ? `1px solid ${titleBorder}` : ''; } } private onContextMenu(e: MouseEvent): void { // Find target anchor const event = new StandardMouseEvent(e); const anchor = { x: event.posx, y: event.posy }; // Fill in contributed actions const actions: IAction[] = []; const actionsDisposable = createAndFillInContextMenuActions(this.contextMenu, undefined, actions); // Show it this.contextMenuService.showContextMenu({ getAnchor: () => anchor, getActions: () => actions, onHide: () => dispose(actionsDisposable) }); } private onLayoutControlContextMenu(e: MouseEvent, el: HTMLElement): void { // Find target anchor const event = new StandardMouseEvent(e); const anchor = { x: event.posx, y: event.posy }; const actions: IAction[] = []; actions.push(toAction({ id: 'layoutControl.hide', label: localize('layoutControl.hide', "Hide Layout Control"), run: () => { this.configurationService.updateValue('workbench.layoutControl.enabled', false); } })); // Show it this.contextMenuService.showContextMenu({ getAnchor: () => anchor, getActions: () => actions, domForShadowRoot: el }); } protected adjustTitleMarginToCenter(): void { const base = isMacintosh ? (this.windowControls?.clientWidth ?? 0) : 0; const leftMarker = base + (this.appIcon?.clientWidth ?? 0) + (this.menubar?.clientWidth ?? 0) + 10; const rightMarker = base + this.rootContainer.clientWidth - (this.layoutControls?.clientWidth ?? 0) - 10; // Not enough space to center the titlebar within window, // Center between left and right controls if (leftMarker > (this.rootContainer.clientWidth + (this.windowControls?.clientWidth ?? 0) - this.title.clientWidth) / 2 || rightMarker < (this.rootContainer.clientWidth + (this.windowControls?.clientWidth ?? 0) + this.title.clientWidth) / 2) { this.title.style.position = ''; this.title.style.left = ''; this.title.style.transform = ''; return; } this.title.style.position = 'absolute'; this.title.style.left = `calc(50% - ${this.title.clientWidth / 2}px)`; } protected get currentMenubarVisibility(): MenuBarVisibility { return getMenuBarVisibility(this.configurationService); } private get layoutControlEnabled(): boolean { return this.configurationService.getValue<boolean>('workbench.layoutControl.enabled'); } updateLayout(dimension: Dimension): void { this.lastLayoutDimensions = dimension; if (getTitleBarStyle(this.configurationService) === 'custom') { // Prevent zooming behavior if any of the following conditions are met: // 1. Native macOS // 2. Menubar is hidden // 3. Shrinking below the window control size (zoom < 1) const zoomFactor = getZoomFactor(); this.element.style.setProperty('--zoom-factor', zoomFactor.toString()); this.rootContainer.classList.toggle('counter-zoom', zoomFactor < 1 || (!isWeb && isMacintosh) || this.currentMenubarVisibility === 'hidden'); runAtThisOrScheduleAtNextAnimationFrame(() => this.adjustTitleMarginToCenter()); if (this.customMenubar) { const menubarDimension = new Dimension(0, dimension.height); this.customMenubar.layout(menubarDimension); } } } override layout(width: number, height: number): void { this.updateLayout(new Dimension(width, height)); super.layoutContents(width, height); } toJSON(): object { return { type: Parts.TITLEBAR_PART }; } } registerThemingParticipant((theme, collector) => { const titlebarActiveFg = theme.getColor(TITLE_BAR_ACTIVE_FOREGROUND); if (titlebarActiveFg) { collector.addRule(` .monaco-workbench .part.titlebar .window-controls-container .window-icon { color: ${titlebarActiveFg}; } `); } const titlebarInactiveFg = theme.getColor(TITLE_BAR_INACTIVE_FOREGROUND); if (titlebarInactiveFg) { collector.addRule(` .monaco-workbench .part.titlebar.inactive .window-controls-container .window-icon { color: ${titlebarInactiveFg}; } `); } });
src/vs/workbench/browser/parts/titlebar/titlebarPart.ts
1
https://github.com/microsoft/vscode/commit/27bb32d00a7e309787e8f3cea271d67f7921dbba
[ 0.9566934704780579, 0.018926706165075302, 0.0001614350767340511, 0.00017251331883016974, 0.13262024521827698 ]
{ "id": 0, "code_window": [ "\tstatic readonly TestItemGutter = new MenuId('TestItemGutter');\n", "\tstatic readonly TestPeekElement = new MenuId('TestPeekElement');\n", "\tstatic readonly TestPeekTitle = new MenuId('TestPeekTitle');\n", "\tstatic readonly TouchBarContext = new MenuId('TouchBarContext');\n", "\tstatic readonly TitleBarContext = new MenuId('TitleBarContext');\n", "\tstatic readonly TunnelContext = new MenuId('TunnelContext');\n", "\tstatic readonly TunnelPrivacy = new MenuId('TunnelPrivacy');\n", "\tstatic readonly TunnelProtocol = new MenuId('TunnelProtocol');\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tstatic readonly TitleBarTitleContext = new MenuId('TitleBarTitleContext');\n" ], "file_path": "src/vs/platform/actions/common/actions.ts", "type": "replace", "edit_start_line_idx": 110 }
"use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", { value: true }); const assert = require("assert"); const i18n = require("../i18n"); suite('XLF Parser Tests', () => { const sampleXlf = '<?xml version="1.0" encoding="utf-8"?><xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"><file original="vs/base/common/keybinding" source-language="en" datatype="plaintext"><body><trans-unit id="key1"><source xml:lang="en">Key #1</source></trans-unit><trans-unit id="key2"><source xml:lang="en">Key #2 &amp;</source></trans-unit></body></file></xliff>'; const sampleTranslatedXlf = '<?xml version="1.0" encoding="utf-8"?><xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"><file original="vs/base/common/keybinding" source-language="en" target-language="ru" datatype="plaintext"><body><trans-unit id="key1"><source xml:lang="en">Key #1</source><target>Кнопка #1</target></trans-unit><trans-unit id="key2"><source xml:lang="en">Key #2 &amp;</source><target>Кнопка #2 &amp;</target></trans-unit></body></file></xliff>'; const originalFilePath = 'vs/base/common/keybinding'; const keys = ['key1', 'key2']; const messages = ['Key #1', 'Key #2 &']; const translatedMessages = { key1: 'Кнопка #1', key2: 'Кнопка #2 &' }; test('Keys & messages to XLF conversion', () => { const xlf = new i18n.XLF('vscode-workbench'); xlf.addFile(originalFilePath, keys, messages); const xlfString = xlf.toString(); assert.strictEqual(xlfString.replace(/\s{2,}/g, ''), sampleXlf); }); test('XLF to keys & messages conversion', () => { i18n.XLF.parse(sampleTranslatedXlf).then(function (resolvedFiles) { assert.deepStrictEqual(resolvedFiles[0].messages, translatedMessages); assert.strictEqual(resolvedFiles[0].originalFilePath, originalFilePath); }); }); test('JSON file source path to Transifex resource match', () => { const editorProject = 'vscode-editor', workbenchProject = 'vscode-workbench'; const platform = { name: 'vs/platform', project: editorProject }, editorContrib = { name: 'vs/editor/contrib', project: editorProject }, editor = { name: 'vs/editor', project: editorProject }, base = { name: 'vs/base', project: editorProject }, code = { name: 'vs/code', project: workbenchProject }, workbenchParts = { name: 'vs/workbench/contrib/html', project: workbenchProject }, workbenchServices = { name: 'vs/workbench/services/textfile', project: workbenchProject }, workbench = { name: 'vs/workbench', project: workbenchProject }; assert.deepStrictEqual(i18n.getResource('vs/platform/actions/browser/menusExtensionPoint'), platform); assert.deepStrictEqual(i18n.getResource('vs/editor/contrib/clipboard/browser/clipboard'), editorContrib); assert.deepStrictEqual(i18n.getResource('vs/editor/common/modes/modesRegistry'), editor); assert.deepStrictEqual(i18n.getResource('vs/base/common/errorMessage'), base); assert.deepStrictEqual(i18n.getResource('vs/code/electron-main/window'), code); assert.deepStrictEqual(i18n.getResource('vs/workbench/contrib/html/browser/webview'), workbenchParts); assert.deepStrictEqual(i18n.getResource('vs/workbench/services/textfile/node/testFileService'), workbenchServices); assert.deepStrictEqual(i18n.getResource('vs/workbench/browser/parts/panel/panelActions'), workbench); }); });
build/lib/test/i18n.test.js
0
https://github.com/microsoft/vscode/commit/27bb32d00a7e309787e8f3cea271d67f7921dbba
[ 0.00017597748956177384, 0.0001754027616698295, 0.0001748523354763165, 0.0001753833203110844, 4.213278828046896e-7 ]
{ "id": 0, "code_window": [ "\tstatic readonly TestItemGutter = new MenuId('TestItemGutter');\n", "\tstatic readonly TestPeekElement = new MenuId('TestPeekElement');\n", "\tstatic readonly TestPeekTitle = new MenuId('TestPeekTitle');\n", "\tstatic readonly TouchBarContext = new MenuId('TouchBarContext');\n", "\tstatic readonly TitleBarContext = new MenuId('TitleBarContext');\n", "\tstatic readonly TunnelContext = new MenuId('TunnelContext');\n", "\tstatic readonly TunnelPrivacy = new MenuId('TunnelPrivacy');\n", "\tstatic readonly TunnelProtocol = new MenuId('TunnelProtocol');\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tstatic readonly TitleBarTitleContext = new MenuId('TitleBarTitleContext');\n" ], "file_path": "src/vs/platform/actions/common/actions.ts", "type": "replace", "edit_start_line_idx": 110 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { timeout } from 'vs/base/common/async'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { Emitter } from 'vs/base/common/event'; import { Disposable, dispose, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { ILogService } from 'vs/platform/log/common/log'; /** * A helper class to track requests that have replies. Using this it's easy to implement an event * that accepts a reply. */ export class RequestStore<T, RequestArgs> extends Disposable { private _lastRequestId = 0; private readonly _timeout: number; private _pendingRequests: Map<number, (resolved: T) => void> = new Map(); private _pendingRequestDisposables: Map<number, IDisposable[]> = new Map(); private readonly _onCreateRequest = this._register(new Emitter<RequestArgs & { requestId: number }>()); readonly onCreateRequest = this._onCreateRequest.event; /** * @param timeout How long in ms to allow requests to go unanswered for, undefined will use the * default (15 seconds). */ constructor( timeout: number | undefined, @ILogService private readonly _logService: ILogService ) { super(); this._timeout = timeout === undefined ? 15000 : timeout; } /** * Creates a request. * @param args The arguments to pass to the onCreateRequest event. */ createRequest(args: RequestArgs): Promise<T> { return new Promise<T>((resolve, reject) => { const requestId = ++this._lastRequestId; this._pendingRequests.set(requestId, resolve); this._onCreateRequest.fire({ requestId, ...args }); const tokenSource = new CancellationTokenSource(); timeout(this._timeout, tokenSource.token).then(() => reject(`Request ${requestId} timed out (${this._timeout}ms)`)); this._pendingRequestDisposables.set(requestId, [toDisposable(() => tokenSource.cancel())]); }); } /** * Accept a reply to a request. * @param requestId The request ID originating from the onCreateRequest event. * @param data The reply data. */ acceptReply(requestId: number, data: T) { const resolveRequest = this._pendingRequests.get(requestId); if (resolveRequest) { this._pendingRequests.delete(requestId); dispose(this._pendingRequestDisposables.get(requestId) || []); this._pendingRequestDisposables.delete(requestId); resolveRequest(data); } else { this._logService.warn(`RequestStore#acceptReply was called without receiving a matching request ${requestId}`); } } }
src/vs/platform/terminal/common/requestStore.ts
0
https://github.com/microsoft/vscode/commit/27bb32d00a7e309787e8f3cea271d67f7921dbba
[ 0.00017646324704401195, 0.00017050937458407134, 0.0001651025959290564, 0.00017028755974024534, 0.000003443647983658593 ]
{ "id": 0, "code_window": [ "\tstatic readonly TestItemGutter = new MenuId('TestItemGutter');\n", "\tstatic readonly TestPeekElement = new MenuId('TestPeekElement');\n", "\tstatic readonly TestPeekTitle = new MenuId('TestPeekTitle');\n", "\tstatic readonly TouchBarContext = new MenuId('TouchBarContext');\n", "\tstatic readonly TitleBarContext = new MenuId('TitleBarContext');\n", "\tstatic readonly TunnelContext = new MenuId('TunnelContext');\n", "\tstatic readonly TunnelPrivacy = new MenuId('TunnelPrivacy');\n", "\tstatic readonly TunnelProtocol = new MenuId('TunnelProtocol');\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tstatic readonly TitleBarTitleContext = new MenuId('TitleBarTitleContext');\n" ], "file_path": "src/vs/platform/actions/common/actions.ts", "type": "replace", "edit_start_line_idx": 110 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; export interface IPointerMoveCallback { (event: PointerEvent): void; } export interface IOnStopCallback { (browserEvent?: PointerEvent | KeyboardEvent): void; } export class GlobalPointerMoveMonitor implements IDisposable { private readonly _hooks = new DisposableStore(); private _pointerMoveCallback: IPointerMoveCallback | null = null; private _onStopCallback: IOnStopCallback | null = null; public dispose(): void { this.stopMonitoring(false); this._hooks.dispose(); } public stopMonitoring(invokeStopCallback: boolean, browserEvent?: PointerEvent | KeyboardEvent): void { if (!this.isMonitoring()) { // Not monitoring return; } // Unhook this._hooks.clear(); this._pointerMoveCallback = null; const onStopCallback = this._onStopCallback; this._onStopCallback = null; if (invokeStopCallback && onStopCallback) { onStopCallback(browserEvent); } } public isMonitoring(): boolean { return !!this._pointerMoveCallback; } public startMonitoring( initialElement: Element, pointerId: number, initialButtons: number, pointerMoveCallback: IPointerMoveCallback, onStopCallback: IOnStopCallback ): void { if (this.isMonitoring()) { this.stopMonitoring(false); } this._pointerMoveCallback = pointerMoveCallback; this._onStopCallback = onStopCallback; let eventSource: Element | Window = initialElement; try { initialElement.setPointerCapture(pointerId); this._hooks.add(toDisposable(() => { initialElement.releasePointerCapture(pointerId); })); } catch (err) { // See https://github.com/microsoft/vscode/issues/144584 // See https://github.com/microsoft/vscode/issues/146947 // `setPointerCapture` sometimes fails when being invoked // from a `mousedown` listener on macOS and Windows // and it always fails on Linux with the exception: // DOMException: Failed to execute 'setPointerCapture' on 'Element': // No active pointer with the given id is found. // In case of failure, we bind the listeners on the window eventSource = window; } this._hooks.add(dom.addDisposableListener( eventSource, dom.EventType.POINTER_MOVE, (e) => { if (e.buttons !== initialButtons) { // Buttons state has changed in the meantime this.stopMonitoring(true); return; } e.preventDefault(); this._pointerMoveCallback!(e); } )); this._hooks.add(dom.addDisposableListener( eventSource, dom.EventType.POINTER_UP, (e: PointerEvent) => this.stopMonitoring(true) )); } }
src/vs/base/browser/globalPointerMoveMonitor.ts
0
https://github.com/microsoft/vscode/commit/27bb32d00a7e309787e8f3cea271d67f7921dbba
[ 0.0001780620077624917, 0.00017435839981772006, 0.00017103497521020472, 0.00017464339907746762, 0.000001909020966195385 ]
{ "id": 1, "code_window": [ "\tprivate isInactive: boolean = false;\n", "\n", "\tprivate readonly windowTitle: WindowTitle;\n", "\n", "\tprivate readonly contextMenu: IMenu;\n", "\n", "\tconstructor(\n", "\t\t@IContextMenuService private readonly contextMenuService: IContextMenuService,\n", "\t\t@IConfigurationService protected readonly configurationService: IConfigurationService,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate readonly titleContextMenu: IMenu;\n" ], "file_path": "src/vs/workbench/browser/parts/titlebar/titlebarPart.ts", "type": "replace", "edit_start_line_idx": 84 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Action, IAction, Separator, SubmenuAction } from 'vs/base/common/actions'; import { CSSIcon } from 'vs/base/common/codicons'; import { Emitter, Event } from 'vs/base/common/event'; import { Iterable } from 'vs/base/common/iterator'; import { DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { LinkedList } from 'vs/base/common/linkedList'; import { ICommandAction, ICommandActionTitle, Icon, ILocalizedString } from 'vs/platform/action/common/action'; import { CommandsRegistry, ICommandHandlerDescription, ICommandService } from 'vs/platform/commands/common/commands'; import { ContextKeyExpr, ContextKeyExpression, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { SyncDescriptor, SyncDescriptor0 } from 'vs/platform/instantiation/common/descriptors'; import { BrandedService, createDecorator, IConstructorSignature, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingRule, IKeybindings, KeybindingsRegistry } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { ThemeIcon } from 'vs/platform/theme/common/themeService'; export interface IMenuItem { command: ICommandAction; alt?: ICommandAction; when?: ContextKeyExpression; group?: 'navigation' | string; order?: number; } export interface ISubmenuItem { title: string | ICommandActionTitle; submenu: MenuId; icon?: Icon; when?: ContextKeyExpression; group?: 'navigation' | string; order?: number; rememberDefaultAction?: boolean; // for dropdown menu: if true the last executed action is remembered as the default action } export function isIMenuItem(item: any): item is IMenuItem { return (item as IMenuItem).command !== undefined; } export function isISubmenuItem(item: any): item is ISubmenuItem { return (item as ISubmenuItem).submenu !== undefined; } export class MenuId { private static readonly _instances = new Map<string, MenuId>(); static readonly CommandPalette = new MenuId('CommandPalette'); static readonly DebugBreakpointsContext = new MenuId('DebugBreakpointsContext'); static readonly DebugCallStackContext = new MenuId('DebugCallStackContext'); static readonly DebugConsoleContext = new MenuId('DebugConsoleContext'); static readonly DebugVariablesContext = new MenuId('DebugVariablesContext'); static readonly DebugWatchContext = new MenuId('DebugWatchContext'); static readonly DebugToolBar = new MenuId('DebugToolBar'); static readonly DebugToolBarStop = new MenuId('DebugToolBarStop'); static readonly EditorContext = new MenuId('EditorContext'); static readonly SimpleEditorContext = new MenuId('SimpleEditorContext'); static readonly EditorContextCopy = new MenuId('EditorContextCopy'); static readonly EditorContextPeek = new MenuId('EditorContextPeek'); static readonly EditorContextShare = new MenuId('EditorContextShare'); static readonly EditorTitle = new MenuId('EditorTitle'); static readonly EditorTitleRun = new MenuId('EditorTitleRun'); static readonly EditorTitleContext = new MenuId('EditorTitleContext'); static readonly EmptyEditorGroup = new MenuId('EmptyEditorGroup'); static readonly EmptyEditorGroupContext = new MenuId('EmptyEditorGroupContext'); static readonly ExplorerContext = new MenuId('ExplorerContext'); static readonly ExtensionContext = new MenuId('ExtensionContext'); static readonly GlobalActivity = new MenuId('GlobalActivity'); static readonly CommandCenter = new MenuId('CommandCenter'); static readonly LayoutControlMenuSubmenu = new MenuId('LayoutControlMenuSubmenu'); static readonly LayoutControlMenu = new MenuId('LayoutControlMenu'); static readonly MenubarMainMenu = new MenuId('MenubarMainMenu'); static readonly MenubarAppearanceMenu = new MenuId('MenubarAppearanceMenu'); static readonly MenubarDebugMenu = new MenuId('MenubarDebugMenu'); static readonly MenubarEditMenu = new MenuId('MenubarEditMenu'); static readonly MenubarCopy = new MenuId('MenubarCopy'); static readonly MenubarFileMenu = new MenuId('MenubarFileMenu'); static readonly MenubarGoMenu = new MenuId('MenubarGoMenu'); static readonly MenubarHelpMenu = new MenuId('MenubarHelpMenu'); static readonly MenubarLayoutMenu = new MenuId('MenubarLayoutMenu'); static readonly MenubarNewBreakpointMenu = new MenuId('MenubarNewBreakpointMenu'); static readonly MenubarPanelAlignmentMenu = new MenuId('MenubarPanelAlignmentMenu'); static readonly MenubarPanelPositionMenu = new MenuId('MenubarPanelPositionMenu'); static readonly MenubarPreferencesMenu = new MenuId('MenubarPreferencesMenu'); static readonly MenubarRecentMenu = new MenuId('MenubarRecentMenu'); static readonly MenubarSelectionMenu = new MenuId('MenubarSelectionMenu'); static readonly MenubarShare = new MenuId('MenubarShare'); static readonly MenubarSwitchEditorMenu = new MenuId('MenubarSwitchEditorMenu'); static readonly MenubarSwitchGroupMenu = new MenuId('MenubarSwitchGroupMenu'); static readonly MenubarTerminalMenu = new MenuId('MenubarTerminalMenu'); static readonly MenubarViewMenu = new MenuId('MenubarViewMenu'); static readonly MenubarHomeMenu = new MenuId('MenubarHomeMenu'); static readonly OpenEditorsContext = new MenuId('OpenEditorsContext'); static readonly ProblemsPanelContext = new MenuId('ProblemsPanelContext'); static readonly SCMChangeContext = new MenuId('SCMChangeContext'); static readonly SCMResourceContext = new MenuId('SCMResourceContext'); static readonly SCMResourceFolderContext = new MenuId('SCMResourceFolderContext'); static readonly SCMResourceGroupContext = new MenuId('SCMResourceGroupContext'); static readonly SCMSourceControl = new MenuId('SCMSourceControl'); static readonly SCMTitle = new MenuId('SCMTitle'); static readonly SearchContext = new MenuId('SearchContext'); static readonly StatusBarWindowIndicatorMenu = new MenuId('StatusBarWindowIndicatorMenu'); static readonly StatusBarRemoteIndicatorMenu = new MenuId('StatusBarRemoteIndicatorMenu'); static readonly TestItem = new MenuId('TestItem'); static readonly TestItemGutter = new MenuId('TestItemGutter'); static readonly TestPeekElement = new MenuId('TestPeekElement'); static readonly TestPeekTitle = new MenuId('TestPeekTitle'); static readonly TouchBarContext = new MenuId('TouchBarContext'); static readonly TitleBarContext = new MenuId('TitleBarContext'); static readonly TunnelContext = new MenuId('TunnelContext'); static readonly TunnelPrivacy = new MenuId('TunnelPrivacy'); static readonly TunnelProtocol = new MenuId('TunnelProtocol'); static readonly TunnelPortInline = new MenuId('TunnelInline'); static readonly TunnelTitle = new MenuId('TunnelTitle'); static readonly TunnelLocalAddressInline = new MenuId('TunnelLocalAddressInline'); static readonly TunnelOriginInline = new MenuId('TunnelOriginInline'); static readonly ViewItemContext = new MenuId('ViewItemContext'); static readonly ViewContainerTitle = new MenuId('ViewContainerTitle'); static readonly ViewContainerTitleContext = new MenuId('ViewContainerTitleContext'); static readonly ViewTitle = new MenuId('ViewTitle'); static readonly ViewTitleContext = new MenuId('ViewTitleContext'); static readonly CommentThreadTitle = new MenuId('CommentThreadTitle'); static readonly CommentThreadActions = new MenuId('CommentThreadActions'); static readonly CommentTitle = new MenuId('CommentTitle'); static readonly CommentActions = new MenuId('CommentActions'); static readonly InteractiveToolbar = new MenuId('InteractiveToolbar'); static readonly InteractiveCellTitle = new MenuId('InteractiveCellTitle'); static readonly InteractiveCellDelete = new MenuId('InteractiveCellDelete'); static readonly InteractiveCellExecute = new MenuId('InteractiveCellExecute'); static readonly InteractiveInputExecute = new MenuId('InteractiveInputExecute'); static readonly NotebookToolbar = new MenuId('NotebookToolbar'); static readonly NotebookCellTitle = new MenuId('NotebookCellTitle'); static readonly NotebookCellDelete = new MenuId('NotebookCellDelete'); static readonly NotebookCellInsert = new MenuId('NotebookCellInsert'); static readonly NotebookCellBetween = new MenuId('NotebookCellBetween'); static readonly NotebookCellListTop = new MenuId('NotebookCellTop'); static readonly NotebookCellExecute = new MenuId('NotebookCellExecute'); static readonly NotebookCellExecutePrimary = new MenuId('NotebookCellExecutePrimary'); static readonly NotebookDiffCellInputTitle = new MenuId('NotebookDiffCellInputTitle'); static readonly NotebookDiffCellMetadataTitle = new MenuId('NotebookDiffCellMetadataTitle'); static readonly NotebookDiffCellOutputsTitle = new MenuId('NotebookDiffCellOutputsTitle'); static readonly NotebookOutputToolbar = new MenuId('NotebookOutputToolbar'); static readonly NotebookEditorLayoutConfigure = new MenuId('NotebookEditorLayoutConfigure'); static readonly NotebookKernelSource = new MenuId('NotebookKernelSource'); static readonly BulkEditTitle = new MenuId('BulkEditTitle'); static readonly BulkEditContext = new MenuId('BulkEditContext'); static readonly TimelineItemContext = new MenuId('TimelineItemContext'); static readonly TimelineTitle = new MenuId('TimelineTitle'); static readonly TimelineTitleContext = new MenuId('TimelineTitleContext'); static readonly TimelineFilterSubMenu = new MenuId('TimelineFilterSubMenu'); static readonly AccountsContext = new MenuId('AccountsContext'); static readonly PanelTitle = new MenuId('PanelTitle'); static readonly AuxiliaryBarTitle = new MenuId('AuxiliaryBarTitle'); static readonly TerminalInstanceContext = new MenuId('TerminalInstanceContext'); static readonly TerminalEditorInstanceContext = new MenuId('TerminalEditorInstanceContext'); static readonly TerminalNewDropdownContext = new MenuId('TerminalNewDropdownContext'); static readonly TerminalTabContext = new MenuId('TerminalTabContext'); static readonly TerminalTabEmptyAreaContext = new MenuId('TerminalTabEmptyAreaContext'); static readonly TerminalInlineTabContext = new MenuId('TerminalInlineTabContext'); static readonly WebviewContext = new MenuId('WebviewContext'); static readonly InlineCompletionsActions = new MenuId('InlineCompletionsActions'); static readonly NewFile = new MenuId('NewFile'); static readonly MergeToolbar = new MenuId('MergeToolbar'); /** * Create or reuse a `MenuId` with the given identifier */ static for(identifier: string): MenuId { return MenuId._instances.get(identifier) ?? new MenuId(identifier); } readonly id: string; /** * Create a new `MenuId` with the unique identifier. Will throw if a menu * with the identifier already exists, use `MenuId.for(ident)` or a unique * identifier */ constructor(identifier: string) { if (MenuId._instances.has(identifier)) { throw new TypeError(`MenuId with identifier '${identifier}' already exists. Use MenuId.for(ident) or a unique identifier`); } MenuId._instances.set(identifier, this); this.id = identifier; } } export interface IMenuActionOptions { arg?: any; shouldForwardArgs?: boolean; renderShortTitle?: boolean; } export interface IMenu extends IDisposable { readonly onDidChange: Event<IMenu>; getActions(options?: IMenuActionOptions): [string, Array<MenuItemAction | SubmenuItemAction>][]; } export const IMenuService = createDecorator<IMenuService>('menuService'); export interface IMenuCreateOptions { emitEventsForSubmenuChanges?: boolean; eventDebounceDelay?: number; } export interface IMenuService { readonly _serviceBrand: undefined; /** * Create a new menu for the given menu identifier. A menu sends events when it's entries * have changed (placement, enablement, checked-state). By default it does not send events for * submenu entries. That is more expensive and must be explicitly enabled with the * `emitEventsForSubmenuChanges` flag. */ createMenu(id: MenuId, contextKeyService: IContextKeyService, options?: IMenuCreateOptions): IMenu; /** * Reset **all** menu item hidden states. */ resetHiddenStates(): void; } export type ICommandsMap = Map<string, ICommandAction>; export interface IMenuRegistryChangeEvent { has(id: MenuId): boolean; } export interface IMenuRegistry { readonly onDidChangeMenu: Event<IMenuRegistryChangeEvent>; addCommands(newCommands: Iterable<ICommandAction>): IDisposable; addCommand(userCommand: ICommandAction): IDisposable; getCommand(id: string): ICommandAction | undefined; getCommands(): ICommandsMap; appendMenuItems(items: Iterable<{ id: MenuId; item: IMenuItem | ISubmenuItem }>): IDisposable; appendMenuItem(menu: MenuId, item: IMenuItem | ISubmenuItem): IDisposable; getMenuItems(loc: MenuId): Array<IMenuItem | ISubmenuItem>; } export const MenuRegistry: IMenuRegistry = new class implements IMenuRegistry { private readonly _commands = new Map<string, ICommandAction>(); private readonly _menuItems = new Map<MenuId, LinkedList<IMenuItem | ISubmenuItem>>(); private readonly _onDidChangeMenu = new Emitter<IMenuRegistryChangeEvent>(); readonly onDidChangeMenu: Event<IMenuRegistryChangeEvent> = this._onDidChangeMenu.event; addCommand(command: ICommandAction): IDisposable { return this.addCommands(Iterable.single(command)); } private readonly _commandPaletteChangeEvent: IMenuRegistryChangeEvent = { has: id => id === MenuId.CommandPalette }; addCommands(commands: Iterable<ICommandAction>): IDisposable { for (const command of commands) { this._commands.set(command.id, command); } this._onDidChangeMenu.fire(this._commandPaletteChangeEvent); return toDisposable(() => { let didChange = false; for (const command of commands) { didChange = this._commands.delete(command.id) || didChange; } if (didChange) { this._onDidChangeMenu.fire(this._commandPaletteChangeEvent); } }); } getCommand(id: string): ICommandAction | undefined { return this._commands.get(id); } getCommands(): ICommandsMap { const map = new Map<string, ICommandAction>(); this._commands.forEach((value, key) => map.set(key, value)); return map; } appendMenuItem(id: MenuId, item: IMenuItem | ISubmenuItem): IDisposable { return this.appendMenuItems(Iterable.single({ id, item })); } appendMenuItems(items: Iterable<{ id: MenuId; item: IMenuItem | ISubmenuItem }>): IDisposable { const changedIds = new Set<MenuId>(); const toRemove = new LinkedList<Function>(); for (const { id, item } of items) { let list = this._menuItems.get(id); if (!list) { list = new LinkedList(); this._menuItems.set(id, list); } toRemove.push(list.push(item)); changedIds.add(id); } this._onDidChangeMenu.fire(changedIds); return toDisposable(() => { if (toRemove.size > 0) { for (const fn of toRemove) { fn(); } this._onDidChangeMenu.fire(changedIds); toRemove.clear(); } }); } getMenuItems(id: MenuId): Array<IMenuItem | ISubmenuItem> { let result: Array<IMenuItem | ISubmenuItem>; if (this._menuItems.has(id)) { result = [...this._menuItems.get(id)!]; } else { result = []; } if (id === MenuId.CommandPalette) { // CommandPalette is special because it shows // all commands by default this._appendImplicitItems(result); } return result; } private _appendImplicitItems(result: Array<IMenuItem | ISubmenuItem>) { const set = new Set<string>(); for (const item of result) { if (isIMenuItem(item)) { set.add(item.command.id); if (item.alt) { set.add(item.alt.id); } } } this._commands.forEach((command, id) => { if (!set.has(id)) { result.push({ command }); } }); } }; export class SubmenuItemAction extends SubmenuAction { constructor( readonly item: ISubmenuItem, readonly hideActions: MenuItemActionManageActions, private readonly _menuService: IMenuService, private readonly _contextKeyService: IContextKeyService, private readonly _options?: IMenuActionOptions ) { super(`submenuitem.${item.submenu.id}`, typeof item.title === 'string' ? item.title : item.title.value, [], 'submenu'); } override get actions(): readonly IAction[] { const result: IAction[] = []; const menu = this._menuService.createMenu(this.item.submenu, this._contextKeyService); const groups = menu.getActions(this._options); menu.dispose(); for (const [, actions] of groups) { if (actions.length > 0) { result.push(...actions); result.push(new Separator()); } } if (result.length) { result.pop(); // remove last separator } return result; } } export class MenuItemActionManageActions { constructor( readonly hideThis: IAction, readonly toggleAny: readonly IAction[][], ) { } asList(): IAction[] { let result: IAction[] = [this.hideThis]; for (const n of this.toggleAny) { result.push(new Separator()); result = result.concat(n); } return result; } } // implements IAction, does NOT extend Action, so that no one // subscribes to events of Action or modified properties export class MenuItemAction implements IAction { readonly item: ICommandAction; readonly alt: MenuItemAction | undefined; private readonly _options: IMenuActionOptions | undefined; readonly id: string; readonly label: string; readonly tooltip: string; readonly class: string | undefined; readonly enabled: boolean; readonly checked?: boolean; constructor( item: ICommandAction, alt: ICommandAction | undefined, options: IMenuActionOptions | undefined, readonly hideActions: MenuItemActionManageActions | undefined, @IContextKeyService contextKeyService: IContextKeyService, @ICommandService private _commandService: ICommandService ) { this.id = item.id; this.label = options?.renderShortTitle && item.shortTitle ? (typeof item.shortTitle === 'string' ? item.shortTitle : item.shortTitle.value) : (typeof item.title === 'string' ? item.title : item.title.value); this.tooltip = (typeof item.tooltip === 'string' ? item.tooltip : item.tooltip?.value) ?? ''; this.enabled = !item.precondition || contextKeyService.contextMatchesRules(item.precondition); this.checked = undefined; if (item.toggled) { const toggled = ((item.toggled as { condition: ContextKeyExpression }).condition ? item.toggled : { condition: item.toggled }) as { condition: ContextKeyExpression; icon?: Icon; tooltip?: string | ILocalizedString; title?: string | ILocalizedString; }; this.checked = contextKeyService.contextMatchesRules(toggled.condition); if (this.checked && toggled.tooltip) { this.tooltip = typeof toggled.tooltip === 'string' ? toggled.tooltip : toggled.tooltip.value; } if (toggled.title) { this.label = typeof toggled.title === 'string' ? toggled.title : toggled.title.value; } } this.item = item; this.alt = alt ? new MenuItemAction(alt, undefined, options, hideActions, contextKeyService, _commandService) : undefined; this._options = options; if (ThemeIcon.isThemeIcon(item.icon)) { this.class = CSSIcon.asClassName(item.icon); } } dispose(): void { // there is NOTHING to dispose and the MenuItemAction should // never have anything to dispose as it is a convenience type // to bridge into the rendering world. } run(...args: any[]): Promise<void> { let runArgs: any[] = []; if (this._options?.arg) { runArgs = [...runArgs, this._options.arg]; } if (this._options?.shouldForwardArgs) { runArgs = [...runArgs, ...args]; } return this._commandService.executeCommand(this.id, ...runArgs); } } export class SyncActionDescriptor { private readonly _descriptor: SyncDescriptor0<Action>; private readonly _id: string; private readonly _label?: string; private readonly _keybindings: IKeybindings | undefined; private readonly _keybindingContext: ContextKeyExpression | undefined; private readonly _keybindingWeight: number | undefined; public static create<Services extends BrandedService[]>(ctor: { new(id: string, label: string, ...services: Services): Action }, id: string, label: string | undefined, keybindings?: IKeybindings, keybindingContext?: ContextKeyExpression, keybindingWeight?: number ): SyncActionDescriptor { return new SyncActionDescriptor(ctor as IConstructorSignature<Action, [string, string | undefined]>, id, label, keybindings, keybindingContext, keybindingWeight); } public static from<Services extends BrandedService[]>( ctor: { new(id: string, label: string, ...services: Services): Action; readonly ID: string; readonly LABEL: string; }, keybindings?: IKeybindings, keybindingContext?: ContextKeyExpression, keybindingWeight?: number ): SyncActionDescriptor { return SyncActionDescriptor.create(ctor, ctor.ID, ctor.LABEL, keybindings, keybindingContext, keybindingWeight); } private constructor(ctor: IConstructorSignature<Action, [string, string | undefined]>, id: string, label: string | undefined, keybindings?: IKeybindings, keybindingContext?: ContextKeyExpression, keybindingWeight?: number ) { this._id = id; this._label = label; this._keybindings = keybindings; this._keybindingContext = keybindingContext; this._keybindingWeight = keybindingWeight; this._descriptor = new SyncDescriptor(ctor, [this._id, this._label]); } public get syncDescriptor(): SyncDescriptor0<Action> { return this._descriptor; } public get id(): string { return this._id; } public get label(): string | undefined { return this._label; } public get keybindings(): IKeybindings | undefined { return this._keybindings; } public get keybindingContext(): ContextKeyExpression | undefined { return this._keybindingContext; } public get keybindingWeight(): number | undefined { return this._keybindingWeight; } } //#region --- IAction2 type OneOrN<T> = T | T[]; export interface IAction2Options extends ICommandAction { /** * Shorthand to add this command to the command palette */ f1?: boolean; /** * One or many menu items. */ menu?: OneOrN<{ id: MenuId } & Omit<IMenuItem, 'command'>>; /** * One keybinding. */ keybinding?: OneOrN<Omit<IKeybindingRule, 'id'>>; /** * Metadata about this command, used for API commands or when * showing keybindings that have no other UX. */ description?: ICommandHandlerDescription; } export abstract class Action2 { constructor(readonly desc: Readonly<IAction2Options>) { } abstract run(accessor: ServicesAccessor, ...args: any[]): void; } export function registerAction2(ctor: { new(): Action2 }): IDisposable { const disposables = new DisposableStore(); const action = new ctor(); const { f1, menu, keybinding, description, ...command } = action.desc; // command disposables.add(CommandsRegistry.registerCommand({ id: command.id, handler: (accessor, ...args) => action.run(accessor, ...args), description: description, })); // menu if (Array.isArray(menu)) { disposables.add(MenuRegistry.appendMenuItems(menu.map(item => ({ id: item.id, item: { command, ...item } })))); } else if (menu) { disposables.add(MenuRegistry.appendMenuItem(menu.id, { command, ...menu })); } if (f1) { disposables.add(MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command, when: command.precondition })); disposables.add(MenuRegistry.addCommand(command)); } // keybinding if (Array.isArray(keybinding)) { for (const item of keybinding) { KeybindingsRegistry.registerKeybindingRule({ ...item, id: command.id, when: command.precondition ? ContextKeyExpr.and(command.precondition, item.when) : item.when }); } } else if (keybinding) { KeybindingsRegistry.registerKeybindingRule({ ...keybinding, id: command.id, when: command.precondition ? ContextKeyExpr.and(command.precondition, keybinding.when) : keybinding.when }); } return disposables; } //#endregion
src/vs/platform/actions/common/actions.ts
1
https://github.com/microsoft/vscode/commit/27bb32d00a7e309787e8f3cea271d67f7921dbba
[ 0.7191007733345032, 0.017189258709549904, 0.00016553513705730438, 0.00017266867507714778, 0.09829194843769073 ]
{ "id": 1, "code_window": [ "\tprivate isInactive: boolean = false;\n", "\n", "\tprivate readonly windowTitle: WindowTitle;\n", "\n", "\tprivate readonly contextMenu: IMenu;\n", "\n", "\tconstructor(\n", "\t\t@IContextMenuService private readonly contextMenuService: IContextMenuService,\n", "\t\t@IConfigurationService protected readonly configurationService: IConfigurationService,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate readonly titleContextMenu: IMenu;\n" ], "file_path": "src/vs/workbench/browser/parts/titlebar/titlebarPart.ts", "type": "replace", "edit_start_line_idx": 84 }
name: On Comment on: issue_comment: types: [created] # also make changes in ./on-label.yml jobs: main: runs-on: ubuntu-latest steps: - name: Checkout Actions uses: actions/checkout@v3 with: repository: "microsoft/vscode-github-triage-actions" path: ./actions ref: stable - name: Install Actions run: npm install --production --prefix ./actions - name: Run Commands uses: ./actions/commands with: appInsightsKey: ${{secrets.TRIAGE_ACTIONS_APP_INSIGHTS}} token: ${{secrets.VSCODE_ISSUE_TRIAGE_BOT_PAT}} config-path: commands - name: "Run Release Pipeline Labeler" uses: ./actions/release-pipeline with: token: ${{secrets.VSCODE_ISSUE_TRIAGE_BOT_PAT}} appInsightsKey: ${{secrets.TRIAGE_ACTIONS_APP_INSIGHTS}} notYetReleasedLabel: unreleased insidersReleasedLabel: insiders-released
.github/workflows/on-comment.yml
0
https://github.com/microsoft/vscode/commit/27bb32d00a7e309787e8f3cea271d67f7921dbba
[ 0.00017738602764438838, 0.0001765371416695416, 0.0001749685761751607, 0.00017689698142930865, 9.279688697461097e-7 ]
{ "id": 1, "code_window": [ "\tprivate isInactive: boolean = false;\n", "\n", "\tprivate readonly windowTitle: WindowTitle;\n", "\n", "\tprivate readonly contextMenu: IMenu;\n", "\n", "\tconstructor(\n", "\t\t@IContextMenuService private readonly contextMenuService: IContextMenuService,\n", "\t\t@IConfigurationService protected readonly configurationService: IConfigurationService,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate readonly titleContextMenu: IMenu;\n" ], "file_path": "src/vs/workbench/browser/parts/titlebar/titlebarPart.ts", "type": "replace", "edit_start_line_idx": 84 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { CancellationToken } from 'vs/base/common/cancellation'; import { Event } from 'vs/base/common/event'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { Position } from 'vs/editor/common/core/position'; import { IRange, Range } from 'vs/editor/common/core/range'; import { SelectionRangeProvider } from 'vs/editor/common/languages'; import { ILanguageConfigurationService } from 'vs/editor/common/languages/languageConfigurationRegistry'; import { IModelService } from 'vs/editor/common/services/model'; import { BracketSelectionRangeProvider } from 'vs/editor/contrib/smartSelect/browser/bracketSelections'; import { provideSelectionRanges } from 'vs/editor/contrib/smartSelect/browser/smartSelect'; import { WordSelectionRangeProvider } from 'vs/editor/contrib/smartSelect/browser/wordSelections'; import { createModelServices } from 'vs/editor/test/common/testTextModel'; import { javascriptOnEnterRules } from 'vs/editor/test/common/modes/supports/javascriptOnEnterRules'; import { LanguageFeatureRegistry } from 'vs/editor/common/languageFeatureRegistry'; import { ILanguageSelection, ILanguageService } from 'vs/editor/common/languages/language'; class StaticLanguageSelector implements ILanguageSelection { readonly onDidChange: Event<string> = Event.None; constructor(public readonly languageId: string) { } } suite('SmartSelect', () => { const OriginalBracketSelectionRangeProviderMaxDuration = BracketSelectionRangeProvider._maxDuration; suiteSetup(() => { BracketSelectionRangeProvider._maxDuration = 5000; // 5 seconds }); suiteTeardown(() => { BracketSelectionRangeProvider._maxDuration = OriginalBracketSelectionRangeProviderMaxDuration; }); const languageId = 'mockJSMode'; let disposables: DisposableStore; let modelService: IModelService; const providers = new LanguageFeatureRegistry<SelectionRangeProvider>(); setup(() => { disposables = new DisposableStore(); const instantiationService = createModelServices(disposables); modelService = instantiationService.get(IModelService); const languagConfigurationService = instantiationService.get(ILanguageConfigurationService); const languageService = instantiationService.get(ILanguageService); disposables.add(languageService.registerLanguage({ id: languageId })); disposables.add(languagConfigurationService.register(languageId, { brackets: [ ['(', ')'], ['{', '}'], ['[', ']'] ], onEnterRules: javascriptOnEnterRules, wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\@\#\$\%\^\&\*\(\)\=\+\[\{\]\}\\\;\:\'\"\,\.\<\>\/\?\s]+)/g })); }); teardown(() => { disposables.dispose(); }); async function assertGetRangesToPosition(text: string[], lineNumber: number, column: number, ranges: Range[], selectLeadingAndTrailingWhitespace = true): Promise<void> { const uri = URI.file('test.js'); const model = modelService.createModel(text.join('\n'), new StaticLanguageSelector(languageId), uri); const [actual] = await provideSelectionRanges(providers, model, [new Position(lineNumber, column)], { selectLeadingAndTrailingWhitespace }, CancellationToken.None); const actualStr = actual!.map(r => new Range(r.startLineNumber, r.startColumn, r.endLineNumber, r.endColumn).toString()); const desiredStr = ranges.reverse().map(r => String(r)); assert.deepStrictEqual(actualStr, desiredStr, `\nA: ${actualStr} VS \nE: ${desiredStr}`); modelService.destroyModel(uri); } test('getRangesToPosition #1', () => { return assertGetRangesToPosition([ 'function a(bar, foo){', '\tif (bar) {', '\t\treturn (bar + (2 * foo))', '\t}', '}' ], 3, 20, [ new Range(1, 1, 5, 2), // all new Range(1, 21, 5, 2), // {} outside new Range(1, 22, 5, 1), // {} inside new Range(2, 1, 4, 3), // block new Range(2, 1, 4, 3), new Range(2, 2, 4, 3), new Range(2, 11, 4, 3), new Range(2, 12, 4, 2), new Range(3, 1, 3, 27), // line w/ triva new Range(3, 3, 3, 27), // line w/o triva new Range(3, 10, 3, 27), // () outside new Range(3, 11, 3, 26), // () inside new Range(3, 17, 3, 26), // () outside new Range(3, 18, 3, 25), // () inside ]); }); test('config: selectLeadingAndTrailingWhitespace', async () => { await assertGetRangesToPosition([ 'aaa', '\tbbb', '' ], 2, 3, [ new Range(1, 1, 3, 1), // all new Range(2, 1, 2, 5), // line w/ triva new Range(2, 2, 2, 5), // bbb ], true); await assertGetRangesToPosition([ 'aaa', '\tbbb', '' ], 2, 3, [ new Range(1, 1, 3, 1), // all new Range(2, 2, 2, 5), // () inside ], false); }); test('getRangesToPosition #56886. Skip empty lines correctly.', () => { return assertGetRangesToPosition([ 'function a(bar, foo){', '\tif (bar) {', '', '\t}', '}' ], 3, 1, [ new Range(1, 1, 5, 2), new Range(1, 21, 5, 2), new Range(1, 22, 5, 1), new Range(2, 1, 4, 3), new Range(2, 1, 4, 3), new Range(2, 2, 4, 3), new Range(2, 11, 4, 3), new Range(2, 12, 4, 2), ]); }); test('getRangesToPosition #56886. Do not skip lines with only whitespaces.', () => { return assertGetRangesToPosition([ 'function a(bar, foo){', '\tif (bar) {', ' ', '\t}', '}' ], 3, 1, [ new Range(1, 1, 5, 2), // all new Range(1, 21, 5, 2), // {} outside new Range(1, 22, 5, 1), // {} inside new Range(2, 1, 4, 3), new Range(2, 1, 4, 3), new Range(2, 2, 4, 3), new Range(2, 11, 4, 3), new Range(2, 12, 4, 2), new Range(3, 1, 3, 2), // block new Range(3, 1, 3, 2) // empty line ]); }); test('getRangesToPosition #40658. Cursor at first position inside brackets should select line inside.', () => { return assertGetRangesToPosition([ ' [ ]', ' { } ', '( ) ' ], 2, 3, [ new Range(1, 1, 3, 5), new Range(2, 1, 2, 6), // line w/ triava new Range(2, 2, 2, 5), // {} inside, line w/o triva new Range(2, 3, 2, 4) // {} inside ]); }); test('getRangesToPosition #40658. Cursor in empty brackets should reveal brackets first.', () => { return assertGetRangesToPosition([ ' [] ', ' { } ', ' ( ) ' ], 1, 3, [ new Range(1, 1, 3, 7), // all new Range(1, 1, 1, 5), // line w/ trival new Range(1, 2, 1, 4), // [] outside, line w/o trival new Range(1, 3, 1, 3), // [] inside ]); }); test('getRangesToPosition #40658. Tokens before bracket will be revealed first.', () => { return assertGetRangesToPosition([ ' [] ', ' { } ', 'selectthis( ) ' ], 3, 11, [ new Range(1, 1, 3, 15), // all new Range(3, 1, 3, 15), // line w/ trivia new Range(3, 1, 3, 14), // line w/o trivia new Range(3, 1, 3, 11) // word ]); }); // -- bracket selections async function assertRanges(provider: SelectionRangeProvider, value: string, ...expected: IRange[]): Promise<void> { const index = value.indexOf('|'); value = value.replace('|', ''); const model = modelService.createModel(value, new StaticLanguageSelector(languageId), URI.parse('fake:lang')); const pos = model.getPositionAt(index); const all = await provider.provideSelectionRanges(model, [pos], CancellationToken.None); const ranges = all![0]; modelService.destroyModel(model.uri); assert.strictEqual(expected.length, ranges!.length); for (const range of ranges!) { const exp = expected.shift() || null; assert.ok(Range.equalsRange(range.range, exp), `A=${range.range} <> E=${exp}`); } } test('bracket selection', async () => { await assertRanges(new BracketSelectionRangeProvider(), '(|)', new Range(1, 2, 1, 2), new Range(1, 1, 1, 3) ); await assertRanges(new BracketSelectionRangeProvider(), '[[[](|)]]', new Range(1, 6, 1, 6), new Range(1, 5, 1, 7), // () new Range(1, 3, 1, 7), new Range(1, 2, 1, 8), // [[]()] new Range(1, 2, 1, 8), new Range(1, 1, 1, 9), // [[[]()]] ); await assertRanges(new BracketSelectionRangeProvider(), '[a[](|)a]', new Range(1, 6, 1, 6), new Range(1, 5, 1, 7), new Range(1, 2, 1, 8), new Range(1, 1, 1, 9), ); // no bracket await assertRanges(new BracketSelectionRangeProvider(), 'fofof|fofo'); // empty await assertRanges(new BracketSelectionRangeProvider(), '[[[]()]]|'); await assertRanges(new BracketSelectionRangeProvider(), '|[[[]()]]'); // edge await assertRanges(new BracketSelectionRangeProvider(), '[|[[]()]]', new Range(1, 2, 1, 8), new Range(1, 1, 1, 9)); await assertRanges(new BracketSelectionRangeProvider(), '[[[]()]|]', new Range(1, 2, 1, 8), new Range(1, 1, 1, 9)); await assertRanges(new BracketSelectionRangeProvider(), 'aaa(aaa)bbb(b|b)ccc(ccc)', new Range(1, 13, 1, 15), new Range(1, 12, 1, 16)); await assertRanges(new BracketSelectionRangeProvider(), '(aaa(aaa)bbb(b|b)ccc(ccc))', new Range(1, 14, 1, 16), new Range(1, 13, 1, 17), new Range(1, 2, 1, 25), new Range(1, 1, 1, 26)); }); test('bracket with leading/trailing', async () => { await assertRanges(new BracketSelectionRangeProvider(), 'for(a of b){\n foo(|);\n}', new Range(2, 7, 2, 7), new Range(2, 6, 2, 8), new Range(1, 13, 3, 1), new Range(1, 12, 3, 2), new Range(1, 1, 3, 2), new Range(1, 1, 3, 2), ); await assertRanges(new BracketSelectionRangeProvider(), 'for(a of b)\n{\n foo(|);\n}', new Range(3, 7, 3, 7), new Range(3, 6, 3, 8), new Range(2, 2, 4, 1), new Range(2, 1, 4, 2), new Range(1, 1, 4, 2), new Range(1, 1, 4, 2), ); }); test('in-word ranges', async () => { await assertRanges(new WordSelectionRangeProvider(), 'f|ooBar', new Range(1, 1, 1, 4), // foo new Range(1, 1, 1, 7), // fooBar new Range(1, 1, 1, 7), // doc ); await assertRanges(new WordSelectionRangeProvider(), 'f|oo_Ba', new Range(1, 1, 1, 4), new Range(1, 1, 1, 7), new Range(1, 1, 1, 7), ); await assertRanges(new WordSelectionRangeProvider(), 'f|oo-Ba', new Range(1, 1, 1, 4), new Range(1, 1, 1, 7), new Range(1, 1, 1, 7), ); }); test('Default selection should select current word/hump first in camelCase #67493', async function () { await assertRanges(new WordSelectionRangeProvider(), 'Abs|tractSmartSelect', new Range(1, 1, 1, 9), new Range(1, 1, 1, 20), new Range(1, 1, 1, 20), ); await assertRanges(new WordSelectionRangeProvider(), 'AbstractSma|rtSelect', new Range(1, 9, 1, 14), new Range(1, 1, 1, 20), new Range(1, 1, 1, 20), ); await assertRanges(new WordSelectionRangeProvider(), 'Abstrac-Sma|rt-elect', new Range(1, 9, 1, 14), new Range(1, 1, 1, 20), new Range(1, 1, 1, 20), ); await assertRanges(new WordSelectionRangeProvider(), 'Abstrac_Sma|rt_elect', new Range(1, 9, 1, 14), new Range(1, 1, 1, 20), new Range(1, 1, 1, 20), ); await assertRanges(new WordSelectionRangeProvider(), 'Abstrac_Sma|rt-elect', new Range(1, 9, 1, 14), new Range(1, 1, 1, 20), new Range(1, 1, 1, 20), ); await assertRanges(new WordSelectionRangeProvider(), 'Abstrac_Sma|rtSelect', new Range(1, 9, 1, 14), new Range(1, 1, 1, 20), new Range(1, 1, 1, 20), ); }); test('Smart select: only add line ranges if they\'re contained by the next range #73850', async function () { const reg = providers.register('*', { provideSelectionRanges() { return [[ { range: { startLineNumber: 1, startColumn: 10, endLineNumber: 1, endColumn: 11 } }, { range: { startLineNumber: 1, startColumn: 10, endLineNumber: 3, endColumn: 2 } }, { range: { startLineNumber: 1, startColumn: 1, endLineNumber: 3, endColumn: 2 } }, ]]; } }); await assertGetRangesToPosition(['type T = {', '\tx: number', '}'], 1, 10, [ new Range(1, 1, 3, 2), // all new Range(1, 10, 3, 2), // { ... } new Range(1, 10, 1, 11), // { ]); reg.dispose(); }); test('Expand selection in words with underscores is inconsistent #90589', async function () { await assertRanges(new WordSelectionRangeProvider(), 'Hel|lo_World', new Range(1, 1, 1, 6), new Range(1, 1, 1, 12), new Range(1, 1, 1, 12), ); await assertRanges(new WordSelectionRangeProvider(), 'Hello_Wo|rld', new Range(1, 7, 1, 12), new Range(1, 1, 1, 12), new Range(1, 1, 1, 12), ); await assertRanges(new WordSelectionRangeProvider(), 'Hello|_World', new Range(1, 1, 1, 6), new Range(1, 1, 1, 12), new Range(1, 1, 1, 12), ); await assertRanges(new WordSelectionRangeProvider(), 'Hello_|World', new Range(1, 7, 1, 12), new Range(1, 1, 1, 12), new Range(1, 1, 1, 12), ); await assertRanges(new WordSelectionRangeProvider(), 'Hello|-World', new Range(1, 1, 1, 6), new Range(1, 1, 1, 12), new Range(1, 1, 1, 12), ); await assertRanges(new WordSelectionRangeProvider(), 'Hello-|World', new Range(1, 7, 1, 12), new Range(1, 1, 1, 12), new Range(1, 1, 1, 12), ); await assertRanges(new WordSelectionRangeProvider(), 'Hello|World', new Range(1, 6, 1, 11), new Range(1, 1, 1, 11), new Range(1, 1, 1, 11), ); }); });
src/vs/editor/contrib/smartSelect/test/browser/smartSelect.test.ts
0
https://github.com/microsoft/vscode/commit/27bb32d00a7e309787e8f3cea271d67f7921dbba
[ 0.0002685084182303399, 0.00017661521269474179, 0.00016749869973864406, 0.00017473299521952868, 0.000014747284694749396 ]
{ "id": 1, "code_window": [ "\tprivate isInactive: boolean = false;\n", "\n", "\tprivate readonly windowTitle: WindowTitle;\n", "\n", "\tprivate readonly contextMenu: IMenu;\n", "\n", "\tconstructor(\n", "\t\t@IContextMenuService private readonly contextMenuService: IContextMenuService,\n", "\t\t@IConfigurationService protected readonly configurationService: IConfigurationService,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate readonly titleContextMenu: IMenu;\n" ], "file_path": "src/vs/workbench/browser/parts/titlebar/titlebarPart.ts", "type": "replace", "edit_start_line_idx": 84 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { ConfigurationChangedEvent, EditorAutoClosingEditStrategy, EditorAutoClosingStrategy, EditorAutoIndentStrategy, EditorAutoSurroundStrategy, EditorOption } from 'vs/editor/common/config/editorOptions'; import { LineTokens } from 'vs/editor/common/tokens/lineTokens'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { ISelection, Selection } from 'vs/editor/common/core/selection'; import { ICommand } from 'vs/editor/common/editorCommon'; import { IEditorConfiguration } from 'vs/editor/common/config/editorConfiguration'; import { PositionAffinity, TextModelResolvedOptions } from 'vs/editor/common/model'; import { AutoClosingPairs } from 'vs/editor/common/languages/languageConfiguration'; import { ILanguageConfigurationService } from 'vs/editor/common/languages/languageConfigurationRegistry'; import { createScopedLineTokens } from 'vs/editor/common/languages/supports'; import { IElectricAction } from 'vs/editor/common/languages/supports/electricCharacter'; import { CursorColumns } from 'vs/editor/common/core/cursorColumns'; import { normalizeIndentation } from 'vs/editor/common/core/indentation'; export interface IColumnSelectData { isReal: boolean; fromViewLineNumber: number; fromViewVisualColumn: number; toViewLineNumber: number; toViewVisualColumn: number; } export const enum RevealTarget { Primary = 0, TopMost = 1, BottomMost = 2 } /** * This is an operation type that will be recorded for undo/redo purposes. * The goal is to introduce an undo stop when the controller switches between different operation types. */ export const enum EditOperationType { Other = 0, DeletingLeft = 2, DeletingRight = 3, TypingOther = 4, TypingFirstSpace = 5, TypingConsecutiveSpace = 6, } export interface CharacterMap { [char: string]: string; } export interface MultipleCharacterMap { [char: string]: string[]; } const autoCloseAlways = () => true; const autoCloseNever = () => false; const autoCloseBeforeWhitespace = (chr: string) => (chr === ' ' || chr === '\t'); export class CursorConfiguration { _cursorMoveConfigurationBrand: void = undefined; public readonly readOnly: boolean; public readonly tabSize: number; public readonly indentSize: number; public readonly insertSpaces: boolean; public readonly stickyTabStops: boolean; public readonly pageSize: number; public readonly lineHeight: number; public readonly useTabStops: boolean; public readonly wordSeparators: string; public readonly emptySelectionClipboard: boolean; public readonly copyWithSyntaxHighlighting: boolean; public readonly multiCursorMergeOverlapping: boolean; public readonly multiCursorPaste: 'spread' | 'full'; public readonly autoClosingBrackets: EditorAutoClosingStrategy; public readonly autoClosingQuotes: EditorAutoClosingStrategy; public readonly autoClosingDelete: EditorAutoClosingEditStrategy; public readonly autoClosingOvertype: EditorAutoClosingEditStrategy; public readonly autoSurround: EditorAutoSurroundStrategy; public readonly autoIndent: EditorAutoIndentStrategy; public readonly autoClosingPairs: AutoClosingPairs; public readonly surroundingPairs: CharacterMap; public readonly shouldAutoCloseBefore: { quote: (ch: string) => boolean; bracket: (ch: string) => boolean }; private readonly _languageId: string; private _electricChars: { [key: string]: boolean } | null; public static shouldRecreate(e: ConfigurationChangedEvent): boolean { return ( e.hasChanged(EditorOption.layoutInfo) || e.hasChanged(EditorOption.wordSeparators) || e.hasChanged(EditorOption.emptySelectionClipboard) || e.hasChanged(EditorOption.multiCursorMergeOverlapping) || e.hasChanged(EditorOption.multiCursorPaste) || e.hasChanged(EditorOption.autoClosingBrackets) || e.hasChanged(EditorOption.autoClosingQuotes) || e.hasChanged(EditorOption.autoClosingDelete) || e.hasChanged(EditorOption.autoClosingOvertype) || e.hasChanged(EditorOption.autoSurround) || e.hasChanged(EditorOption.useTabStops) || e.hasChanged(EditorOption.lineHeight) || e.hasChanged(EditorOption.readOnly) ); } constructor( languageId: string, modelOptions: TextModelResolvedOptions, configuration: IEditorConfiguration, public readonly languageConfigurationService: ILanguageConfigurationService ) { this._languageId = languageId; const options = configuration.options; const layoutInfo = options.get(EditorOption.layoutInfo); this.readOnly = options.get(EditorOption.readOnly); this.tabSize = modelOptions.tabSize; this.indentSize = modelOptions.indentSize; this.insertSpaces = modelOptions.insertSpaces; this.stickyTabStops = options.get(EditorOption.stickyTabStops); this.lineHeight = options.get(EditorOption.lineHeight); this.pageSize = Math.max(1, Math.floor(layoutInfo.height / this.lineHeight) - 2); this.useTabStops = options.get(EditorOption.useTabStops); this.wordSeparators = options.get(EditorOption.wordSeparators); this.emptySelectionClipboard = options.get(EditorOption.emptySelectionClipboard); this.copyWithSyntaxHighlighting = options.get(EditorOption.copyWithSyntaxHighlighting); this.multiCursorMergeOverlapping = options.get(EditorOption.multiCursorMergeOverlapping); this.multiCursorPaste = options.get(EditorOption.multiCursorPaste); this.autoClosingBrackets = options.get(EditorOption.autoClosingBrackets); this.autoClosingQuotes = options.get(EditorOption.autoClosingQuotes); this.autoClosingDelete = options.get(EditorOption.autoClosingDelete); this.autoClosingOvertype = options.get(EditorOption.autoClosingOvertype); this.autoSurround = options.get(EditorOption.autoSurround); this.autoIndent = options.get(EditorOption.autoIndent); this.surroundingPairs = {}; this._electricChars = null; this.shouldAutoCloseBefore = { quote: this._getShouldAutoClose(languageId, this.autoClosingQuotes), bracket: this._getShouldAutoClose(languageId, this.autoClosingBrackets) }; this.autoClosingPairs = this.languageConfigurationService.getLanguageConfiguration(languageId).getAutoClosingPairs(); const surroundingPairs = this.languageConfigurationService.getLanguageConfiguration(languageId).getSurroundingPairs(); if (surroundingPairs) { for (const pair of surroundingPairs) { this.surroundingPairs[pair.open] = pair.close; } } } public get electricChars() { if (!this._electricChars) { this._electricChars = {}; const electricChars = this.languageConfigurationService.getLanguageConfiguration(this._languageId).electricCharacter?.getElectricCharacters(); if (electricChars) { for (const char of electricChars) { this._electricChars[char] = true; } } } return this._electricChars; } /** * Should return opening bracket type to match indentation with */ public onElectricCharacter(character: string, context: LineTokens, column: number): IElectricAction | null { const scopedLineTokens = createScopedLineTokens(context, column - 1); const electricCharacterSupport = this.languageConfigurationService.getLanguageConfiguration(scopedLineTokens.languageId).electricCharacter; if (!electricCharacterSupport) { return null; } return electricCharacterSupport.onElectricCharacter(character, scopedLineTokens, column - scopedLineTokens.firstCharOffset); } public normalizeIndentation(str: string): string { return normalizeIndentation(str, this.indentSize, this.insertSpaces); } private _getShouldAutoClose(languageId: string, autoCloseConfig: EditorAutoClosingStrategy): (ch: string) => boolean { switch (autoCloseConfig) { case 'beforeWhitespace': return autoCloseBeforeWhitespace; case 'languageDefined': return this._getLanguageDefinedShouldAutoClose(languageId); case 'always': return autoCloseAlways; case 'never': return autoCloseNever; } } private _getLanguageDefinedShouldAutoClose(languageId: string): (ch: string) => boolean { const autoCloseBeforeSet = this.languageConfigurationService.getLanguageConfiguration(languageId).getAutoCloseBeforeSet(); return c => autoCloseBeforeSet.indexOf(c) !== -1; } /** * Returns a visible column from a column. * @see {@link CursorColumns} */ public visibleColumnFromColumn(model: ICursorSimpleModel, position: Position): number { return CursorColumns.visibleColumnFromColumn(model.getLineContent(position.lineNumber), position.column, this.tabSize); } /** * Returns a visible column from a column. * @see {@link CursorColumns} */ public columnFromVisibleColumn(model: ICursorSimpleModel, lineNumber: number, visibleColumn: number): number { const result = CursorColumns.columnFromVisibleColumn(model.getLineContent(lineNumber), visibleColumn, this.tabSize); const minColumn = model.getLineMinColumn(lineNumber); if (result < minColumn) { return minColumn; } const maxColumn = model.getLineMaxColumn(lineNumber); if (result > maxColumn) { return maxColumn; } return result; } } /** * Represents a simple model (either the model or the view model). */ export interface ICursorSimpleModel { getLineCount(): number; getLineContent(lineNumber: number): string; getLineMinColumn(lineNumber: number): number; getLineMaxColumn(lineNumber: number): number; getLineFirstNonWhitespaceColumn(lineNumber: number): number; getLineLastNonWhitespaceColumn(lineNumber: number): number; normalizePosition(position: Position, affinity: PositionAffinity): Position; /** * Gets the column at which indentation stops at a given line. * @internal */ getLineIndentColumn(lineNumber: number): number; } export type PartialCursorState = CursorState | PartialModelCursorState | PartialViewCursorState; export class CursorState { _cursorStateBrand: void = undefined; public static fromModelState(modelState: SingleCursorState): PartialModelCursorState { return new PartialModelCursorState(modelState); } public static fromViewState(viewState: SingleCursorState): PartialViewCursorState { return new PartialViewCursorState(viewState); } public static fromModelSelection(modelSelection: ISelection): PartialModelCursorState { const selection = Selection.liftSelection(modelSelection); const modelState = new SingleCursorState( Range.fromPositions(selection.getSelectionStart()), 0, selection.getPosition(), 0 ); return CursorState.fromModelState(modelState); } public static fromModelSelections(modelSelections: readonly ISelection[]): PartialModelCursorState[] { const states: PartialModelCursorState[] = []; for (let i = 0, len = modelSelections.length; i < len; i++) { states[i] = this.fromModelSelection(modelSelections[i]); } return states; } readonly modelState: SingleCursorState; readonly viewState: SingleCursorState; constructor(modelState: SingleCursorState, viewState: SingleCursorState) { this.modelState = modelState; this.viewState = viewState; } public equals(other: CursorState): boolean { return (this.viewState.equals(other.viewState) && this.modelState.equals(other.modelState)); } } export class PartialModelCursorState { readonly modelState: SingleCursorState; readonly viewState: null; constructor(modelState: SingleCursorState) { this.modelState = modelState; this.viewState = null; } } export class PartialViewCursorState { readonly modelState: null; readonly viewState: SingleCursorState; constructor(viewState: SingleCursorState) { this.modelState = null; this.viewState = viewState; } } /** * Represents the cursor state on either the model or on the view model. */ export class SingleCursorState { _singleCursorStateBrand: void = undefined; // --- selection can start as a range (think double click and drag) public readonly selectionStart: Range; public readonly selectionStartLeftoverVisibleColumns: number; public readonly position: Position; public readonly leftoverVisibleColumns: number; public readonly selection: Selection; constructor( selectionStart: Range, selectionStartLeftoverVisibleColumns: number, position: Position, leftoverVisibleColumns: number, ) { this.selectionStart = selectionStart; this.selectionStartLeftoverVisibleColumns = selectionStartLeftoverVisibleColumns; this.position = position; this.leftoverVisibleColumns = leftoverVisibleColumns; this.selection = SingleCursorState._computeSelection(this.selectionStart, this.position); } public equals(other: SingleCursorState) { return ( this.selectionStartLeftoverVisibleColumns === other.selectionStartLeftoverVisibleColumns && this.leftoverVisibleColumns === other.leftoverVisibleColumns && this.position.equals(other.position) && this.selectionStart.equalsRange(other.selectionStart) ); } public hasSelection(): boolean { return (!this.selection.isEmpty() || !this.selectionStart.isEmpty()); } public move(inSelectionMode: boolean, lineNumber: number, column: number, leftoverVisibleColumns: number): SingleCursorState { if (inSelectionMode) { // move just position return new SingleCursorState( this.selectionStart, this.selectionStartLeftoverVisibleColumns, new Position(lineNumber, column), leftoverVisibleColumns ); } else { // move everything return new SingleCursorState( new Range(lineNumber, column, lineNumber, column), leftoverVisibleColumns, new Position(lineNumber, column), leftoverVisibleColumns ); } } private static _computeSelection(selectionStart: Range, position: Position): Selection { if (selectionStart.isEmpty() || !position.isBeforeOrEqual(selectionStart.getStartPosition())) { return Selection.fromPositions(selectionStart.getStartPosition(), position); } else { return Selection.fromPositions(selectionStart.getEndPosition(), position); } } } export class EditOperationResult { _editOperationResultBrand: void = undefined; readonly type: EditOperationType; readonly commands: Array<ICommand | null>; readonly shouldPushStackElementBefore: boolean; readonly shouldPushStackElementAfter: boolean; constructor( type: EditOperationType, commands: Array<ICommand | null>, opts: { shouldPushStackElementBefore: boolean; shouldPushStackElementAfter: boolean; } ) { this.type = type; this.commands = commands; this.shouldPushStackElementBefore = opts.shouldPushStackElementBefore; this.shouldPushStackElementAfter = opts.shouldPushStackElementAfter; } } export function isQuote(ch: string): boolean { return (ch === '\'' || ch === '"' || ch === '`'); }
src/vs/editor/common/cursorCommon.ts
0
https://github.com/microsoft/vscode/commit/27bb32d00a7e309787e8f3cea271d67f7921dbba
[ 0.0009236152400262654, 0.0001945479743881151, 0.00016624615818727762, 0.0001733040262479335, 0.00011713794083334506 ]
{ "id": 2, "code_window": [ "\t) {\n", "\t\tsuper(Parts.TITLEBAR_PART, { hasTitle: false }, themeService, storageService, layoutService);\n", "\t\tthis.windowTitle = this._register(instantiationService.createInstance(WindowTitle));\n", "\t\tthis.contextMenu = this._register(menuService.createMenu(MenuId.TitleBarContext, contextKeyService));\n", "\n", "\t\tthis.titleBarStyle = getTitleBarStyle(this.configurationService);\n", "\n", "\t\tthis.hoverDelegate = new class implements IHoverDelegate {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.titleContextMenu = this._register(menuService.createMenu(MenuId.TitleBarTitleContext, contextKeyService));\n" ], "file_path": "src/vs/workbench/browser/parts/titlebar/titlebarPart.ts", "type": "replace", "edit_start_line_idx": 101 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./media/titlebarpart'; import { localize } from 'vs/nls'; import { Part } from 'vs/workbench/browser/part'; import { ITitleService, ITitleProperties } from 'vs/workbench/services/title/common/titleService'; import { getZoomFactor } from 'vs/base/browser/browser'; import { MenuBarVisibility, getTitleBarStyle, getMenuBarVisibility } from 'vs/platform/window/common/window'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import { IAction, toAction } from 'vs/base/common/actions'; import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration'; import { DisposableStore, dispose } from 'vs/base/common/lifecycle'; import { IBrowserWorkbenchEnvironmentService } from 'vs/workbench/services/environment/browser/environmentService'; import { IThemeService, registerThemingParticipant, ThemeIcon } from 'vs/platform/theme/common/themeService'; import { TITLE_BAR_ACTIVE_BACKGROUND, TITLE_BAR_ACTIVE_FOREGROUND, TITLE_BAR_INACTIVE_FOREGROUND, TITLE_BAR_INACTIVE_BACKGROUND, TITLE_BAR_BORDER, WORKBENCH_BACKGROUND } from 'vs/workbench/common/theme'; import { isMacintosh, isWindows, isLinux, isWeb } from 'vs/base/common/platform'; import { Color } from 'vs/base/common/color'; import { EventType, EventHelper, Dimension, isAncestor, append, $, addDisposableListener, runAtThisOrScheduleAtNextAnimationFrame, prepend, reset } from 'vs/base/browser/dom'; import { CustomMenubarControl } from 'vs/workbench/browser/parts/titlebar/menubarControl'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { Emitter, Event } from 'vs/base/common/event'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { Parts, IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService'; import { createActionViewItem, createAndFillInContextMenuActions } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { IMenuService, IMenu, MenuId } from 'vs/platform/actions/common/actions'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IHostService } from 'vs/workbench/services/host/browser/host'; import { Codicon } from 'vs/base/common/codicons'; import { getIconRegistry } from 'vs/platform/theme/common/iconRegistry'; import { ToolBar } from 'vs/base/browser/ui/toolbar/toolbar'; import { WindowTitle } from 'vs/workbench/browser/parts/titlebar/windowTitle'; import { CommandCenterControl } from 'vs/workbench/browser/parts/titlebar/commandCenterControl'; import { IHoverDelegate } from 'vs/base/browser/ui/iconLabel/iconHoverDelegate'; import { IHoverService } from 'vs/workbench/services/hover/browser/hover'; export class TitlebarPart extends Part implements ITitleService { private static readonly configCommandCenter = 'window.commandCenter'; declare readonly _serviceBrand: undefined; //#region IView readonly minimumWidth: number = 0; readonly maximumWidth: number = Number.POSITIVE_INFINITY; get minimumHeight(): number { const value = this.isCommandCenterVisible ? 35 : 30; return value / (this.currentMenubarVisibility === 'hidden' || getZoomFactor() < 1 ? getZoomFactor() : 1); } get maximumHeight(): number { return this.minimumHeight; } //#endregion private _onMenubarVisibilityChange = this._register(new Emitter<boolean>()); readonly onMenubarVisibilityChange = this._onMenubarVisibilityChange.event; private readonly _onDidChangeCommandCenterVisibility = new Emitter<void>(); readonly onDidChangeCommandCenterVisibility: Event<void> = this._onDidChangeCommandCenterVisibility.event; protected rootContainer!: HTMLElement; protected windowControls: HTMLElement | undefined; protected title!: HTMLElement; protected customMenubar: CustomMenubarControl | undefined; protected appIcon: HTMLElement | undefined; private appIconBadge: HTMLElement | undefined; protected menubar?: HTMLElement; protected layoutControls: HTMLElement | undefined; private layoutToolbar: ToolBar | undefined; protected lastLayoutDimensions: Dimension | undefined; private hoverDelegate: IHoverDelegate; private readonly titleDisposables = this._register(new DisposableStore()); private titleBarStyle: 'native' | 'custom'; private isInactive: boolean = false; private readonly windowTitle: WindowTitle; private readonly contextMenu: IMenu; constructor( @IContextMenuService private readonly contextMenuService: IContextMenuService, @IConfigurationService protected readonly configurationService: IConfigurationService, @IBrowserWorkbenchEnvironmentService protected readonly environmentService: IBrowserWorkbenchEnvironmentService, @IInstantiationService protected readonly instantiationService: IInstantiationService, @IThemeService themeService: IThemeService, @IStorageService storageService: IStorageService, @IWorkbenchLayoutService layoutService: IWorkbenchLayoutService, @IMenuService private readonly menuService: IMenuService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IHostService private readonly hostService: IHostService, @IHoverService hoverService: IHoverService, ) { super(Parts.TITLEBAR_PART, { hasTitle: false }, themeService, storageService, layoutService); this.windowTitle = this._register(instantiationService.createInstance(WindowTitle)); this.contextMenu = this._register(menuService.createMenu(MenuId.TitleBarContext, contextKeyService)); this.titleBarStyle = getTitleBarStyle(this.configurationService); this.hoverDelegate = new class implements IHoverDelegate { private _lastHoverHideTime: number = 0; readonly showHover = hoverService.showHover.bind(hoverService); readonly placement = 'element'; get delay(): number { return Date.now() - this._lastHoverHideTime < 200 ? 0 // show instantly when a hover was recently shown : configurationService.getValue<number>('workbench.hover.delay'); } onDidHideHover() { this._lastHoverHideTime = Date.now(); } }; this.registerListeners(); } updateProperties(properties: ITitleProperties): void { this.windowTitle.updateProperties(properties); } get isCommandCenterVisible() { return this.configurationService.getValue<boolean>(TitlebarPart.configCommandCenter); } private registerListeners(): void { this._register(this.hostService.onDidChangeFocus(focused => focused ? this.onFocus() : this.onBlur())); this._register(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationChanged(e))); } private onBlur(): void { this.isInactive = true; this.updateStyles(); } private onFocus(): void { this.isInactive = false; this.updateStyles(); } protected onConfigurationChanged(event: IConfigurationChangeEvent): void { if (this.titleBarStyle !== 'native' && (!isMacintosh || isWeb)) { if (event.affectsConfiguration('window.menuBarVisibility')) { if (this.currentMenubarVisibility === 'compact') { this.uninstallMenubar(); } else { this.installMenubar(); } } } if (this.titleBarStyle !== 'native' && this.layoutControls && event.affectsConfiguration('workbench.layoutControl.enabled')) { this.layoutControls.classList.toggle('show-layout-control', this.layoutControlEnabled); } if (event.affectsConfiguration(TitlebarPart.configCommandCenter)) { this.updateTitle(); this.adjustTitleMarginToCenter(); this._onDidChangeCommandCenterVisibility.fire(); } } protected onMenubarVisibilityChanged(visible: boolean): void { if (isWeb || isWindows || isLinux) { if (this.lastLayoutDimensions) { this.layout(this.lastLayoutDimensions.width, this.lastLayoutDimensions.height); } this._onMenubarVisibilityChange.fire(visible); } } private uninstallMenubar(): void { if (this.customMenubar) { this.customMenubar.dispose(); this.customMenubar = undefined; } if (this.menubar) { this.menubar.remove(); this.menubar = undefined; } this.onMenubarVisibilityChanged(false); } protected installMenubar(): void { // If the menubar is already installed, skip if (this.menubar) { return; } this.customMenubar = this._register(this.instantiationService.createInstance(CustomMenubarControl)); this.menubar = this.rootContainer.insertBefore($('div.menubar'), this.title); this.menubar.setAttribute('role', 'menubar'); this._register(this.customMenubar.onVisibilityChange(e => this.onMenubarVisibilityChanged(e))); this.customMenubar.create(this.menubar); } private updateTitle(): void { this.titleDisposables.clear(); if (!this.isCommandCenterVisible) { // Text Title this.title.innerText = this.windowTitle.value; this.titleDisposables.add(this.windowTitle.onDidChange(() => { this.title.innerText = this.windowTitle.value; this.adjustTitleMarginToCenter(); })); } else { // Menu Title const commandCenter = this.instantiationService.createInstance(CommandCenterControl, this.windowTitle, this.hoverDelegate); reset(this.title, commandCenter.element); this.titleDisposables.add(commandCenter); this.titleDisposables.add(commandCenter.onDidChangeVisibility(this.adjustTitleMarginToCenter, this)); } } override createContentArea(parent: HTMLElement): HTMLElement { this.element = parent; this.rootContainer = append(parent, $('.titlebar-container')); // App Icon (Native Windows/Linux and Web) if (!isMacintosh || isWeb) { this.appIcon = prepend(this.rootContainer, $('a.window-appicon')); // Web-only home indicator and menu if (isWeb) { const homeIndicator = this.environmentService.options?.homeIndicator; if (homeIndicator) { const icon: ThemeIcon = getIconRegistry().getIcon(homeIndicator.icon) ? { id: homeIndicator.icon } : Codicon.code; this.appIcon.setAttribute('href', homeIndicator.href); this.appIcon.classList.add(...ThemeIcon.asClassNameArray(icon)); this.appIconBadge = document.createElement('div'); this.appIconBadge.classList.add('home-bar-icon-badge'); this.appIcon.appendChild(this.appIconBadge); } } } // Menubar: install a custom menu bar depending on configuration // and when not in activity bar if (this.titleBarStyle !== 'native' && (!isMacintosh || isWeb) && this.currentMenubarVisibility !== 'compact') { this.installMenubar(); } // Title this.title = append(this.rootContainer, $('div.window-title')); this.updateTitle(); if (this.titleBarStyle !== 'native') { this.layoutControls = append(this.rootContainer, $('div.layout-controls-container')); this.layoutControls.classList.toggle('show-layout-control', this.layoutControlEnabled); this.layoutToolbar = new ToolBar(this.layoutControls, this.contextMenuService, { actionViewItemProvider: action => { return createActionViewItem(this.instantiationService, action, { hoverDelegate: this.hoverDelegate }); }, allowContextMenu: true }); this._register(addDisposableListener(this.layoutControls, EventType.CONTEXT_MENU, e => { EventHelper.stop(e); this.onLayoutControlContextMenu(e, this.layoutControls!); })); const menu = this._register(this.menuService.createMenu(MenuId.LayoutControlMenu, this.contextKeyService)); const updateLayoutMenu = () => { if (!this.layoutToolbar) { return; } const actions: IAction[] = []; const toDispose = createAndFillInContextMenuActions(menu, undefined, { primary: [], secondary: actions }); this.layoutToolbar.setActions(actions); toDispose.dispose(); }; menu.onDidChange(updateLayoutMenu); updateLayoutMenu(); } this.windowControls = append(this.element, $('div.window-controls-container')); // Context menu on title [EventType.CONTEXT_MENU, EventType.MOUSE_DOWN].forEach(event => { this._register(addDisposableListener(this.title, event, e => { if (e.type === EventType.CONTEXT_MENU || e.metaKey) { EventHelper.stop(e); this.onContextMenu(e); } })); }); // Since the title area is used to drag the window, we do not want to steal focus from the // currently active element. So we restore focus after a timeout back to where it was. this._register(addDisposableListener(this.element, EventType.MOUSE_DOWN, e => { if (e.target && this.menubar && isAncestor(e.target as HTMLElement, this.menubar)) { return; } if (e.target && this.layoutToolbar && isAncestor(e.target as HTMLElement, this.layoutToolbar.getElement())) { return; } if (e.target && isAncestor(e.target as HTMLElement, this.title)) { return; } const active = document.activeElement; setTimeout(() => { if (active instanceof HTMLElement) { active.focus(); } }, 0 /* need a timeout because we are in capture phase */); }, true /* use capture to know the currently active element properly */)); this.updateStyles(); return this.element; } override updateStyles(): void { super.updateStyles(); // Part container if (this.element) { if (this.isInactive) { this.element.classList.add('inactive'); } else { this.element.classList.remove('inactive'); } const titleBackground = this.getColor(this.isInactive ? TITLE_BAR_INACTIVE_BACKGROUND : TITLE_BAR_ACTIVE_BACKGROUND, (color, theme) => { // LCD Rendering Support: the title bar part is a defining its own GPU layer. // To benefit from LCD font rendering, we must ensure that we always set an // opaque background color. As such, we compute an opaque color given we know // the background color is the workbench background. return color.isOpaque() ? color : color.makeOpaque(WORKBENCH_BACKGROUND(theme)); }) || ''; this.element.style.backgroundColor = titleBackground; if (this.appIconBadge) { this.appIconBadge.style.backgroundColor = titleBackground; } if (titleBackground && Color.fromHex(titleBackground).isLighter()) { this.element.classList.add('light'); } else { this.element.classList.remove('light'); } const titleForeground = this.getColor(this.isInactive ? TITLE_BAR_INACTIVE_FOREGROUND : TITLE_BAR_ACTIVE_FOREGROUND); this.element.style.color = titleForeground || ''; const titleBorder = this.getColor(TITLE_BAR_BORDER); this.element.style.borderBottom = titleBorder ? `1px solid ${titleBorder}` : ''; } } private onContextMenu(e: MouseEvent): void { // Find target anchor const event = new StandardMouseEvent(e); const anchor = { x: event.posx, y: event.posy }; // Fill in contributed actions const actions: IAction[] = []; const actionsDisposable = createAndFillInContextMenuActions(this.contextMenu, undefined, actions); // Show it this.contextMenuService.showContextMenu({ getAnchor: () => anchor, getActions: () => actions, onHide: () => dispose(actionsDisposable) }); } private onLayoutControlContextMenu(e: MouseEvent, el: HTMLElement): void { // Find target anchor const event = new StandardMouseEvent(e); const anchor = { x: event.posx, y: event.posy }; const actions: IAction[] = []; actions.push(toAction({ id: 'layoutControl.hide', label: localize('layoutControl.hide', "Hide Layout Control"), run: () => { this.configurationService.updateValue('workbench.layoutControl.enabled', false); } })); // Show it this.contextMenuService.showContextMenu({ getAnchor: () => anchor, getActions: () => actions, domForShadowRoot: el }); } protected adjustTitleMarginToCenter(): void { const base = isMacintosh ? (this.windowControls?.clientWidth ?? 0) : 0; const leftMarker = base + (this.appIcon?.clientWidth ?? 0) + (this.menubar?.clientWidth ?? 0) + 10; const rightMarker = base + this.rootContainer.clientWidth - (this.layoutControls?.clientWidth ?? 0) - 10; // Not enough space to center the titlebar within window, // Center between left and right controls if (leftMarker > (this.rootContainer.clientWidth + (this.windowControls?.clientWidth ?? 0) - this.title.clientWidth) / 2 || rightMarker < (this.rootContainer.clientWidth + (this.windowControls?.clientWidth ?? 0) + this.title.clientWidth) / 2) { this.title.style.position = ''; this.title.style.left = ''; this.title.style.transform = ''; return; } this.title.style.position = 'absolute'; this.title.style.left = `calc(50% - ${this.title.clientWidth / 2}px)`; } protected get currentMenubarVisibility(): MenuBarVisibility { return getMenuBarVisibility(this.configurationService); } private get layoutControlEnabled(): boolean { return this.configurationService.getValue<boolean>('workbench.layoutControl.enabled'); } updateLayout(dimension: Dimension): void { this.lastLayoutDimensions = dimension; if (getTitleBarStyle(this.configurationService) === 'custom') { // Prevent zooming behavior if any of the following conditions are met: // 1. Native macOS // 2. Menubar is hidden // 3. Shrinking below the window control size (zoom < 1) const zoomFactor = getZoomFactor(); this.element.style.setProperty('--zoom-factor', zoomFactor.toString()); this.rootContainer.classList.toggle('counter-zoom', zoomFactor < 1 || (!isWeb && isMacintosh) || this.currentMenubarVisibility === 'hidden'); runAtThisOrScheduleAtNextAnimationFrame(() => this.adjustTitleMarginToCenter()); if (this.customMenubar) { const menubarDimension = new Dimension(0, dimension.height); this.customMenubar.layout(menubarDimension); } } } override layout(width: number, height: number): void { this.updateLayout(new Dimension(width, height)); super.layoutContents(width, height); } toJSON(): object { return { type: Parts.TITLEBAR_PART }; } } registerThemingParticipant((theme, collector) => { const titlebarActiveFg = theme.getColor(TITLE_BAR_ACTIVE_FOREGROUND); if (titlebarActiveFg) { collector.addRule(` .monaco-workbench .part.titlebar .window-controls-container .window-icon { color: ${titlebarActiveFg}; } `); } const titlebarInactiveFg = theme.getColor(TITLE_BAR_INACTIVE_FOREGROUND); if (titlebarInactiveFg) { collector.addRule(` .monaco-workbench .part.titlebar.inactive .window-controls-container .window-icon { color: ${titlebarInactiveFg}; } `); } });
src/vs/workbench/browser/parts/titlebar/titlebarPart.ts
1
https://github.com/microsoft/vscode/commit/27bb32d00a7e309787e8f3cea271d67f7921dbba
[ 0.9976382255554199, 0.02299853228032589, 0.00016434364079032093, 0.0002742448996286839, 0.1380685716867447 ]
{ "id": 2, "code_window": [ "\t) {\n", "\t\tsuper(Parts.TITLEBAR_PART, { hasTitle: false }, themeService, storageService, layoutService);\n", "\t\tthis.windowTitle = this._register(instantiationService.createInstance(WindowTitle));\n", "\t\tthis.contextMenu = this._register(menuService.createMenu(MenuId.TitleBarContext, contextKeyService));\n", "\n", "\t\tthis.titleBarStyle = getTitleBarStyle(this.configurationService);\n", "\n", "\t\tthis.hoverDelegate = new class implements IHoverDelegate {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.titleContextMenu = this._register(menuService.createMenu(MenuId.TitleBarTitleContext, contextKeyService));\n" ], "file_path": "src/vs/workbench/browser/parts/titlebar/titlebarPart.ts", "type": "replace", "edit_start_line_idx": 101 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { URI } from 'vs/base/common/uri'; import { IResolvedNotebookEditorModel } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { IReference } from 'vs/base/common/lifecycle'; import { Event, IWaitUntil } from 'vs/base/common/event'; export const INotebookEditorModelResolverService = createDecorator<INotebookEditorModelResolverService>('INotebookModelResolverService'); /** * A notebook file can only be opened ONCE per notebook type. * This event fires when a file is already open as type A * and there is request to open it as type B. Listeners must * do cleanup (close editor, release references) or the request fails */ export interface INotebookConflictEvent extends IWaitUntil { resource: URI; viewType: string; } export interface IUntitledNotebookResource { /** * Depending on the value of `untitledResource` will * resolve a untitled notebook that: * - gets a unique name if `undefined` (e.g. `Untitled-1') * - uses the resource directly if the scheme is `untitled:` * - converts any other resource scheme to `untitled:` and will * assume an associated file path * * Untitled notebook editors with associated path behave slightly * different from other untitled editors: * - they are dirty right when opening * - they will not ask for a file path when saving but use the associated path */ untitledResource: URI | undefined; } export interface INotebookEditorModelResolverService { readonly _serviceBrand: undefined; readonly onDidSaveNotebook: Event<URI>; readonly onDidChangeDirty: Event<IResolvedNotebookEditorModel>; readonly onWillFailWithConflict: Event<INotebookConflictEvent>; isDirty(resource: URI): boolean; resolve(resource: URI, viewType?: string): Promise<IReference<IResolvedNotebookEditorModel>>; resolve(resource: IUntitledNotebookResource, viewType: string): Promise<IReference<IResolvedNotebookEditorModel>>; }
src/vs/workbench/contrib/notebook/common/notebookEditorModelResolverService.ts
0
https://github.com/microsoft/vscode/commit/27bb32d00a7e309787e8f3cea271d67f7921dbba
[ 0.00017649705114308745, 0.00017093463975470513, 0.00016696723469067365, 0.00016950120334513485, 0.0000035231209949415643 ]
{ "id": 2, "code_window": [ "\t) {\n", "\t\tsuper(Parts.TITLEBAR_PART, { hasTitle: false }, themeService, storageService, layoutService);\n", "\t\tthis.windowTitle = this._register(instantiationService.createInstance(WindowTitle));\n", "\t\tthis.contextMenu = this._register(menuService.createMenu(MenuId.TitleBarContext, contextKeyService));\n", "\n", "\t\tthis.titleBarStyle = getTitleBarStyle(this.configurationService);\n", "\n", "\t\tthis.hoverDelegate = new class implements IHoverDelegate {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.titleContextMenu = this._register(menuService.createMenu(MenuId.TitleBarTitleContext, contextKeyService));\n" ], "file_path": "src/vs/workbench/browser/parts/titlebar/titlebarPart.ts", "type": "replace", "edit_start_line_idx": 101 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { IAuthenticationProvider, SyncStatus, SyncResource, Change, MergeState } from 'vs/platform/userDataSync/common/userDataSync'; import { Event } from 'vs/base/common/event'; import { RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { localize } from 'vs/nls'; import { URI } from 'vs/base/common/uri'; import { Codicon } from 'vs/base/common/codicons'; import { registerIcon } from 'vs/platform/theme/common/iconRegistry'; export interface IUserDataSyncAccount { readonly authenticationProviderId: string; readonly accountName: string; readonly accountId: string; } export interface IUserDataSyncPreview { readonly onDidChangeResources: Event<ReadonlyArray<IUserDataSyncResource>>; readonly resources: ReadonlyArray<IUserDataSyncResource>; accept(syncResource: SyncResource, resource: URI, content?: string | null): Promise<void>; merge(resource?: URI): Promise<void>; discard(resource?: URI): Promise<void>; pull(): Promise<void>; push(): Promise<void>; apply(): Promise<void>; cancel(): Promise<void>; } export interface IUserDataSyncResource { readonly syncResource: SyncResource; readonly local: URI; readonly remote: URI; readonly merged: URI; readonly accepted: URI; readonly localChange: Change; readonly remoteChange: Change; readonly mergeState: MergeState; } export const IUserDataSyncWorkbenchService = createDecorator<IUserDataSyncWorkbenchService>('IUserDataSyncWorkbenchService'); export interface IUserDataSyncWorkbenchService { _serviceBrand: any; readonly enabled: boolean; readonly authenticationProviders: IAuthenticationProvider[]; readonly all: IUserDataSyncAccount[]; readonly current: IUserDataSyncAccount | undefined; readonly accountStatus: AccountStatus; readonly onDidChangeAccountStatus: Event<AccountStatus>; readonly userDataSyncPreview: IUserDataSyncPreview; turnOn(): Promise<void>; turnOnUsingCurrentAccount(): Promise<void>; turnoff(everyWhere: boolean): Promise<void>; signIn(): Promise<void>; resetSyncedData(): Promise<void>; showSyncActivity(): Promise<void>; syncNow(): Promise<void>; synchroniseUserDataSyncStoreType(): Promise<void>; } export function getSyncAreaLabel(source: SyncResource): string { switch (source) { case SyncResource.Settings: return localize('settings', "Settings"); case SyncResource.Keybindings: return localize('keybindings', "Keyboard Shortcuts"); case SyncResource.Snippets: return localize('snippets', "User Snippets"); case SyncResource.Tasks: return localize('tasks', "User Tasks"); case SyncResource.Extensions: return localize('extensions', "Extensions"); case SyncResource.GlobalState: return localize('ui state label', "UI State"); } } export const enum AccountStatus { Uninitialized = 'uninitialized', Unavailable = 'unavailable', Available = 'available', } export const SYNC_TITLE = localize('sync category', "Settings Sync"); export const SYNC_VIEW_ICON = registerIcon('settings-sync-view-icon', Codicon.sync, localize('syncViewIcon', 'View icon of the Settings Sync view.')); // Contexts export const CONTEXT_SYNC_STATE = new RawContextKey<string>('syncStatus', SyncStatus.Uninitialized); export const CONTEXT_SYNC_ENABLEMENT = new RawContextKey<boolean>('syncEnabled', false); export const CONTEXT_ACCOUNT_STATE = new RawContextKey<string>('userDataSyncAccountStatus', AccountStatus.Uninitialized); export const CONTEXT_ENABLE_ACTIVITY_VIEWS = new RawContextKey<boolean>(`enableSyncActivityViews`, false); export const CONTEXT_ENABLE_SYNC_MERGES_VIEW = new RawContextKey<boolean>(`enableSyncMergesView`, false); // Commands export const CONFIGURE_SYNC_COMMAND_ID = 'workbench.userDataSync.actions.configure'; export const SHOW_SYNC_LOG_COMMAND_ID = 'workbench.userDataSync.actions.showLog'; // VIEWS export const SYNC_VIEW_CONTAINER_ID = 'workbench.view.sync'; export const SYNC_MERGES_VIEW_ID = 'workbench.views.sync.merges';
src/vs/workbench/services/userDataSync/common/userDataSync.ts
0
https://github.com/microsoft/vscode/commit/27bb32d00a7e309787e8f3cea271d67f7921dbba
[ 0.00017617542471271008, 0.0001725832698866725, 0.00016459645121358335, 0.00017401239892933518, 0.0000037467980291694403 ]
{ "id": 2, "code_window": [ "\t) {\n", "\t\tsuper(Parts.TITLEBAR_PART, { hasTitle: false }, themeService, storageService, layoutService);\n", "\t\tthis.windowTitle = this._register(instantiationService.createInstance(WindowTitle));\n", "\t\tthis.contextMenu = this._register(menuService.createMenu(MenuId.TitleBarContext, contextKeyService));\n", "\n", "\t\tthis.titleBarStyle = getTitleBarStyle(this.configurationService);\n", "\n", "\t\tthis.hoverDelegate = new class implements IHoverDelegate {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.titleContextMenu = this._register(menuService.createMenu(MenuId.TitleBarTitleContext, contextKeyService));\n" ], "file_path": "src/vs/workbench/browser/parts/titlebar/titlebarPart.ts", "type": "replace", "edit_start_line_idx": 101 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { renderLabelWithIcons } from 'vs/base/browser/ui/iconLabel/iconLabels'; import * as objects from 'vs/base/common/objects'; /** * A range to be highlighted. */ export interface IHighlight { start: number; end: number; extraClasses?: string[]; } export interface IOptions { /** * Whether */ readonly supportIcons?: boolean; } /** * A widget which can render a label with substring highlights, often * originating from a filter function like the fuzzy matcher. */ export class HighlightedLabel { private readonly domNode: HTMLElement; private text: string = ''; private title: string = ''; private highlights: IHighlight[] = []; private supportIcons: boolean; private didEverRender: boolean = false; /** * Create a new {@link HighlightedLabel}. * * @param container The parent container to append to. */ constructor(container: HTMLElement, options?: IOptions) { this.supportIcons = options?.supportIcons ?? false; this.domNode = dom.append(container, dom.$('span.monaco-highlighted-label')); } /** * The label's DOM node. */ get element(): HTMLElement { return this.domNode; } /** * Set the label and highlights. * * @param text The label to display. * @param highlights The ranges to highlight. * @param title An optional title for the hover tooltip. * @param escapeNewLines Whether to escape new lines. * @returns */ set(text: string | undefined, highlights: IHighlight[] = [], title: string = '', escapeNewLines?: boolean) { if (!text) { text = ''; } if (escapeNewLines) { // adjusts highlights inplace text = HighlightedLabel.escapeNewLines(text, highlights); } if (this.didEverRender && this.text === text && this.title === title && objects.equals(this.highlights, highlights)) { return; } this.text = text; this.title = title; this.highlights = highlights; this.render(); } private render(): void { const children: HTMLSpanElement[] = []; let pos = 0; for (const highlight of this.highlights) { if (highlight.end === highlight.start) { continue; } if (pos < highlight.start) { const substring = this.text.substring(pos, highlight.start); children.push(dom.$('span', undefined, ...this.supportIcons ? renderLabelWithIcons(substring) : [substring])); pos = highlight.end; } const substring = this.text.substring(highlight.start, highlight.end); const element = dom.$('span.highlight', undefined, ...this.supportIcons ? renderLabelWithIcons(substring) : [substring]); if (highlight.extraClasses) { element.classList.add(...highlight.extraClasses); } children.push(element); pos = highlight.end; } if (pos < this.text.length) { const substring = this.text.substring(pos,); children.push(dom.$('span', undefined, ...this.supportIcons ? renderLabelWithIcons(substring) : [substring])); } dom.reset(this.domNode, ...children); if (this.title) { this.domNode.title = this.title; } else { this.domNode.removeAttribute('title'); } this.didEverRender = true; } static escapeNewLines(text: string, highlights: IHighlight[]): string { let total = 0; let extra = 0; return text.replace(/\r\n|\r|\n/g, (match, offset) => { extra = match === '\r\n' ? -1 : 0; offset += total; for (const highlight of highlights) { if (highlight.end <= offset) { continue; } if (highlight.start >= offset) { highlight.start += extra; } if (highlight.end >= offset) { highlight.end += extra; } } total += extra; return '\u23CE'; }); } }
src/vs/base/browser/ui/highlightedlabel/highlightedLabel.ts
0
https://github.com/microsoft/vscode/commit/27bb32d00a7e309787e8f3cea271d67f7921dbba
[ 0.0001765187771525234, 0.00017148656479548663, 0.0001646677264943719, 0.00017245339404325932, 0.0000032384264159190934 ]
{ "id": 3, "code_window": [ "\t\tconst event = new StandardMouseEvent(e);\n", "\t\tconst anchor = { x: event.posx, y: event.posy };\n", "\n", "\t\t// Fill in contributed actions\n", "\t\tconst actions: IAction[] = [];\n", "\t\tconst actionsDisposable = createAndFillInContextMenuActions(this.contextMenu, undefined, actions);\n", "\n", "\t\t// Show it\n", "\t\tthis.contextMenuService.showContextMenu({\n", "\t\t\tgetAnchor: () => anchor,\n", "\t\t\tgetActions: () => actions,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst actionsDisposable = createAndFillInContextMenuActions(this.titleContextMenu, undefined, actions);\n" ], "file_path": "src/vs/workbench/browser/parts/titlebar/titlebarPart.ts", "type": "replace", "edit_start_line_idx": 389 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./media/titlebarpart'; import { localize } from 'vs/nls'; import { Part } from 'vs/workbench/browser/part'; import { ITitleService, ITitleProperties } from 'vs/workbench/services/title/common/titleService'; import { getZoomFactor } from 'vs/base/browser/browser'; import { MenuBarVisibility, getTitleBarStyle, getMenuBarVisibility } from 'vs/platform/window/common/window'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import { IAction, toAction } from 'vs/base/common/actions'; import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration'; import { DisposableStore, dispose } from 'vs/base/common/lifecycle'; import { IBrowserWorkbenchEnvironmentService } from 'vs/workbench/services/environment/browser/environmentService'; import { IThemeService, registerThemingParticipant, ThemeIcon } from 'vs/platform/theme/common/themeService'; import { TITLE_BAR_ACTIVE_BACKGROUND, TITLE_BAR_ACTIVE_FOREGROUND, TITLE_BAR_INACTIVE_FOREGROUND, TITLE_BAR_INACTIVE_BACKGROUND, TITLE_BAR_BORDER, WORKBENCH_BACKGROUND } from 'vs/workbench/common/theme'; import { isMacintosh, isWindows, isLinux, isWeb } from 'vs/base/common/platform'; import { Color } from 'vs/base/common/color'; import { EventType, EventHelper, Dimension, isAncestor, append, $, addDisposableListener, runAtThisOrScheduleAtNextAnimationFrame, prepend, reset } from 'vs/base/browser/dom'; import { CustomMenubarControl } from 'vs/workbench/browser/parts/titlebar/menubarControl'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { Emitter, Event } from 'vs/base/common/event'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { Parts, IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService'; import { createActionViewItem, createAndFillInContextMenuActions } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { IMenuService, IMenu, MenuId } from 'vs/platform/actions/common/actions'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IHostService } from 'vs/workbench/services/host/browser/host'; import { Codicon } from 'vs/base/common/codicons'; import { getIconRegistry } from 'vs/platform/theme/common/iconRegistry'; import { ToolBar } from 'vs/base/browser/ui/toolbar/toolbar'; import { WindowTitle } from 'vs/workbench/browser/parts/titlebar/windowTitle'; import { CommandCenterControl } from 'vs/workbench/browser/parts/titlebar/commandCenterControl'; import { IHoverDelegate } from 'vs/base/browser/ui/iconLabel/iconHoverDelegate'; import { IHoverService } from 'vs/workbench/services/hover/browser/hover'; export class TitlebarPart extends Part implements ITitleService { private static readonly configCommandCenter = 'window.commandCenter'; declare readonly _serviceBrand: undefined; //#region IView readonly minimumWidth: number = 0; readonly maximumWidth: number = Number.POSITIVE_INFINITY; get minimumHeight(): number { const value = this.isCommandCenterVisible ? 35 : 30; return value / (this.currentMenubarVisibility === 'hidden' || getZoomFactor() < 1 ? getZoomFactor() : 1); } get maximumHeight(): number { return this.minimumHeight; } //#endregion private _onMenubarVisibilityChange = this._register(new Emitter<boolean>()); readonly onMenubarVisibilityChange = this._onMenubarVisibilityChange.event; private readonly _onDidChangeCommandCenterVisibility = new Emitter<void>(); readonly onDidChangeCommandCenterVisibility: Event<void> = this._onDidChangeCommandCenterVisibility.event; protected rootContainer!: HTMLElement; protected windowControls: HTMLElement | undefined; protected title!: HTMLElement; protected customMenubar: CustomMenubarControl | undefined; protected appIcon: HTMLElement | undefined; private appIconBadge: HTMLElement | undefined; protected menubar?: HTMLElement; protected layoutControls: HTMLElement | undefined; private layoutToolbar: ToolBar | undefined; protected lastLayoutDimensions: Dimension | undefined; private hoverDelegate: IHoverDelegate; private readonly titleDisposables = this._register(new DisposableStore()); private titleBarStyle: 'native' | 'custom'; private isInactive: boolean = false; private readonly windowTitle: WindowTitle; private readonly contextMenu: IMenu; constructor( @IContextMenuService private readonly contextMenuService: IContextMenuService, @IConfigurationService protected readonly configurationService: IConfigurationService, @IBrowserWorkbenchEnvironmentService protected readonly environmentService: IBrowserWorkbenchEnvironmentService, @IInstantiationService protected readonly instantiationService: IInstantiationService, @IThemeService themeService: IThemeService, @IStorageService storageService: IStorageService, @IWorkbenchLayoutService layoutService: IWorkbenchLayoutService, @IMenuService private readonly menuService: IMenuService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IHostService private readonly hostService: IHostService, @IHoverService hoverService: IHoverService, ) { super(Parts.TITLEBAR_PART, { hasTitle: false }, themeService, storageService, layoutService); this.windowTitle = this._register(instantiationService.createInstance(WindowTitle)); this.contextMenu = this._register(menuService.createMenu(MenuId.TitleBarContext, contextKeyService)); this.titleBarStyle = getTitleBarStyle(this.configurationService); this.hoverDelegate = new class implements IHoverDelegate { private _lastHoverHideTime: number = 0; readonly showHover = hoverService.showHover.bind(hoverService); readonly placement = 'element'; get delay(): number { return Date.now() - this._lastHoverHideTime < 200 ? 0 // show instantly when a hover was recently shown : configurationService.getValue<number>('workbench.hover.delay'); } onDidHideHover() { this._lastHoverHideTime = Date.now(); } }; this.registerListeners(); } updateProperties(properties: ITitleProperties): void { this.windowTitle.updateProperties(properties); } get isCommandCenterVisible() { return this.configurationService.getValue<boolean>(TitlebarPart.configCommandCenter); } private registerListeners(): void { this._register(this.hostService.onDidChangeFocus(focused => focused ? this.onFocus() : this.onBlur())); this._register(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationChanged(e))); } private onBlur(): void { this.isInactive = true; this.updateStyles(); } private onFocus(): void { this.isInactive = false; this.updateStyles(); } protected onConfigurationChanged(event: IConfigurationChangeEvent): void { if (this.titleBarStyle !== 'native' && (!isMacintosh || isWeb)) { if (event.affectsConfiguration('window.menuBarVisibility')) { if (this.currentMenubarVisibility === 'compact') { this.uninstallMenubar(); } else { this.installMenubar(); } } } if (this.titleBarStyle !== 'native' && this.layoutControls && event.affectsConfiguration('workbench.layoutControl.enabled')) { this.layoutControls.classList.toggle('show-layout-control', this.layoutControlEnabled); } if (event.affectsConfiguration(TitlebarPart.configCommandCenter)) { this.updateTitle(); this.adjustTitleMarginToCenter(); this._onDidChangeCommandCenterVisibility.fire(); } } protected onMenubarVisibilityChanged(visible: boolean): void { if (isWeb || isWindows || isLinux) { if (this.lastLayoutDimensions) { this.layout(this.lastLayoutDimensions.width, this.lastLayoutDimensions.height); } this._onMenubarVisibilityChange.fire(visible); } } private uninstallMenubar(): void { if (this.customMenubar) { this.customMenubar.dispose(); this.customMenubar = undefined; } if (this.menubar) { this.menubar.remove(); this.menubar = undefined; } this.onMenubarVisibilityChanged(false); } protected installMenubar(): void { // If the menubar is already installed, skip if (this.menubar) { return; } this.customMenubar = this._register(this.instantiationService.createInstance(CustomMenubarControl)); this.menubar = this.rootContainer.insertBefore($('div.menubar'), this.title); this.menubar.setAttribute('role', 'menubar'); this._register(this.customMenubar.onVisibilityChange(e => this.onMenubarVisibilityChanged(e))); this.customMenubar.create(this.menubar); } private updateTitle(): void { this.titleDisposables.clear(); if (!this.isCommandCenterVisible) { // Text Title this.title.innerText = this.windowTitle.value; this.titleDisposables.add(this.windowTitle.onDidChange(() => { this.title.innerText = this.windowTitle.value; this.adjustTitleMarginToCenter(); })); } else { // Menu Title const commandCenter = this.instantiationService.createInstance(CommandCenterControl, this.windowTitle, this.hoverDelegate); reset(this.title, commandCenter.element); this.titleDisposables.add(commandCenter); this.titleDisposables.add(commandCenter.onDidChangeVisibility(this.adjustTitleMarginToCenter, this)); } } override createContentArea(parent: HTMLElement): HTMLElement { this.element = parent; this.rootContainer = append(parent, $('.titlebar-container')); // App Icon (Native Windows/Linux and Web) if (!isMacintosh || isWeb) { this.appIcon = prepend(this.rootContainer, $('a.window-appicon')); // Web-only home indicator and menu if (isWeb) { const homeIndicator = this.environmentService.options?.homeIndicator; if (homeIndicator) { const icon: ThemeIcon = getIconRegistry().getIcon(homeIndicator.icon) ? { id: homeIndicator.icon } : Codicon.code; this.appIcon.setAttribute('href', homeIndicator.href); this.appIcon.classList.add(...ThemeIcon.asClassNameArray(icon)); this.appIconBadge = document.createElement('div'); this.appIconBadge.classList.add('home-bar-icon-badge'); this.appIcon.appendChild(this.appIconBadge); } } } // Menubar: install a custom menu bar depending on configuration // and when not in activity bar if (this.titleBarStyle !== 'native' && (!isMacintosh || isWeb) && this.currentMenubarVisibility !== 'compact') { this.installMenubar(); } // Title this.title = append(this.rootContainer, $('div.window-title')); this.updateTitle(); if (this.titleBarStyle !== 'native') { this.layoutControls = append(this.rootContainer, $('div.layout-controls-container')); this.layoutControls.classList.toggle('show-layout-control', this.layoutControlEnabled); this.layoutToolbar = new ToolBar(this.layoutControls, this.contextMenuService, { actionViewItemProvider: action => { return createActionViewItem(this.instantiationService, action, { hoverDelegate: this.hoverDelegate }); }, allowContextMenu: true }); this._register(addDisposableListener(this.layoutControls, EventType.CONTEXT_MENU, e => { EventHelper.stop(e); this.onLayoutControlContextMenu(e, this.layoutControls!); })); const menu = this._register(this.menuService.createMenu(MenuId.LayoutControlMenu, this.contextKeyService)); const updateLayoutMenu = () => { if (!this.layoutToolbar) { return; } const actions: IAction[] = []; const toDispose = createAndFillInContextMenuActions(menu, undefined, { primary: [], secondary: actions }); this.layoutToolbar.setActions(actions); toDispose.dispose(); }; menu.onDidChange(updateLayoutMenu); updateLayoutMenu(); } this.windowControls = append(this.element, $('div.window-controls-container')); // Context menu on title [EventType.CONTEXT_MENU, EventType.MOUSE_DOWN].forEach(event => { this._register(addDisposableListener(this.title, event, e => { if (e.type === EventType.CONTEXT_MENU || e.metaKey) { EventHelper.stop(e); this.onContextMenu(e); } })); }); // Since the title area is used to drag the window, we do not want to steal focus from the // currently active element. So we restore focus after a timeout back to where it was. this._register(addDisposableListener(this.element, EventType.MOUSE_DOWN, e => { if (e.target && this.menubar && isAncestor(e.target as HTMLElement, this.menubar)) { return; } if (e.target && this.layoutToolbar && isAncestor(e.target as HTMLElement, this.layoutToolbar.getElement())) { return; } if (e.target && isAncestor(e.target as HTMLElement, this.title)) { return; } const active = document.activeElement; setTimeout(() => { if (active instanceof HTMLElement) { active.focus(); } }, 0 /* need a timeout because we are in capture phase */); }, true /* use capture to know the currently active element properly */)); this.updateStyles(); return this.element; } override updateStyles(): void { super.updateStyles(); // Part container if (this.element) { if (this.isInactive) { this.element.classList.add('inactive'); } else { this.element.classList.remove('inactive'); } const titleBackground = this.getColor(this.isInactive ? TITLE_BAR_INACTIVE_BACKGROUND : TITLE_BAR_ACTIVE_BACKGROUND, (color, theme) => { // LCD Rendering Support: the title bar part is a defining its own GPU layer. // To benefit from LCD font rendering, we must ensure that we always set an // opaque background color. As such, we compute an opaque color given we know // the background color is the workbench background. return color.isOpaque() ? color : color.makeOpaque(WORKBENCH_BACKGROUND(theme)); }) || ''; this.element.style.backgroundColor = titleBackground; if (this.appIconBadge) { this.appIconBadge.style.backgroundColor = titleBackground; } if (titleBackground && Color.fromHex(titleBackground).isLighter()) { this.element.classList.add('light'); } else { this.element.classList.remove('light'); } const titleForeground = this.getColor(this.isInactive ? TITLE_BAR_INACTIVE_FOREGROUND : TITLE_BAR_ACTIVE_FOREGROUND); this.element.style.color = titleForeground || ''; const titleBorder = this.getColor(TITLE_BAR_BORDER); this.element.style.borderBottom = titleBorder ? `1px solid ${titleBorder}` : ''; } } private onContextMenu(e: MouseEvent): void { // Find target anchor const event = new StandardMouseEvent(e); const anchor = { x: event.posx, y: event.posy }; // Fill in contributed actions const actions: IAction[] = []; const actionsDisposable = createAndFillInContextMenuActions(this.contextMenu, undefined, actions); // Show it this.contextMenuService.showContextMenu({ getAnchor: () => anchor, getActions: () => actions, onHide: () => dispose(actionsDisposable) }); } private onLayoutControlContextMenu(e: MouseEvent, el: HTMLElement): void { // Find target anchor const event = new StandardMouseEvent(e); const anchor = { x: event.posx, y: event.posy }; const actions: IAction[] = []; actions.push(toAction({ id: 'layoutControl.hide', label: localize('layoutControl.hide', "Hide Layout Control"), run: () => { this.configurationService.updateValue('workbench.layoutControl.enabled', false); } })); // Show it this.contextMenuService.showContextMenu({ getAnchor: () => anchor, getActions: () => actions, domForShadowRoot: el }); } protected adjustTitleMarginToCenter(): void { const base = isMacintosh ? (this.windowControls?.clientWidth ?? 0) : 0; const leftMarker = base + (this.appIcon?.clientWidth ?? 0) + (this.menubar?.clientWidth ?? 0) + 10; const rightMarker = base + this.rootContainer.clientWidth - (this.layoutControls?.clientWidth ?? 0) - 10; // Not enough space to center the titlebar within window, // Center between left and right controls if (leftMarker > (this.rootContainer.clientWidth + (this.windowControls?.clientWidth ?? 0) - this.title.clientWidth) / 2 || rightMarker < (this.rootContainer.clientWidth + (this.windowControls?.clientWidth ?? 0) + this.title.clientWidth) / 2) { this.title.style.position = ''; this.title.style.left = ''; this.title.style.transform = ''; return; } this.title.style.position = 'absolute'; this.title.style.left = `calc(50% - ${this.title.clientWidth / 2}px)`; } protected get currentMenubarVisibility(): MenuBarVisibility { return getMenuBarVisibility(this.configurationService); } private get layoutControlEnabled(): boolean { return this.configurationService.getValue<boolean>('workbench.layoutControl.enabled'); } updateLayout(dimension: Dimension): void { this.lastLayoutDimensions = dimension; if (getTitleBarStyle(this.configurationService) === 'custom') { // Prevent zooming behavior if any of the following conditions are met: // 1. Native macOS // 2. Menubar is hidden // 3. Shrinking below the window control size (zoom < 1) const zoomFactor = getZoomFactor(); this.element.style.setProperty('--zoom-factor', zoomFactor.toString()); this.rootContainer.classList.toggle('counter-zoom', zoomFactor < 1 || (!isWeb && isMacintosh) || this.currentMenubarVisibility === 'hidden'); runAtThisOrScheduleAtNextAnimationFrame(() => this.adjustTitleMarginToCenter()); if (this.customMenubar) { const menubarDimension = new Dimension(0, dimension.height); this.customMenubar.layout(menubarDimension); } } } override layout(width: number, height: number): void { this.updateLayout(new Dimension(width, height)); super.layoutContents(width, height); } toJSON(): object { return { type: Parts.TITLEBAR_PART }; } } registerThemingParticipant((theme, collector) => { const titlebarActiveFg = theme.getColor(TITLE_BAR_ACTIVE_FOREGROUND); if (titlebarActiveFg) { collector.addRule(` .monaco-workbench .part.titlebar .window-controls-container .window-icon { color: ${titlebarActiveFg}; } `); } const titlebarInactiveFg = theme.getColor(TITLE_BAR_INACTIVE_FOREGROUND); if (titlebarInactiveFg) { collector.addRule(` .monaco-workbench .part.titlebar.inactive .window-controls-container .window-icon { color: ${titlebarInactiveFg}; } `); } });
src/vs/workbench/browser/parts/titlebar/titlebarPart.ts
1
https://github.com/microsoft/vscode/commit/27bb32d00a7e309787e8f3cea271d67f7921dbba
[ 0.9993650317192078, 0.08271145075559616, 0.00016261867131106555, 0.00017298590682912618, 0.25689226388931274 ]
{ "id": 3, "code_window": [ "\t\tconst event = new StandardMouseEvent(e);\n", "\t\tconst anchor = { x: event.posx, y: event.posy };\n", "\n", "\t\t// Fill in contributed actions\n", "\t\tconst actions: IAction[] = [];\n", "\t\tconst actionsDisposable = createAndFillInContextMenuActions(this.contextMenu, undefined, actions);\n", "\n", "\t\t// Show it\n", "\t\tthis.contextMenuService.showContextMenu({\n", "\t\t\tgetAnchor: () => anchor,\n", "\t\t\tgetActions: () => actions,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst actionsDisposable = createAndFillInContextMenuActions(this.titleContextMenu, undefined, actions);\n" ], "file_path": "src/vs/workbench/browser/parts/titlebar/titlebarPart.ts", "type": "replace", "edit_start_line_idx": 389 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Code } from './code'; export abstract class Viewlet { constructor(protected code: Code) { } async waitForTitle(fn: (title: string) => boolean): Promise<void> { await this.code.waitForTextContent('.monaco-workbench .part.sidebar > .title > .title-label > h2', undefined, fn); } }
test/automation/src/viewlet.ts
0
https://github.com/microsoft/vscode/commit/27bb32d00a7e309787e8f3cea271d67f7921dbba
[ 0.00017676249262876809, 0.00017445164849050343, 0.00017214080435223877, 0.00017445164849050343, 0.000002310844138264656 ]