hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
sequencelengths 5
5
|
---|---|---|---|---|---|
{
"id": 2,
"code_window": [
"function stripComments(input: string): string {\n",
" return input.replace(_commentRe, '');\n",
"}\n",
"\n",
"// all comments except inline source mapping\n",
"const _sourceMappingUrlRe = /\\/\\*\\s*#\\s*sourceMappingURL=[\\s\\S]+?\\*\\//;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"const _commentWithHashRe = /\\/\\*\\s*#\\s*source(Mapping)?URL=[\\s\\S]+?\\*\\//g;\n"
],
"file_path": "packages/compiler/src/shadow_css.ts",
"type": "replace",
"edit_start_line_idx": 546
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
export default [
[
['mi', 'n', 'in the morning', 'in the afternoon', 'in the evening', 'at night'],
['midnight', 'noon', 'in the morning', 'in the afternoon', 'in the evening', 'at night'],
],
[
['midnight', 'noon', 'morning', 'afternoon', 'evening', 'night'],
,
],
[
'00:00', '12:00', ['06:00', '12:00'], ['12:00', '18:00'], ['18:00', '21:00'],
['21:00', '06:00']
]
];
| packages/common/locales/extra/en-ZA.ts | 0 | https://github.com/angular/angular/commit/5f681f9745077a261c7e316fbcec9415011361ba | [
0.0001738142454996705,
0.00017265112546738237,
0.00017076234507840127,
0.00017337674216832966,
0.0000013474493698595325
] |
{
"id": 2,
"code_window": [
"function stripComments(input: string): string {\n",
" return input.replace(_commentRe, '');\n",
"}\n",
"\n",
"// all comments except inline source mapping\n",
"const _sourceMappingUrlRe = /\\/\\*\\s*#\\s*sourceMappingURL=[\\s\\S]+?\\*\\//;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"const _commentWithHashRe = /\\/\\*\\s*#\\s*source(Mapping)?URL=[\\s\\S]+?\\*\\//g;\n"
],
"file_path": "packages/compiler/src/shadow_css.ts",
"type": "replace",
"edit_start_line_idx": 546
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Routes} from '../src/config';
import {createRouterState} from '../src/create_router_state';
import {recognize} from '../src/recognize';
import {DefaultRouteReuseStrategy} from '../src/route_reuse_strategy';
import {ActivatedRoute, RouterState, RouterStateSnapshot, advanceActivatedRoute, createEmptyState} from '../src/router_state';
import {PRIMARY_OUTLET} from '../src/shared';
import {DefaultUrlSerializer, UrlSegmentGroup, UrlTree} from '../src/url_tree';
import {TreeNode} from '../src/utils/tree';
describe('create router state', () => {
const reuseStrategy = new DefaultRouteReuseStrategy();
const emptyState = () => createEmptyState(
new (UrlTree as any)(new UrlSegmentGroup([], {}), {}, null !), RootComponent);
it('should work create new state', () => {
const state = createRouterState(
reuseStrategy, createState(
[
{path: 'a', component: ComponentA},
{path: 'b', component: ComponentB, outlet: 'left'},
{path: 'c', component: ComponentC, outlet: 'right'}
],
'a(left:b//right:c)'),
emptyState());
checkActivatedRoute(state.root, RootComponent);
const c = (state as any).children(state.root);
checkActivatedRoute(c[0], ComponentA);
checkActivatedRoute(c[1], ComponentB, 'left');
checkActivatedRoute(c[2], ComponentC, 'right');
});
it('should reuse existing nodes when it can', () => {
const config = [
{path: 'a', component: ComponentA}, {path: 'b', component: ComponentB, outlet: 'left'},
{path: 'c', component: ComponentC, outlet: 'left'}
];
const prevState =
createRouterState(reuseStrategy, createState(config, 'a(left:b)'), emptyState());
advanceState(prevState);
const state = createRouterState(reuseStrategy, createState(config, 'a(left:c)'), prevState);
expect(prevState.root).toBe(state.root);
const prevC = (prevState as any).children(prevState.root);
const currC = (state as any).children(state.root);
expect(prevC[0]).toBe(currC[0]);
expect(prevC[1]).not.toBe(currC[1]);
checkActivatedRoute(currC[1], ComponentC, 'left');
});
it('should handle componentless routes', () => {
const config = [{
path: 'a/:id',
children: [
{path: 'b', component: ComponentA}, {path: 'c', component: ComponentB, outlet: 'right'}
]
}];
const prevState = createRouterState(
reuseStrategy, createState(config, 'a/1;p=11/(b//right:c)'), emptyState());
advanceState(prevState);
const state =
createRouterState(reuseStrategy, createState(config, 'a/2;p=22/(b//right:c)'), prevState);
expect(prevState.root).toBe(state.root);
const prevP = (prevState as any).firstChild(prevState.root) !;
const currP = (state as any).firstChild(state.root) !;
expect(prevP).toBe(currP);
const currC = (state as any).children(currP);
expect(currP._futureSnapshot.params).toEqual({id: '2', p: '22'});
expect(currP._futureSnapshot.paramMap.get('id')).toEqual('2');
expect(currP._futureSnapshot.paramMap.get('p')).toEqual('22');
checkActivatedRoute(currC[0], ComponentA);
checkActivatedRoute(currC[1], ComponentB, 'right');
});
});
function advanceState(state: RouterState): void {
advanceNode((state as any)._root);
}
function advanceNode(node: TreeNode<ActivatedRoute>): void {
advanceActivatedRoute(node.value);
node.children.forEach(advanceNode);
}
function createState(config: Routes, url: string): RouterStateSnapshot {
let res: RouterStateSnapshot = undefined !;
recognize(RootComponent, config, tree(url), url).forEach(s => res = s);
return res;
}
function checkActivatedRoute(
actual: ActivatedRoute, cmp: Function, outlet: string = PRIMARY_OUTLET): void {
if (actual === null) {
expect(actual).toBeDefined();
} else {
expect(actual.component).toBe(cmp);
expect(actual.outlet).toEqual(outlet);
}
}
function tree(url: string): UrlTree {
return new DefaultUrlSerializer().parse(url);
}
class RootComponent {}
class ComponentA {}
class ComponentB {}
class ComponentC {}
| packages/router/test/create_router_state.spec.ts | 0 | https://github.com/angular/angular/commit/5f681f9745077a261c7e316fbcec9415011361ba | [
0.0001880513154901564,
0.0001733594835968688,
0.00016695655358489603,
0.00017300799663644284,
0.000005265705567580881
] |
{
"id": 3,
"code_window": [
"\n",
"function extractSourceMappingUrl(input: string): string {\n",
" const matcher = input.match(_sourceMappingUrlRe);\n",
" return matcher ? matcher[0] : '';\n",
"}\n",
"\n",
"const _ruleRe = /(\\s*)([^;\\{\\}]+?)(\\s*)((?:{%BLOCK%}?\\s*;?)|(?:\\s*;))/g;\n",
"const _curlyRe = /([{}])/g;\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"function extractCommentsWithHash(input: string): string[] {\n",
" return input.match(_commentWithHashRe) || [];\n"
],
"file_path": "packages/compiler/src/shadow_css.ts",
"type": "replace",
"edit_start_line_idx": 549
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* This file is a port of shadowCSS from webcomponents.js to TypeScript.
*
* Please make sure to keep to edits in sync with the source file.
*
* Source:
* https://github.com/webcomponents/webcomponentsjs/blob/4efecd7e0e/src/ShadowCSS/ShadowCSS.js
*
* The original file level comment is reproduced below
*/
/*
This is a limited shim for ShadowDOM css styling.
https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/shadow/index.html#styles
The intention here is to support only the styling features which can be
relatively simply implemented. The goal is to allow users to avoid the
most obvious pitfalls and do so without compromising performance significantly.
For ShadowDOM styling that's not covered here, a set of best practices
can be provided that should allow users to accomplish more complex styling.
The following is a list of specific ShadowDOM styling features and a brief
discussion of the approach used to shim.
Shimmed features:
* :host, :host-context: ShadowDOM allows styling of the shadowRoot's host
element using the :host rule. To shim this feature, the :host styles are
reformatted and prefixed with a given scope name and promoted to a
document level stylesheet.
For example, given a scope name of .foo, a rule like this:
:host {
background: red;
}
}
becomes:
.foo {
background: red;
}
* encapsulation: Styles defined within ShadowDOM, apply only to
dom inside the ShadowDOM. Polymer uses one of two techniques to implement
this feature.
By default, rules are prefixed with the host element tag name
as a descendant selector. This ensures styling does not leak out of the 'top'
of the element's ShadowDOM. For example,
div {
font-weight: bold;
}
becomes:
x-foo div {
font-weight: bold;
}
becomes:
Alternatively, if WebComponents.ShadowCSS.strictStyling is set to true then
selectors are scoped by adding an attribute selector suffix to each
simple selector that contains the host element tag name. Each element
in the element's ShadowDOM template is also given the scope attribute.
Thus, these rules match only elements that have the scope attribute.
For example, given a scope name of x-foo, a rule like this:
div {
font-weight: bold;
}
becomes:
div[x-foo] {
font-weight: bold;
}
Note that elements that are dynamically added to a scope must have the scope
selector added to them manually.
* upper/lower bound encapsulation: Styles which are defined outside a
shadowRoot should not cross the ShadowDOM boundary and should not apply
inside a shadowRoot.
This styling behavior is not emulated. Some possible ways to do this that
were rejected due to complexity and/or performance concerns include: (1) reset
every possible property for every possible selector for a given scope name;
(2) re-implement css in javascript.
As an alternative, users should make sure to use selectors
specific to the scope in which they are working.
* ::distributed: This behavior is not emulated. It's often not necessary
to style the contents of a specific insertion point and instead, descendants
of the host element can be styled selectively. Users can also create an
extra node around an insertion point and style that node's contents
via descendent selectors. For example, with a shadowRoot like this:
<style>
::content(div) {
background: red;
}
</style>
<content></content>
could become:
<style>
/ *@polyfill .content-container div * /
::content(div) {
background: red;
}
</style>
<div class="content-container">
<content></content>
</div>
Note the use of @polyfill in the comment above a ShadowDOM specific style
declaration. This is a directive to the styling shim to use the selector
in comments in lieu of the next selector when running under polyfill.
*/
export class ShadowCss {
strictStyling: boolean = true;
constructor() {}
/*
* Shim some cssText with the given selector. Returns cssText that can
* be included in the document via WebComponents.ShadowCSS.addCssToDocument(css).
*
* When strictStyling is true:
* - selector is the attribute added to all elements inside the host,
* - hostSelector is the attribute added to the host itself.
*/
shimCssText(cssText: string, selector: string, hostSelector: string = ''): string {
const sourceMappingUrl: string = extractSourceMappingUrl(cssText);
cssText = stripComments(cssText);
cssText = this._insertDirectives(cssText);
return this._scopeCssText(cssText, selector, hostSelector) + sourceMappingUrl;
}
private _insertDirectives(cssText: string): string {
cssText = this._insertPolyfillDirectivesInCssText(cssText);
return this._insertPolyfillRulesInCssText(cssText);
}
/*
* Process styles to convert native ShadowDOM rules that will trip
* up the css parser; we rely on decorating the stylesheet with inert rules.
*
* For example, we convert this rule:
*
* polyfill-next-selector { content: ':host menu-item'; }
* ::content menu-item {
*
* to this:
*
* scopeName menu-item {
*
**/
private _insertPolyfillDirectivesInCssText(cssText: string): string {
// Difference with webcomponents.js: does not handle comments
return cssText.replace(
_cssContentNextSelectorRe, function(...m: string[]) { return m[2] + '{'; });
}
/*
* Process styles to add rules which will only apply under the polyfill
*
* For example, we convert this rule:
*
* polyfill-rule {
* content: ':host menu-item';
* ...
* }
*
* to this:
*
* scopeName menu-item {...}
*
**/
private _insertPolyfillRulesInCssText(cssText: string): string {
// Difference with webcomponents.js: does not handle comments
return cssText.replace(_cssContentRuleRe, (...m: string[]) => {
const rule = m[0].replace(m[1], '').replace(m[2], '');
return m[4] + rule;
});
}
/* Ensure styles are scoped. Pseudo-scoping takes a rule like:
*
* .foo {... }
*
* and converts this to
*
* scopeName .foo { ... }
*/
private _scopeCssText(cssText: string, scopeSelector: string, hostSelector: string): string {
const unscopedRules = this._extractUnscopedRulesFromCssText(cssText);
// replace :host and :host-context -shadowcsshost and -shadowcsshost respectively
cssText = this._insertPolyfillHostInCssText(cssText);
cssText = this._convertColonHost(cssText);
cssText = this._convertColonHostContext(cssText);
cssText = this._convertShadowDOMSelectors(cssText);
if (scopeSelector) {
cssText = this._scopeSelectors(cssText, scopeSelector, hostSelector);
}
cssText = cssText + '\n' + unscopedRules;
return cssText.trim();
}
/*
* Process styles to add rules which will only apply under the polyfill
* and do not process via CSSOM. (CSSOM is destructive to rules on rare
* occasions, e.g. -webkit-calc on Safari.)
* For example, we convert this rule:
*
* @polyfill-unscoped-rule {
* content: 'menu-item';
* ... }
*
* to this:
*
* menu-item {...}
*
**/
private _extractUnscopedRulesFromCssText(cssText: string): string {
// Difference with webcomponents.js: does not handle comments
let r = '';
let m: RegExpExecArray|null;
_cssContentUnscopedRuleRe.lastIndex = 0;
while ((m = _cssContentUnscopedRuleRe.exec(cssText)) !== null) {
const rule = m[0].replace(m[2], '').replace(m[1], m[4]);
r += rule + '\n\n';
}
return r;
}
/*
* convert a rule like :host(.foo) > .bar { }
*
* to
*
* .foo<scopeName> > .bar
*/
private _convertColonHost(cssText: string): string {
return this._convertColonRule(cssText, _cssColonHostRe, this._colonHostPartReplacer);
}
/*
* convert a rule like :host-context(.foo) > .bar { }
*
* to
*
* .foo<scopeName> > .bar, .foo scopeName > .bar { }
*
* and
*
* :host-context(.foo:host) .bar { ... }
*
* to
*
* .foo<scopeName> .bar { ... }
*/
private _convertColonHostContext(cssText: string): string {
return this._convertColonRule(
cssText, _cssColonHostContextRe, this._colonHostContextPartReplacer);
}
private _convertColonRule(cssText: string, regExp: RegExp, partReplacer: Function): string {
// m[1] = :host(-context), m[2] = contents of (), m[3] rest of rule
return cssText.replace(regExp, function(...m: string[]) {
if (m[2]) {
const parts = m[2].split(',');
const r: string[] = [];
for (let i = 0; i < parts.length; i++) {
const p = parts[i].trim();
if (!p) break;
r.push(partReplacer(_polyfillHostNoCombinator, p, m[3]));
}
return r.join(',');
} else {
return _polyfillHostNoCombinator + m[3];
}
});
}
private _colonHostContextPartReplacer(host: string, part: string, suffix: string): string {
if (part.indexOf(_polyfillHost) > -1) {
return this._colonHostPartReplacer(host, part, suffix);
} else {
return host + part + suffix + ', ' + part + ' ' + host + suffix;
}
}
private _colonHostPartReplacer(host: string, part: string, suffix: string): string {
return host + part.replace(_polyfillHost, '') + suffix;
}
/*
* Convert combinators like ::shadow and pseudo-elements like ::content
* by replacing with space.
*/
private _convertShadowDOMSelectors(cssText: string): string {
return _shadowDOMSelectorsRe.reduce((result, pattern) => result.replace(pattern, ' '), cssText);
}
// change a selector like 'div' to 'name div'
private _scopeSelectors(cssText: string, scopeSelector: string, hostSelector: string): string {
return processRules(cssText, (rule: CssRule) => {
let selector = rule.selector;
let content = rule.content;
if (rule.selector[0] != '@') {
selector =
this._scopeSelector(rule.selector, scopeSelector, hostSelector, this.strictStyling);
} else if (
rule.selector.startsWith('@media') || rule.selector.startsWith('@supports') ||
rule.selector.startsWith('@page') || rule.selector.startsWith('@document')) {
content = this._scopeSelectors(rule.content, scopeSelector, hostSelector);
}
return new CssRule(selector, content);
});
}
private _scopeSelector(
selector: string, scopeSelector: string, hostSelector: string, strict: boolean): string {
return selector.split(',')
.map(part => part.trim().split(_shadowDeepSelectors))
.map((deepParts) => {
const [shallowPart, ...otherParts] = deepParts;
const applyScope = (shallowPart: string) => {
if (this._selectorNeedsScoping(shallowPart, scopeSelector)) {
return strict ?
this._applyStrictSelectorScope(shallowPart, scopeSelector, hostSelector) :
this._applySelectorScope(shallowPart, scopeSelector, hostSelector);
} else {
return shallowPart;
}
};
return [applyScope(shallowPart), ...otherParts].join(' ');
})
.join(', ');
}
private _selectorNeedsScoping(selector: string, scopeSelector: string): boolean {
const re = this._makeScopeMatcher(scopeSelector);
return !re.test(selector);
}
private _makeScopeMatcher(scopeSelector: string): RegExp {
const lre = /\[/g;
const rre = /\]/g;
scopeSelector = scopeSelector.replace(lre, '\\[').replace(rre, '\\]');
return new RegExp('^(' + scopeSelector + ')' + _selectorReSuffix, 'm');
}
private _applySelectorScope(selector: string, scopeSelector: string, hostSelector: string):
string {
// Difference from webcomponents.js: scopeSelector could not be an array
return this._applySimpleSelectorScope(selector, scopeSelector, hostSelector);
}
// scope via name and [is=name]
private _applySimpleSelectorScope(selector: string, scopeSelector: string, hostSelector: string):
string {
// In Android browser, the lastIndex is not reset when the regex is used in String.replace()
_polyfillHostRe.lastIndex = 0;
if (_polyfillHostRe.test(selector)) {
const replaceBy = this.strictStyling ? `[${hostSelector}]` : scopeSelector;
return selector
.replace(
_polyfillHostNoCombinatorRe,
(hnc, selector) => {
return selector.replace(
/([^:]*)(:*)(.*)/,
(_: string, before: string, colon: string, after: string) => {
return before + replaceBy + colon + after;
});
})
.replace(_polyfillHostRe, replaceBy + ' ');
}
return scopeSelector + ' ' + selector;
}
// return a selector with [name] suffix on each simple selector
// e.g. .foo.bar > .zot becomes .foo[name].bar[name] > .zot[name] /** @internal */
private _applyStrictSelectorScope(selector: string, scopeSelector: string, hostSelector: string):
string {
const isRe = /\[is=([^\]]*)\]/g;
scopeSelector = scopeSelector.replace(isRe, (_: string, ...parts: string[]) => parts[0]);
const attrName = '[' + scopeSelector + ']';
const _scopeSelectorPart = (p: string) => {
let scopedP = p.trim();
if (!scopedP) {
return '';
}
if (p.indexOf(_polyfillHostNoCombinator) > -1) {
scopedP = this._applySimpleSelectorScope(p, scopeSelector, hostSelector);
} else {
// remove :host since it should be unnecessary
const t = p.replace(_polyfillHostRe, '');
if (t.length > 0) {
const matches = t.match(/([^:]*)(:*)(.*)/);
if (matches) {
scopedP = matches[1] + attrName + matches[2] + matches[3];
}
}
}
return scopedP;
};
const safeContent = new SafeSelector(selector);
selector = safeContent.content();
let scopedSelector = '';
let startIndex = 0;
let res: RegExpExecArray|null;
const sep = /( |>|\+|~(?!=))\s*/g;
// If a selector appears before :host it should not be shimmed as it
// matches on ancestor elements and not on elements in the host's shadow
// `:host-context(div)` is transformed to
// `-shadowcsshost-no-combinatordiv, div -shadowcsshost-no-combinator`
// the `div` is not part of the component in the 2nd selectors and should not be scoped.
// Historically `component-tag:host` was matching the component so we also want to preserve
// this behavior to avoid breaking legacy apps (it should not match).
// The behavior should be:
// - `tag:host` -> `tag[h]` (this is to avoid breaking legacy apps, should not match anything)
// - `tag :host` -> `tag [h]` (`tag` is not scoped because it's considered part of a
// `:host-context(tag)`)
const hasHost = selector.indexOf(_polyfillHostNoCombinator) > -1;
// Only scope parts after the first `-shadowcsshost-no-combinator` when it is present
let shouldScope = !hasHost;
while ((res = sep.exec(selector)) !== null) {
const separator = res[1];
const part = selector.slice(startIndex, res.index).trim();
shouldScope = shouldScope || part.indexOf(_polyfillHostNoCombinator) > -1;
const scopedPart = shouldScope ? _scopeSelectorPart(part) : part;
scopedSelector += `${scopedPart} ${separator} `;
startIndex = sep.lastIndex;
}
const part = selector.substring(startIndex);
shouldScope = shouldScope || part.indexOf(_polyfillHostNoCombinator) > -1;
scopedSelector += shouldScope ? _scopeSelectorPart(part) : part;
// replace the placeholders with their original values
return safeContent.restore(scopedSelector);
}
private _insertPolyfillHostInCssText(selector: string): string {
return selector.replace(_colonHostContextRe, _polyfillHostContext)
.replace(_colonHostRe, _polyfillHost);
}
}
class SafeSelector {
private placeholders: string[] = [];
private index = 0;
private _content: string;
constructor(selector: string) {
// Replaces attribute selectors with placeholders.
// The WS in [attr="va lue"] would otherwise be interpreted as a selector separator.
selector = selector.replace(/(\[[^\]]*\])/g, (_, keep) => {
const replaceBy = `__ph-${this.index}__`;
this.placeholders.push(keep);
this.index++;
return replaceBy;
});
// Replaces the expression in `:nth-child(2n + 1)` with a placeholder.
// WS and "+" would otherwise be interpreted as selector separators.
this._content = selector.replace(/(:nth-[-\w]+)(\([^)]+\))/g, (_, pseudo, exp) => {
const replaceBy = `__ph-${this.index}__`;
this.placeholders.push(exp);
this.index++;
return pseudo + replaceBy;
});
}
restore(content: string): string {
return content.replace(/__ph-(\d+)__/g, (ph, index) => this.placeholders[+index]);
}
content(): string { return this._content; }
}
const _cssContentNextSelectorRe =
/polyfill-next-selector[^}]*content:[\s]*?(['"])(.*?)\1[;\s]*}([^{]*?){/gim;
const _cssContentRuleRe = /(polyfill-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim;
const _cssContentUnscopedRuleRe =
/(polyfill-unscoped-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim;
const _polyfillHost = '-shadowcsshost';
// note: :host-context pre-processed to -shadowcsshostcontext.
const _polyfillHostContext = '-shadowcsscontext';
const _parenSuffix = ')(?:\\((' +
'(?:\\([^)(]*\\)|[^)(]*)+?' +
')\\))?([^,{]*)';
const _cssColonHostRe = new RegExp('(' + _polyfillHost + _parenSuffix, 'gim');
const _cssColonHostContextRe = new RegExp('(' + _polyfillHostContext + _parenSuffix, 'gim');
const _polyfillHostNoCombinator = _polyfillHost + '-no-combinator';
const _polyfillHostNoCombinatorRe = /-shadowcsshost-no-combinator([^\s]*)/;
const _shadowDOMSelectorsRe = [
/::shadow/g,
/::content/g,
// Deprecated selectors
/\/shadow-deep\//g,
/\/shadow\//g,
];
// The deep combinator is deprecated in the CSS spec
// Support for `>>>`, `deep`, `::ng-deep` is then also deprecated and will be removed in the future.
// see https://github.com/angular/angular/pull/17677
const _shadowDeepSelectors = /(?:>>>)|(?:\/deep\/)|(?:::ng-deep)/g;
const _selectorReSuffix = '([>\\s~+\[.,{:][\\s\\S]*)?$';
const _polyfillHostRe = /-shadowcsshost/gim;
const _colonHostRe = /:host/gim;
const _colonHostContextRe = /:host-context/gim;
const _commentRe = /\/\*\s*[\s\S]*?\*\//g;
function stripComments(input: string): string {
return input.replace(_commentRe, '');
}
// all comments except inline source mapping
const _sourceMappingUrlRe = /\/\*\s*#\s*sourceMappingURL=[\s\S]+?\*\//;
function extractSourceMappingUrl(input: string): string {
const matcher = input.match(_sourceMappingUrlRe);
return matcher ? matcher[0] : '';
}
const _ruleRe = /(\s*)([^;\{\}]+?)(\s*)((?:{%BLOCK%}?\s*;?)|(?:\s*;))/g;
const _curlyRe = /([{}])/g;
const OPEN_CURLY = '{';
const CLOSE_CURLY = '}';
const BLOCK_PLACEHOLDER = '%BLOCK%';
export class CssRule {
constructor(public selector: string, public content: string) {}
}
export function processRules(input: string, ruleCallback: (rule: CssRule) => CssRule): string {
const inputWithEscapedBlocks = escapeBlocks(input);
let nextBlockIndex = 0;
return inputWithEscapedBlocks.escapedString.replace(_ruleRe, function(...m: string[]) {
const selector = m[2];
let content = '';
let suffix = m[4];
let contentPrefix = '';
if (suffix && suffix.startsWith('{' + BLOCK_PLACEHOLDER)) {
content = inputWithEscapedBlocks.blocks[nextBlockIndex++];
suffix = suffix.substring(BLOCK_PLACEHOLDER.length + 1);
contentPrefix = '{';
}
const rule = ruleCallback(new CssRule(selector, content));
return `${m[1]}${rule.selector}${m[3]}${contentPrefix}${rule.content}${suffix}`;
});
}
class StringWithEscapedBlocks {
constructor(public escapedString: string, public blocks: string[]) {}
}
function escapeBlocks(input: string): StringWithEscapedBlocks {
const inputParts = input.split(_curlyRe);
const resultParts: string[] = [];
const escapedBlocks: string[] = [];
let bracketCount = 0;
let currentBlockParts: string[] = [];
for (let partIndex = 0; partIndex < inputParts.length; partIndex++) {
const part = inputParts[partIndex];
if (part == CLOSE_CURLY) {
bracketCount--;
}
if (bracketCount > 0) {
currentBlockParts.push(part);
} else {
if (currentBlockParts.length > 0) {
escapedBlocks.push(currentBlockParts.join(''));
resultParts.push(BLOCK_PLACEHOLDER);
currentBlockParts = [];
}
resultParts.push(part);
}
if (part == OPEN_CURLY) {
bracketCount++;
}
}
if (currentBlockParts.length > 0) {
escapedBlocks.push(currentBlockParts.join(''));
resultParts.push(BLOCK_PLACEHOLDER);
}
return new StringWithEscapedBlocks(resultParts.join(''), escapedBlocks);
}
| packages/compiler/src/shadow_css.ts | 1 | https://github.com/angular/angular/commit/5f681f9745077a261c7e316fbcec9415011361ba | [
0.9982151985168457,
0.08222723007202148,
0.00016384014452341944,
0.00017263977497350425,
0.27029654383659363
] |
{
"id": 3,
"code_window": [
"\n",
"function extractSourceMappingUrl(input: string): string {\n",
" const matcher = input.match(_sourceMappingUrlRe);\n",
" return matcher ? matcher[0] : '';\n",
"}\n",
"\n",
"const _ruleRe = /(\\s*)([^;\\{\\}]+?)(\\s*)((?:{%BLOCK%}?\\s*;?)|(?:\\s*;))/g;\n",
"const _curlyRe = /([{}])/g;\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"function extractCommentsWithHash(input: string): string[] {\n",
" return input.match(_commentWithHashRe) || [];\n"
],
"file_path": "packages/compiler/src/shadow_css.ts",
"type": "replace",
"edit_start_line_idx": 549
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Component} from '@angular/core';
import {SerializerTypes, ServiceMessageBrokerFactory} from '@angular/platform-webworker';
const ECHO_CHANNEL = 'ECHO';
@Component({selector: 'app', template: '<h1>WebWorker MessageBroker Test</h1>'})
export class App {
constructor(private _serviceBrokerFactory: ServiceMessageBrokerFactory) {
const broker = _serviceBrokerFactory.createMessageBroker(ECHO_CHANNEL, false);
broker.registerMethod(
'echo', [SerializerTypes.PRIMITIVE], this._echo, SerializerTypes.PRIMITIVE);
}
private _echo(val: string) { return new Promise((res) => res(val)); }
}
| modules/playground/src/web_workers/message_broker/index_common.ts | 0 | https://github.com/angular/angular/commit/5f681f9745077a261c7e316fbcec9415011361ba | [
0.0001762165775289759,
0.00017164833843708038,
0.00016780546866357327,
0.00017092295456677675,
0.000003471917807473801
] |
{
"id": 3,
"code_window": [
"\n",
"function extractSourceMappingUrl(input: string): string {\n",
" const matcher = input.match(_sourceMappingUrlRe);\n",
" return matcher ? matcher[0] : '';\n",
"}\n",
"\n",
"const _ruleRe = /(\\s*)([^;\\{\\}]+?)(\\s*)((?:{%BLOCK%}?\\s*;?)|(?:\\s*;))/g;\n",
"const _curlyRe = /([{}])/g;\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"function extractCommentsWithHash(input: string): string[] {\n",
" return input.match(_commentWithHashRe) || [];\n"
],
"file_path": "packages/compiler/src/shadow_css.ts",
"type": "replace",
"edit_start_line_idx": 549
} | <!DOCTYPE html>
<html lang="en">
<head>
<title>Hierarchical Injectors</title>
<base href="/">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<app-root></app-root>
</body>
</html>
| aio/content/examples/hierarchical-dependency-injection/src/index.html | 0 | https://github.com/angular/angular/commit/5f681f9745077a261c7e316fbcec9415011361ba | [
0.00017275231948588043,
0.00017115037189796567,
0.00016954843886196613,
0.00017115037189796567,
0.0000016019403119571507
] |
{
"id": 3,
"code_window": [
"\n",
"function extractSourceMappingUrl(input: string): string {\n",
" const matcher = input.match(_sourceMappingUrlRe);\n",
" return matcher ? matcher[0] : '';\n",
"}\n",
"\n",
"const _ruleRe = /(\\s*)([^;\\{\\}]+?)(\\s*)((?:{%BLOCK%}?\\s*;?)|(?:\\s*;))/g;\n",
"const _curlyRe = /([{}])/g;\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"function extractCommentsWithHash(input: string): string[] {\n",
" return input.match(_commentWithHashRe) || [];\n"
],
"file_path": "packages/compiler/src/shadow_css.ts",
"type": "replace",
"edit_start_line_idx": 549
} | // Imports
import {getEnvVar} from '../common/utils';
import {BuildVerifier} from './build-verifier';
// Run
_main();
// Functions
function _main() {
const secret = 'unused';
const githubToken = getEnvVar('AIO_GITHUB_TOKEN');
const repoSlug = getEnvVar('AIO_REPO_SLUG');
const organization = getEnvVar('AIO_GITHUB_ORGANIZATION');
const allowedTeamSlugs = getEnvVar('AIO_GITHUB_TEAM_SLUGS').split(',');
const trustedPrLabel = getEnvVar('AIO_TRUSTED_PR_LABEL');
const pr = +getEnvVar('AIO_PREVERIFY_PR');
const buildVerifier = new BuildVerifier(secret, githubToken, repoSlug, organization, allowedTeamSlugs,
trustedPrLabel);
// Exit codes:
// - 0: The PR can be automatically trusted (i.e. author belongs to trusted team or PR has the "trusted PR" label).
// - 1: An error occurred.
// - 2: The PR cannot be automatically trusted.
buildVerifier.getPrIsTrusted(pr).
then(isTrusted => {
if (!isTrusted) {
console.warn(
`The PR cannot be automatically verified, because it doesn't have the "${trustedPrLabel}" label and the ` +
`the author is not an active member of any of the following teams: ${allowedTeamSlugs.join(', ')}`);
}
process.exit(isTrusted ? 0 : 2);
}).
catch(err => {
console.error(err);
process.exit(1);
});
}
| aio/aio-builds-setup/dockerbuild/scripts-js/lib/upload-server/index-preverify-pr.ts | 0 | https://github.com/angular/angular/commit/5f681f9745077a261c7e316fbcec9415011361ba | [
0.00017663798644207418,
0.00017484197451267391,
0.00017231029050890356,
0.0001752098323777318,
0.0000015876917132118251
] |
{
"id": 4,
"code_window": [
" expect(s('b {c}/*# sourceMappingURL=data:x */', 'contenta'))\n",
" .toEqual('b[contenta] {c}/*# sourceMappingURL=data:x */');\n",
" expect(s('b {c}/* #sourceMappingURL=data:x */', 'contenta'))\n",
" .toEqual('b[contenta] {c}/* #sourceMappingURL=data:x */');\n",
" });\n",
" });\n",
"\n",
" describe('processRules', () => {\n",
" describe('parse rules', () => {\n",
" function captureRules(input: string): CssRule[] {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" it('should keep sourceURL comments', () => {\n",
" expect(s('/*# sourceMappingURL=data:x */b {c}/*# sourceURL=xxx */', 'contenta'))\n",
" .toEqual('b[contenta] {c}/*# sourceMappingURL=data:x *//*# sourceURL=xxx */');\n",
" });\n"
],
"file_path": "packages/compiler/test/shadow_css_spec.ts",
"type": "add",
"edit_start_line_idx": 302
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* This file is a port of shadowCSS from webcomponents.js to TypeScript.
*
* Please make sure to keep to edits in sync with the source file.
*
* Source:
* https://github.com/webcomponents/webcomponentsjs/blob/4efecd7e0e/src/ShadowCSS/ShadowCSS.js
*
* The original file level comment is reproduced below
*/
/*
This is a limited shim for ShadowDOM css styling.
https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/shadow/index.html#styles
The intention here is to support only the styling features which can be
relatively simply implemented. The goal is to allow users to avoid the
most obvious pitfalls and do so without compromising performance significantly.
For ShadowDOM styling that's not covered here, a set of best practices
can be provided that should allow users to accomplish more complex styling.
The following is a list of specific ShadowDOM styling features and a brief
discussion of the approach used to shim.
Shimmed features:
* :host, :host-context: ShadowDOM allows styling of the shadowRoot's host
element using the :host rule. To shim this feature, the :host styles are
reformatted and prefixed with a given scope name and promoted to a
document level stylesheet.
For example, given a scope name of .foo, a rule like this:
:host {
background: red;
}
}
becomes:
.foo {
background: red;
}
* encapsulation: Styles defined within ShadowDOM, apply only to
dom inside the ShadowDOM. Polymer uses one of two techniques to implement
this feature.
By default, rules are prefixed with the host element tag name
as a descendant selector. This ensures styling does not leak out of the 'top'
of the element's ShadowDOM. For example,
div {
font-weight: bold;
}
becomes:
x-foo div {
font-weight: bold;
}
becomes:
Alternatively, if WebComponents.ShadowCSS.strictStyling is set to true then
selectors are scoped by adding an attribute selector suffix to each
simple selector that contains the host element tag name. Each element
in the element's ShadowDOM template is also given the scope attribute.
Thus, these rules match only elements that have the scope attribute.
For example, given a scope name of x-foo, a rule like this:
div {
font-weight: bold;
}
becomes:
div[x-foo] {
font-weight: bold;
}
Note that elements that are dynamically added to a scope must have the scope
selector added to them manually.
* upper/lower bound encapsulation: Styles which are defined outside a
shadowRoot should not cross the ShadowDOM boundary and should not apply
inside a shadowRoot.
This styling behavior is not emulated. Some possible ways to do this that
were rejected due to complexity and/or performance concerns include: (1) reset
every possible property for every possible selector for a given scope name;
(2) re-implement css in javascript.
As an alternative, users should make sure to use selectors
specific to the scope in which they are working.
* ::distributed: This behavior is not emulated. It's often not necessary
to style the contents of a specific insertion point and instead, descendants
of the host element can be styled selectively. Users can also create an
extra node around an insertion point and style that node's contents
via descendent selectors. For example, with a shadowRoot like this:
<style>
::content(div) {
background: red;
}
</style>
<content></content>
could become:
<style>
/ *@polyfill .content-container div * /
::content(div) {
background: red;
}
</style>
<div class="content-container">
<content></content>
</div>
Note the use of @polyfill in the comment above a ShadowDOM specific style
declaration. This is a directive to the styling shim to use the selector
in comments in lieu of the next selector when running under polyfill.
*/
export class ShadowCss {
strictStyling: boolean = true;
constructor() {}
/*
* Shim some cssText with the given selector. Returns cssText that can
* be included in the document via WebComponents.ShadowCSS.addCssToDocument(css).
*
* When strictStyling is true:
* - selector is the attribute added to all elements inside the host,
* - hostSelector is the attribute added to the host itself.
*/
shimCssText(cssText: string, selector: string, hostSelector: string = ''): string {
const sourceMappingUrl: string = extractSourceMappingUrl(cssText);
cssText = stripComments(cssText);
cssText = this._insertDirectives(cssText);
return this._scopeCssText(cssText, selector, hostSelector) + sourceMappingUrl;
}
private _insertDirectives(cssText: string): string {
cssText = this._insertPolyfillDirectivesInCssText(cssText);
return this._insertPolyfillRulesInCssText(cssText);
}
/*
* Process styles to convert native ShadowDOM rules that will trip
* up the css parser; we rely on decorating the stylesheet with inert rules.
*
* For example, we convert this rule:
*
* polyfill-next-selector { content: ':host menu-item'; }
* ::content menu-item {
*
* to this:
*
* scopeName menu-item {
*
**/
private _insertPolyfillDirectivesInCssText(cssText: string): string {
// Difference with webcomponents.js: does not handle comments
return cssText.replace(
_cssContentNextSelectorRe, function(...m: string[]) { return m[2] + '{'; });
}
/*
* Process styles to add rules which will only apply under the polyfill
*
* For example, we convert this rule:
*
* polyfill-rule {
* content: ':host menu-item';
* ...
* }
*
* to this:
*
* scopeName menu-item {...}
*
**/
private _insertPolyfillRulesInCssText(cssText: string): string {
// Difference with webcomponents.js: does not handle comments
return cssText.replace(_cssContentRuleRe, (...m: string[]) => {
const rule = m[0].replace(m[1], '').replace(m[2], '');
return m[4] + rule;
});
}
/* Ensure styles are scoped. Pseudo-scoping takes a rule like:
*
* .foo {... }
*
* and converts this to
*
* scopeName .foo { ... }
*/
private _scopeCssText(cssText: string, scopeSelector: string, hostSelector: string): string {
const unscopedRules = this._extractUnscopedRulesFromCssText(cssText);
// replace :host and :host-context -shadowcsshost and -shadowcsshost respectively
cssText = this._insertPolyfillHostInCssText(cssText);
cssText = this._convertColonHost(cssText);
cssText = this._convertColonHostContext(cssText);
cssText = this._convertShadowDOMSelectors(cssText);
if (scopeSelector) {
cssText = this._scopeSelectors(cssText, scopeSelector, hostSelector);
}
cssText = cssText + '\n' + unscopedRules;
return cssText.trim();
}
/*
* Process styles to add rules which will only apply under the polyfill
* and do not process via CSSOM. (CSSOM is destructive to rules on rare
* occasions, e.g. -webkit-calc on Safari.)
* For example, we convert this rule:
*
* @polyfill-unscoped-rule {
* content: 'menu-item';
* ... }
*
* to this:
*
* menu-item {...}
*
**/
private _extractUnscopedRulesFromCssText(cssText: string): string {
// Difference with webcomponents.js: does not handle comments
let r = '';
let m: RegExpExecArray|null;
_cssContentUnscopedRuleRe.lastIndex = 0;
while ((m = _cssContentUnscopedRuleRe.exec(cssText)) !== null) {
const rule = m[0].replace(m[2], '').replace(m[1], m[4]);
r += rule + '\n\n';
}
return r;
}
/*
* convert a rule like :host(.foo) > .bar { }
*
* to
*
* .foo<scopeName> > .bar
*/
private _convertColonHost(cssText: string): string {
return this._convertColonRule(cssText, _cssColonHostRe, this._colonHostPartReplacer);
}
/*
* convert a rule like :host-context(.foo) > .bar { }
*
* to
*
* .foo<scopeName> > .bar, .foo scopeName > .bar { }
*
* and
*
* :host-context(.foo:host) .bar { ... }
*
* to
*
* .foo<scopeName> .bar { ... }
*/
private _convertColonHostContext(cssText: string): string {
return this._convertColonRule(
cssText, _cssColonHostContextRe, this._colonHostContextPartReplacer);
}
private _convertColonRule(cssText: string, regExp: RegExp, partReplacer: Function): string {
// m[1] = :host(-context), m[2] = contents of (), m[3] rest of rule
return cssText.replace(regExp, function(...m: string[]) {
if (m[2]) {
const parts = m[2].split(',');
const r: string[] = [];
for (let i = 0; i < parts.length; i++) {
const p = parts[i].trim();
if (!p) break;
r.push(partReplacer(_polyfillHostNoCombinator, p, m[3]));
}
return r.join(',');
} else {
return _polyfillHostNoCombinator + m[3];
}
});
}
private _colonHostContextPartReplacer(host: string, part: string, suffix: string): string {
if (part.indexOf(_polyfillHost) > -1) {
return this._colonHostPartReplacer(host, part, suffix);
} else {
return host + part + suffix + ', ' + part + ' ' + host + suffix;
}
}
private _colonHostPartReplacer(host: string, part: string, suffix: string): string {
return host + part.replace(_polyfillHost, '') + suffix;
}
/*
* Convert combinators like ::shadow and pseudo-elements like ::content
* by replacing with space.
*/
private _convertShadowDOMSelectors(cssText: string): string {
return _shadowDOMSelectorsRe.reduce((result, pattern) => result.replace(pattern, ' '), cssText);
}
// change a selector like 'div' to 'name div'
private _scopeSelectors(cssText: string, scopeSelector: string, hostSelector: string): string {
return processRules(cssText, (rule: CssRule) => {
let selector = rule.selector;
let content = rule.content;
if (rule.selector[0] != '@') {
selector =
this._scopeSelector(rule.selector, scopeSelector, hostSelector, this.strictStyling);
} else if (
rule.selector.startsWith('@media') || rule.selector.startsWith('@supports') ||
rule.selector.startsWith('@page') || rule.selector.startsWith('@document')) {
content = this._scopeSelectors(rule.content, scopeSelector, hostSelector);
}
return new CssRule(selector, content);
});
}
private _scopeSelector(
selector: string, scopeSelector: string, hostSelector: string, strict: boolean): string {
return selector.split(',')
.map(part => part.trim().split(_shadowDeepSelectors))
.map((deepParts) => {
const [shallowPart, ...otherParts] = deepParts;
const applyScope = (shallowPart: string) => {
if (this._selectorNeedsScoping(shallowPart, scopeSelector)) {
return strict ?
this._applyStrictSelectorScope(shallowPart, scopeSelector, hostSelector) :
this._applySelectorScope(shallowPart, scopeSelector, hostSelector);
} else {
return shallowPart;
}
};
return [applyScope(shallowPart), ...otherParts].join(' ');
})
.join(', ');
}
private _selectorNeedsScoping(selector: string, scopeSelector: string): boolean {
const re = this._makeScopeMatcher(scopeSelector);
return !re.test(selector);
}
private _makeScopeMatcher(scopeSelector: string): RegExp {
const lre = /\[/g;
const rre = /\]/g;
scopeSelector = scopeSelector.replace(lre, '\\[').replace(rre, '\\]');
return new RegExp('^(' + scopeSelector + ')' + _selectorReSuffix, 'm');
}
private _applySelectorScope(selector: string, scopeSelector: string, hostSelector: string):
string {
// Difference from webcomponents.js: scopeSelector could not be an array
return this._applySimpleSelectorScope(selector, scopeSelector, hostSelector);
}
// scope via name and [is=name]
private _applySimpleSelectorScope(selector: string, scopeSelector: string, hostSelector: string):
string {
// In Android browser, the lastIndex is not reset when the regex is used in String.replace()
_polyfillHostRe.lastIndex = 0;
if (_polyfillHostRe.test(selector)) {
const replaceBy = this.strictStyling ? `[${hostSelector}]` : scopeSelector;
return selector
.replace(
_polyfillHostNoCombinatorRe,
(hnc, selector) => {
return selector.replace(
/([^:]*)(:*)(.*)/,
(_: string, before: string, colon: string, after: string) => {
return before + replaceBy + colon + after;
});
})
.replace(_polyfillHostRe, replaceBy + ' ');
}
return scopeSelector + ' ' + selector;
}
// return a selector with [name] suffix on each simple selector
// e.g. .foo.bar > .zot becomes .foo[name].bar[name] > .zot[name] /** @internal */
private _applyStrictSelectorScope(selector: string, scopeSelector: string, hostSelector: string):
string {
const isRe = /\[is=([^\]]*)\]/g;
scopeSelector = scopeSelector.replace(isRe, (_: string, ...parts: string[]) => parts[0]);
const attrName = '[' + scopeSelector + ']';
const _scopeSelectorPart = (p: string) => {
let scopedP = p.trim();
if (!scopedP) {
return '';
}
if (p.indexOf(_polyfillHostNoCombinator) > -1) {
scopedP = this._applySimpleSelectorScope(p, scopeSelector, hostSelector);
} else {
// remove :host since it should be unnecessary
const t = p.replace(_polyfillHostRe, '');
if (t.length > 0) {
const matches = t.match(/([^:]*)(:*)(.*)/);
if (matches) {
scopedP = matches[1] + attrName + matches[2] + matches[3];
}
}
}
return scopedP;
};
const safeContent = new SafeSelector(selector);
selector = safeContent.content();
let scopedSelector = '';
let startIndex = 0;
let res: RegExpExecArray|null;
const sep = /( |>|\+|~(?!=))\s*/g;
// If a selector appears before :host it should not be shimmed as it
// matches on ancestor elements and not on elements in the host's shadow
// `:host-context(div)` is transformed to
// `-shadowcsshost-no-combinatordiv, div -shadowcsshost-no-combinator`
// the `div` is not part of the component in the 2nd selectors and should not be scoped.
// Historically `component-tag:host` was matching the component so we also want to preserve
// this behavior to avoid breaking legacy apps (it should not match).
// The behavior should be:
// - `tag:host` -> `tag[h]` (this is to avoid breaking legacy apps, should not match anything)
// - `tag :host` -> `tag [h]` (`tag` is not scoped because it's considered part of a
// `:host-context(tag)`)
const hasHost = selector.indexOf(_polyfillHostNoCombinator) > -1;
// Only scope parts after the first `-shadowcsshost-no-combinator` when it is present
let shouldScope = !hasHost;
while ((res = sep.exec(selector)) !== null) {
const separator = res[1];
const part = selector.slice(startIndex, res.index).trim();
shouldScope = shouldScope || part.indexOf(_polyfillHostNoCombinator) > -1;
const scopedPart = shouldScope ? _scopeSelectorPart(part) : part;
scopedSelector += `${scopedPart} ${separator} `;
startIndex = sep.lastIndex;
}
const part = selector.substring(startIndex);
shouldScope = shouldScope || part.indexOf(_polyfillHostNoCombinator) > -1;
scopedSelector += shouldScope ? _scopeSelectorPart(part) : part;
// replace the placeholders with their original values
return safeContent.restore(scopedSelector);
}
private _insertPolyfillHostInCssText(selector: string): string {
return selector.replace(_colonHostContextRe, _polyfillHostContext)
.replace(_colonHostRe, _polyfillHost);
}
}
class SafeSelector {
private placeholders: string[] = [];
private index = 0;
private _content: string;
constructor(selector: string) {
// Replaces attribute selectors with placeholders.
// The WS in [attr="va lue"] would otherwise be interpreted as a selector separator.
selector = selector.replace(/(\[[^\]]*\])/g, (_, keep) => {
const replaceBy = `__ph-${this.index}__`;
this.placeholders.push(keep);
this.index++;
return replaceBy;
});
// Replaces the expression in `:nth-child(2n + 1)` with a placeholder.
// WS and "+" would otherwise be interpreted as selector separators.
this._content = selector.replace(/(:nth-[-\w]+)(\([^)]+\))/g, (_, pseudo, exp) => {
const replaceBy = `__ph-${this.index}__`;
this.placeholders.push(exp);
this.index++;
return pseudo + replaceBy;
});
}
restore(content: string): string {
return content.replace(/__ph-(\d+)__/g, (ph, index) => this.placeholders[+index]);
}
content(): string { return this._content; }
}
const _cssContentNextSelectorRe =
/polyfill-next-selector[^}]*content:[\s]*?(['"])(.*?)\1[;\s]*}([^{]*?){/gim;
const _cssContentRuleRe = /(polyfill-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim;
const _cssContentUnscopedRuleRe =
/(polyfill-unscoped-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim;
const _polyfillHost = '-shadowcsshost';
// note: :host-context pre-processed to -shadowcsshostcontext.
const _polyfillHostContext = '-shadowcsscontext';
const _parenSuffix = ')(?:\\((' +
'(?:\\([^)(]*\\)|[^)(]*)+?' +
')\\))?([^,{]*)';
const _cssColonHostRe = new RegExp('(' + _polyfillHost + _parenSuffix, 'gim');
const _cssColonHostContextRe = new RegExp('(' + _polyfillHostContext + _parenSuffix, 'gim');
const _polyfillHostNoCombinator = _polyfillHost + '-no-combinator';
const _polyfillHostNoCombinatorRe = /-shadowcsshost-no-combinator([^\s]*)/;
const _shadowDOMSelectorsRe = [
/::shadow/g,
/::content/g,
// Deprecated selectors
/\/shadow-deep\//g,
/\/shadow\//g,
];
// The deep combinator is deprecated in the CSS spec
// Support for `>>>`, `deep`, `::ng-deep` is then also deprecated and will be removed in the future.
// see https://github.com/angular/angular/pull/17677
const _shadowDeepSelectors = /(?:>>>)|(?:\/deep\/)|(?:::ng-deep)/g;
const _selectorReSuffix = '([>\\s~+\[.,{:][\\s\\S]*)?$';
const _polyfillHostRe = /-shadowcsshost/gim;
const _colonHostRe = /:host/gim;
const _colonHostContextRe = /:host-context/gim;
const _commentRe = /\/\*\s*[\s\S]*?\*\//g;
function stripComments(input: string): string {
return input.replace(_commentRe, '');
}
// all comments except inline source mapping
const _sourceMappingUrlRe = /\/\*\s*#\s*sourceMappingURL=[\s\S]+?\*\//;
function extractSourceMappingUrl(input: string): string {
const matcher = input.match(_sourceMappingUrlRe);
return matcher ? matcher[0] : '';
}
const _ruleRe = /(\s*)([^;\{\}]+?)(\s*)((?:{%BLOCK%}?\s*;?)|(?:\s*;))/g;
const _curlyRe = /([{}])/g;
const OPEN_CURLY = '{';
const CLOSE_CURLY = '}';
const BLOCK_PLACEHOLDER = '%BLOCK%';
export class CssRule {
constructor(public selector: string, public content: string) {}
}
export function processRules(input: string, ruleCallback: (rule: CssRule) => CssRule): string {
const inputWithEscapedBlocks = escapeBlocks(input);
let nextBlockIndex = 0;
return inputWithEscapedBlocks.escapedString.replace(_ruleRe, function(...m: string[]) {
const selector = m[2];
let content = '';
let suffix = m[4];
let contentPrefix = '';
if (suffix && suffix.startsWith('{' + BLOCK_PLACEHOLDER)) {
content = inputWithEscapedBlocks.blocks[nextBlockIndex++];
suffix = suffix.substring(BLOCK_PLACEHOLDER.length + 1);
contentPrefix = '{';
}
const rule = ruleCallback(new CssRule(selector, content));
return `${m[1]}${rule.selector}${m[3]}${contentPrefix}${rule.content}${suffix}`;
});
}
class StringWithEscapedBlocks {
constructor(public escapedString: string, public blocks: string[]) {}
}
function escapeBlocks(input: string): StringWithEscapedBlocks {
const inputParts = input.split(_curlyRe);
const resultParts: string[] = [];
const escapedBlocks: string[] = [];
let bracketCount = 0;
let currentBlockParts: string[] = [];
for (let partIndex = 0; partIndex < inputParts.length; partIndex++) {
const part = inputParts[partIndex];
if (part == CLOSE_CURLY) {
bracketCount--;
}
if (bracketCount > 0) {
currentBlockParts.push(part);
} else {
if (currentBlockParts.length > 0) {
escapedBlocks.push(currentBlockParts.join(''));
resultParts.push(BLOCK_PLACEHOLDER);
currentBlockParts = [];
}
resultParts.push(part);
}
if (part == OPEN_CURLY) {
bracketCount++;
}
}
if (currentBlockParts.length > 0) {
escapedBlocks.push(currentBlockParts.join(''));
resultParts.push(BLOCK_PLACEHOLDER);
}
return new StringWithEscapedBlocks(resultParts.join(''), escapedBlocks);
}
| packages/compiler/src/shadow_css.ts | 1 | https://github.com/angular/angular/commit/5f681f9745077a261c7e316fbcec9415011361ba | [
0.0046891518868505955,
0.0002759136841632426,
0.000162918382557109,
0.0001735404075589031,
0.0006001621368341148
] |
{
"id": 4,
"code_window": [
" expect(s('b {c}/*# sourceMappingURL=data:x */', 'contenta'))\n",
" .toEqual('b[contenta] {c}/*# sourceMappingURL=data:x */');\n",
" expect(s('b {c}/* #sourceMappingURL=data:x */', 'contenta'))\n",
" .toEqual('b[contenta] {c}/* #sourceMappingURL=data:x */');\n",
" });\n",
" });\n",
"\n",
" describe('processRules', () => {\n",
" describe('parse rules', () => {\n",
" function captureRules(input: string): CssRule[] {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" it('should keep sourceURL comments', () => {\n",
" expect(s('/*# sourceMappingURL=data:x */b {c}/*# sourceURL=xxx */', 'contenta'))\n",
" .toEqual('b[contenta] {c}/*# sourceMappingURL=data:x *//*# sourceURL=xxx */');\n",
" });\n"
],
"file_path": "packages/compiler/test/shadow_css_spec.ts",
"type": "add",
"edit_start_line_idx": 302
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/* tslint:disable:no-console */
// #docregion Component
import {Component} from '@angular/core';
import {FormArray, FormControl, FormGroup} from '@angular/forms';
@Component({
selector: 'example-app',
template: `
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div formArrayName="cities">
<div *ngFor="let city of cities.controls; index as i">
<input [formControlName]="i" placeholder="City">
</div>
</div>
<button>Submit</button>
</form>
<button (click)="addCity()">Add City</button>
<button (click)="setPreset()">Set preset</button>
`,
})
export class NestedFormArray {
form = new FormGroup({
cities: new FormArray([
new FormControl('SF'),
new FormControl('NY'),
]),
});
get cities(): FormArray { return this.form.get('cities') as FormArray; }
addCity() { this.cities.push(new FormControl()); }
onSubmit() {
console.log(this.cities.value); // ['SF', 'NY']
console.log(this.form.value); // { cities: ['SF', 'NY'] }
}
setPreset() { this.cities.patchValue(['LA', 'MTV']); }
}
// #enddocregion
| packages/examples/forms/ts/nestedFormArray/nested_form_array_example.ts | 0 | https://github.com/angular/angular/commit/5f681f9745077a261c7e316fbcec9415011361ba | [
0.00017796814790926874,
0.0001752579992171377,
0.0001727292692521587,
0.00017387125990353525,
0.0000022451979475590633
] |
{
"id": 4,
"code_window": [
" expect(s('b {c}/*# sourceMappingURL=data:x */', 'contenta'))\n",
" .toEqual('b[contenta] {c}/*# sourceMappingURL=data:x */');\n",
" expect(s('b {c}/* #sourceMappingURL=data:x */', 'contenta'))\n",
" .toEqual('b[contenta] {c}/* #sourceMappingURL=data:x */');\n",
" });\n",
" });\n",
"\n",
" describe('processRules', () => {\n",
" describe('parse rules', () => {\n",
" function captureRules(input: string): CssRule[] {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" it('should keep sourceURL comments', () => {\n",
" expect(s('/*# sourceMappingURL=data:x */b {c}/*# sourceURL=xxx */', 'contenta'))\n",
" .toEqual('b[contenta] {c}/*# sourceMappingURL=data:x *//*# sourceURL=xxx */');\n",
" });\n"
],
"file_path": "packages/compiler/test/shadow_css_spec.ts",
"type": "add",
"edit_start_line_idx": 302
} | /**
* Copyright (c) 2016, Tiernan Cridland
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with or without
* fee is hereby
* granted, provided that the above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
* SOFTWARE INCLUDING ALL
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*
* Typings for Service Worker
* @author Tiernan Cridland
* @email [email protected]
* @license: ISC
*/
interface ExtendableEvent extends Event {
waitUntil(fn: Promise<any>): void;
}
// Client API
declare class Client {
frameType: ClientFrameType;
id: string;
url: string;
postMessage(message: any): void;
}
interface Clients {
claim(): Promise<any>;
get(id: string): Promise<Client>;
matchAll(options?: ClientMatchOptions): Promise<Array<Client>>;
}
interface ClientMatchOptions {
includeUncontrolled?: boolean;
type?: ClientMatchTypes;
}
interface WindowClient {
focused: boolean;
visibilityState: WindowClientState;
focus(): Promise<WindowClient>;
navigate(url: string): Promise<WindowClient>;
}
type ClientFrameType = 'auxiliary' | 'top-level' | 'nested' | 'none';
type ClientMatchTypes = 'window' | 'worker' | 'sharedworker' | 'all';
type WindowClientState = 'hidden' | 'visible' | 'prerender' | 'unloaded';
// Fetch API
interface FetchEvent extends ExtendableEvent {
clientId: string|null;
request: Request;
respondWith(response: Promise<Response>|Response): Promise<Response>;
}
interface InstallEvent extends ExtendableEvent {
activeWorker: ServiceWorker;
}
interface ActivateEvent extends ExtendableEvent {}
// Notification API
interface NotificationEvent {
action: string;
notification: Notification;
}
// Push API
interface PushEvent extends ExtendableEvent {
data: PushMessageData;
}
interface PushMessageData {
arrayBuffer(): ArrayBuffer;
blob(): Blob;
json(): any;
text(): string;
}
// Sync API
interface SyncEvent extends ExtendableEvent {
lastChance: boolean;
tag: string;
}
interface ExtendableMessageEvent extends ExtendableEvent {
data: any;
source: Client|Object;
}
// ServiceWorkerGlobalScope
interface ServiceWorkerGlobalScope {
caches: CacheStorage;
clients: Clients;
registration: ServiceWorkerRegistration;
addEventListener(event: 'activate', fn: (event?: ExtendableEvent) => any): void;
addEventListener(event: 'message', fn: (event?: ExtendableMessageEvent) => any): void;
addEventListener(event: 'fetch', fn: (event?: FetchEvent) => any): void;
addEventListener(event: 'install', fn: (event?: ExtendableEvent) => any): void;
addEventListener(event: 'push', fn: (event?: PushEvent) => any): void;
addEventListener(event: 'sync', fn: (event?: SyncEvent) => any): void;
fetch(request: Request|string): Promise<Response>;
skipWaiting(): Promise<void>;
}
| packages/service-worker/worker/src/service-worker.d.ts | 0 | https://github.com/angular/angular/commit/5f681f9745077a261c7e316fbcec9415011361ba | [
0.00017726242367643863,
0.00017284092609770596,
0.0001663622388150543,
0.0001736567064654082,
0.000003105566975136753
] |
{
"id": 4,
"code_window": [
" expect(s('b {c}/*# sourceMappingURL=data:x */', 'contenta'))\n",
" .toEqual('b[contenta] {c}/*# sourceMappingURL=data:x */');\n",
" expect(s('b {c}/* #sourceMappingURL=data:x */', 'contenta'))\n",
" .toEqual('b[contenta] {c}/* #sourceMappingURL=data:x */');\n",
" });\n",
" });\n",
"\n",
" describe('processRules', () => {\n",
" describe('parse rules', () => {\n",
" function captureRules(input: string): CssRule[] {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" it('should keep sourceURL comments', () => {\n",
" expect(s('/*# sourceMappingURL=data:x */b {c}/*# sourceURL=xxx */', 'contenta'))\n",
" .toEqual('b[contenta] {c}/*# sourceMappingURL=data:x *//*# sourceURL=xxx */');\n",
" });\n"
],
"file_path": "packages/compiler/test/shadow_css_spec.ts",
"type": "add",
"edit_start_line_idx": 302
} | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var kLogsArgument = /^--logs\s*=\s*(.+?)$/;
var kTrimLeft = /^\s+/;
var kTrimRight = /\s+$/;
var kCamelCase = /[-_\s]+(.)?/g;
var logs = findArgvLogs();
function findArgvLogs() {
for (var i = 0; i < process.argv.length; ++i) {
var match = process.argv[i].match(kLogsArgument);
if (match) {
return logsToObject(match[1]);
}
}
return null;
}
function logsToObject(logstr) {
return logstr.split(',').reduce(function(obj, key) {
key = camelize(key);
if (key.length > 0) obj[key] = true;
return obj;
}, Object.create(null));
return logs;
}
function camelize(str) {
return str.replace(kTrimLeft, '').replace(kTrimRight, '').replace(kCamelCase, function(match, c) {
return c ? c.toUpperCase() : '';
});
}
function shouldLog(str) {
if (!logs || logs.quiet) return false;
if (logs.all) return true;
return !!logs[camelize(str)];
}
module.exports = shouldLog;
| tools/build/logging.js | 0 | https://github.com/angular/angular/commit/5f681f9745077a261c7e316fbcec9415011361ba | [
0.00017585318710189313,
0.00017145686433650553,
0.00016029112157411873,
0.00017381041834596545,
0.000005684116786142113
] |
{
"id": 3,
"code_window": [
"\n",
"export class SCMAccessibilityProvider implements IListAccessibilityProvider<TreeElement> {\n",
"\n",
"\tconstructor(@ILabelService private readonly labelService: ILabelService) { }\n",
"\n",
"\tgetWidgetAriaLabel(): string {\n",
"\t\treturn localize('scm', \"Source Control Management\");\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tconstructor(\n",
"\t\t@ILabelService private readonly labelService: ILabelService,\n",
"\t\t@IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService\n",
"\t) { }\n"
],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewPane.ts",
"type": "replace",
"edit_start_line_idx": 688
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { localize } from 'vs/nls';
import { Disposable, DisposableStore, toDisposable } from 'vs/base/common/lifecycle';
import { Event, Emitter } from 'vs/base/common/event';
import { isPromiseCanceledError, getErrorMessage, createErrorWithActions } from 'vs/base/common/errors';
import { PagedModel, IPagedModel, IPager, DelayedPagedModel } from 'vs/base/common/paging';
import { SortBy, SortOrder, IQueryOptions } from 'vs/platform/extensionManagement/common/extensionManagement';
import { IExtensionManagementServer, IExtensionManagementServerService, EnablementState, IWorkbenchExtensioManagementService } from 'vs/workbench/services/extensionManagement/common/extensionManagement';
import { IExtensionRecommendationsService } from 'vs/workbench/services/extensionRecommendations/common/extensionRecommendations';
import { areSameExtensions } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { append, $ } from 'vs/base/browser/dom';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { Delegate, Renderer, IExtensionsViewState, EXTENSION_LIST_ELEMENT_HEIGHT } from 'vs/workbench/contrib/extensions/browser/extensionsList';
import { ExtensionState, IExtension, IExtensionsWorkbenchService, IWorkspaceRecommendedExtensionsView } from 'vs/workbench/contrib/extensions/common/extensions';
import { Query } from 'vs/workbench/contrib/extensions/common/extensionQuery';
import { IExtensionService, toExtension } from 'vs/workbench/services/extensions/common/extensions';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { attachBadgeStyler } from 'vs/platform/theme/common/styler';
import { IViewletViewOptions } from 'vs/workbench/browser/parts/views/viewsViewlet';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { CountBadge } from 'vs/base/browser/ui/countBadge/countBadge';
import { ManageExtensionAction, getContextMenuActions, ExtensionAction } from 'vs/workbench/contrib/extensions/browser/extensionsActions';
import { WorkbenchPagedList } from 'vs/platform/list/browser/listService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { ViewPane, IViewPaneOptions } from 'vs/workbench/browser/parts/views/viewPane';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { coalesce, distinct, flatten } from 'vs/base/common/arrays';
import { IExperimentService, IExperiment, ExperimentActionType } from 'vs/workbench/contrib/experiments/common/experimentService';
import { alert } from 'vs/base/browser/ui/aria/aria';
import { IListContextMenuEvent } from 'vs/base/browser/ui/list/list';
import { CancellationToken } from 'vs/base/common/cancellation';
import { IAction, Action, Separator, ActionRunner } from 'vs/base/common/actions';
import { ExtensionIdentifier, IExtensionDescription, isLanguagePackExtension } from 'vs/platform/extensions/common/extensions';
import { CancelablePromise, createCancelablePromise } from 'vs/base/common/async';
import { IProductService } from 'vs/platform/product/common/productService';
import { SeverityIcon } from 'vs/platform/severityIcon/common/severityIcon';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { SIDE_BAR_BACKGROUND } from 'vs/workbench/common/theme';
import { IViewDescriptorService } from 'vs/workbench/common/views';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { IPreferencesService } from 'vs/workbench/services/preferences/common/preferences';
import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
// Extensions that are automatically classified as Programming Language extensions, but should be Feature extensions
const FORCE_FEATURE_EXTENSIONS = ['vscode.git', 'vscode.search-result'];
type WorkspaceRecommendationsClassification = {
count: { classification: 'SystemMetaData', purpose: 'FeatureInsight', 'isMeasurement': true };
};
class ExtensionsViewState extends Disposable implements IExtensionsViewState {
private readonly _onFocus: Emitter<IExtension> = this._register(new Emitter<IExtension>());
readonly onFocus: Event<IExtension> = this._onFocus.event;
private readonly _onBlur: Emitter<IExtension> = this._register(new Emitter<IExtension>());
readonly onBlur: Event<IExtension> = this._onBlur.event;
private currentlyFocusedItems: IExtension[] = [];
onFocusChange(extensions: IExtension[]): void {
this.currentlyFocusedItems.forEach(extension => this._onBlur.fire(extension));
this.currentlyFocusedItems = extensions;
this.currentlyFocusedItems.forEach(extension => this._onFocus.fire(extension));
}
}
export interface ExtensionsListViewOptions {
server?: IExtensionManagementServer;
fixedHeight?: boolean;
onDidChangeTitle?: Event<string>;
}
class ExtensionListViewWarning extends Error { }
interface IQueryResult {
readonly model: IPagedModel<IExtension>;
readonly onDidChangeModel?: Event<IPagedModel<IExtension>>;
readonly disposables: DisposableStore;
}
export class ExtensionsListView extends ViewPane {
private bodyTemplate: {
messageContainer: HTMLElement;
messageSeverityIcon: HTMLElement;
messageBox: HTMLElement;
extensionsList: HTMLElement;
} | undefined;
private badge: CountBadge | undefined;
private list: WorkbenchPagedList<IExtension> | null = null;
private queryRequest: { query: string, request: CancelablePromise<IPagedModel<IExtension>> } | null = null;
private queryResult: IQueryResult | undefined;
private readonly contextMenuActionRunner = this._register(new ActionRunner());
constructor(
protected readonly options: ExtensionsListViewOptions,
viewletViewOptions: IViewletViewOptions,
@INotificationService protected notificationService: INotificationService,
@IKeybindingService keybindingService: IKeybindingService,
@IContextMenuService contextMenuService: IContextMenuService,
@IInstantiationService protected instantiationService: IInstantiationService,
@IThemeService themeService: IThemeService,
@IExtensionService private readonly extensionService: IExtensionService,
@IExtensionsWorkbenchService protected extensionsWorkbenchService: IExtensionsWorkbenchService,
@IExtensionRecommendationsService protected extensionRecommendationsService: IExtensionRecommendationsService,
@ITelemetryService telemetryService: ITelemetryService,
@IConfigurationService configurationService: IConfigurationService,
@IWorkspaceContextService protected contextService: IWorkspaceContextService,
@IExperimentService private readonly experimentService: IExperimentService,
@IExtensionManagementServerService protected readonly extensionManagementServerService: IExtensionManagementServerService,
@IWorkbenchExtensioManagementService protected readonly extensionManagementService: IWorkbenchExtensioManagementService,
@IProductService protected readonly productService: IProductService,
@IContextKeyService contextKeyService: IContextKeyService,
@IViewDescriptorService viewDescriptorService: IViewDescriptorService,
@IOpenerService openerService: IOpenerService,
@IPreferencesService private readonly preferencesService: IPreferencesService,
@IStorageService private readonly storageService: IStorageService,
) {
super({
...(viewletViewOptions as IViewPaneOptions),
showActionsAlways: true,
maximumBodySize: options.fixedHeight ? storageService.getNumber(viewletViewOptions.id, StorageScope.GLOBAL, 0) : undefined
}, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService);
if (this.options.onDidChangeTitle) {
this._register(this.options.onDidChangeTitle(title => this.updateTitle(title)));
}
this._register(this.contextMenuActionRunner.onDidRun(({ error }) => error && this.notificationService.error(error)));
this.registerActions();
}
protected registerActions(): void { }
protected renderHeader(container: HTMLElement): void {
container.classList.add('extension-view-header');
super.renderHeader(container);
this.badge = new CountBadge(append(container, $('.count-badge-wrapper')));
this._register(attachBadgeStyler(this.badge, this.themeService));
}
renderBody(container: HTMLElement): void {
super.renderBody(container);
const extensionsList = append(container, $('.extensions-list'));
const messageContainer = append(container, $('.message-container'));
const messageSeverityIcon = append(messageContainer, $(''));
const messageBox = append(messageContainer, $('.message'));
const delegate = new Delegate();
const extensionsViewState = new ExtensionsViewState();
const renderer = this.instantiationService.createInstance(Renderer, extensionsViewState);
this.list = this.instantiationService.createInstance(WorkbenchPagedList, 'Extensions', extensionsList, delegate, [renderer], {
multipleSelectionSupport: false,
setRowLineHeight: false,
horizontalScrolling: false,
accessibilityProvider: <IListAccessibilityProvider<IExtension | null>>{
getAriaLabel(extension: IExtension | null): string {
return extension ? localize('extension-arialabel', "{0}, {1}, {2}, press enter for extension details.", extension.displayName, extension.version, extension.publisherDisplayName) : '';
},
getWidgetAriaLabel(): string {
return localize('extensions', "Extensions");
}
},
overrideStyles: {
listBackground: SIDE_BAR_BACKGROUND
},
openOnSingleClick: true
}) as WorkbenchPagedList<IExtension>;
this._register(this.list.onContextMenu(e => this.onContextMenu(e), this));
this._register(this.list.onDidChangeFocus(e => extensionsViewState.onFocusChange(coalesce(e.elements)), this));
this._register(this.list);
this._register(extensionsViewState);
this._register(Event.debounce(Event.filter(this.list.onDidOpen, e => e.element !== null), (_, event) => event, 75, true)(options => {
this.openExtension(options.element!, { sideByside: options.sideBySide, ...options.editorOptions });
}));
this.bodyTemplate = {
extensionsList,
messageBox,
messageContainer,
messageSeverityIcon
};
}
protected layoutBody(height: number, width: number): void {
super.layoutBody(height, width);
if (this.bodyTemplate) {
this.bodyTemplate.extensionsList.style.height = height + 'px';
}
if (this.list) {
this.list.layout(height, width);
}
}
async show(query: string, refresh?: boolean): Promise<IPagedModel<IExtension>> {
if (this.queryRequest) {
if (!refresh && this.queryRequest.query === query) {
return this.queryRequest.request;
}
this.queryRequest.request.cancel();
this.queryRequest = null;
}
if (this.queryResult) {
this.queryResult.disposables.dispose();
this.queryResult = undefined;
}
const parsedQuery = Query.parse(query);
let options: IQueryOptions = {
sortOrder: SortOrder.Default
};
switch (parsedQuery.sortBy) {
case 'installs': options.sortBy = SortBy.InstallCount; break;
case 'rating': options.sortBy = SortBy.WeightedRating; break;
case 'name': options.sortBy = SortBy.Title; break;
case 'publishedDate': options.sortBy = SortBy.PublishedDate; break;
}
const request = createCancelablePromise(async token => {
try {
this.queryResult = await this.query(parsedQuery, options, token);
const model = this.queryResult.model;
this.setModel(model);
if (this.queryResult.onDidChangeModel) {
this.queryResult.disposables.add(this.queryResult.onDidChangeModel(model => this.updateModel(model)));
}
return model;
} catch (e) {
const model = new PagedModel([]);
if (!isPromiseCanceledError(e)) {
this.setModel(model, e);
}
return this.list ? this.list.model : model;
}
});
request.finally(() => this.queryRequest = null);
this.queryRequest = { query, request };
return request;
}
count(): number {
return this.list ? this.list.length : 0;
}
protected showEmptyModel(): Promise<IPagedModel<IExtension>> {
const emptyModel = new PagedModel([]);
this.setModel(emptyModel);
return Promise.resolve(emptyModel);
}
private async onContextMenu(e: IListContextMenuEvent<IExtension>): Promise<void> {
if (e.element) {
const runningExtensions = await this.extensionService.getExtensions();
const manageExtensionAction = this.instantiationService.createInstance(ManageExtensionAction);
manageExtensionAction.extension = e.element;
let groups: IAction[][] = [];
if (manageExtensionAction.enabled) {
groups = await manageExtensionAction.getActionGroups(runningExtensions);
} else if (e.element) {
groups = getContextMenuActions(e.element, false, this.instantiationService);
groups.forEach(group => group.forEach(extensionAction => {
if (extensionAction instanceof ExtensionAction) {
extensionAction.extension = e.element!;
}
}));
}
let actions: IAction[] = [];
for (const menuActions of groups) {
actions = [...actions, ...menuActions, new Separator()];
}
actions.pop();
this.contextMenuService.showContextMenu({
getAnchor: () => e.anchor,
getActions: () => actions,
actionRunner: this.contextMenuActionRunner,
});
}
}
private async query(query: Query, options: IQueryOptions, token: CancellationToken): Promise<IQueryResult> {
const idRegex = /@id:(([a-z0-9A-Z][a-z0-9\-A-Z]*)\.([a-z0-9A-Z][a-z0-9\-A-Z]*))/g;
const ids: string[] = [];
let idMatch;
while ((idMatch = idRegex.exec(query.value)) !== null) {
const name = idMatch[1];
ids.push(name);
}
if (ids.length) {
const model = await this.queryByIds(ids, options, token);
return { model, disposables: new DisposableStore() };
}
if (ExtensionsListView.isLocalExtensionsQuery(query.value)) {
return this.queryLocal(query, options);
}
try {
const model = await this.queryGallery(query, options, token);
return { model, disposables: new DisposableStore() };
} catch (e) {
console.warn('Error querying extensions gallery', getErrorMessage(e));
return Promise.reject(new ExtensionListViewWarning(localize('galleryError', "We cannot connect to the Extensions Marketplace at this time, please try again later.")));
}
}
private async queryByIds(ids: string[], options: IQueryOptions, token: CancellationToken): Promise<IPagedModel<IExtension>> {
const idsSet: Set<string> = ids.reduce((result, id) => { result.add(id.toLowerCase()); return result; }, new Set<string>());
const result = (await this.extensionsWorkbenchService.queryLocal(this.options.server))
.filter(e => idsSet.has(e.identifier.id.toLowerCase()));
if (result.length) {
return this.getPagedModel(this.sortExtensions(result, options));
}
return this.extensionsWorkbenchService.queryGallery({ names: ids, source: 'queryById' }, token)
.then(pager => this.getPagedModel(pager));
}
private async queryLocal(query: Query, options: IQueryOptions): Promise<IQueryResult> {
const local = await this.extensionsWorkbenchService.queryLocal(this.options.server);
const runningExtensions = await this.extensionService.getExtensions();
let { extensions, canIncludeInstalledExtensions } = this.filterLocal(local, runningExtensions, query, options);
const disposables = new DisposableStore();
const onDidChangeModel = disposables.add(new Emitter<IPagedModel<IExtension>>());
if (canIncludeInstalledExtensions) {
let isDisposed: boolean = false;
disposables.add(toDisposable(() => isDisposed = true));
disposables.add(Event.debounce(Event.any(
Event.filter(this.extensionsWorkbenchService.onChange, e => e?.state === ExtensionState.Installed),
this.extensionService.onDidChangeExtensions
), () => undefined)(async () => {
const local = this.options.server ? this.extensionsWorkbenchService.installed.filter(e => e.server === this.options.server) : this.extensionsWorkbenchService.local;
const runningExtensions = await this.extensionService.getExtensions();
const { extensions: newExtensions } = this.filterLocal(local, runningExtensions, query, options);
if (!isDisposed) {
const mergedExtensions = this.mergeAddedExtensions(extensions, newExtensions);
if (mergedExtensions) {
extensions = mergedExtensions;
onDidChangeModel.fire(new PagedModel(extensions));
}
}
}));
}
return {
model: new PagedModel(extensions),
onDidChangeModel: onDidChangeModel.event,
disposables
};
}
private filterLocal(local: IExtension[], runningExtensions: IExtensionDescription[], query: Query, options: IQueryOptions): { extensions: IExtension[], canIncludeInstalledExtensions: boolean } {
let value = query.value;
let extensions: IExtension[] = [];
let canIncludeInstalledExtensions = true;
if (/@builtin/i.test(value)) {
extensions = this.filterBuiltinExtensions(local, query, options);
canIncludeInstalledExtensions = false;
}
else if (/@installed/i.test(value)) {
extensions = this.filterInstalledExtensions(local, runningExtensions, query, options);
}
else if (/@outdated/i.test(value)) {
extensions = this.filterOutdatedExtensions(local, query, options);
}
else if (/@disabled/i.test(value)) {
extensions = this.filterDisabledExtensions(local, runningExtensions, query, options);
}
else if (/@enabled/i.test(value)) {
extensions = this.filterEnabledExtensions(local, runningExtensions, query, options);
}
return { extensions, canIncludeInstalledExtensions };
}
private filterBuiltinExtensions(local: IExtension[], query: Query, options: IQueryOptions): IExtension[] {
let value = query.value;
const showThemesOnly = /@builtin:themes/i.test(value);
if (showThemesOnly) {
value = value.replace(/@builtin:themes/g, '');
}
const showBasicsOnly = /@builtin:basics/i.test(value);
if (showBasicsOnly) {
value = value.replace(/@builtin:basics/g, '');
}
const showFeaturesOnly = /@builtin:features/i.test(value);
if (showFeaturesOnly) {
value = value.replace(/@builtin:features/g, '');
}
value = value.replace(/@builtin/g, '').replace(/@sort:(\w+)(-\w*)?/g, '').trim().toLowerCase();
let result = local
.filter(e => e.isBuiltin && (e.name.toLowerCase().indexOf(value) > -1 || e.displayName.toLowerCase().indexOf(value) > -1));
const isThemeExtension = (e: IExtension): boolean => {
return (Array.isArray(e.local?.manifest?.contributes?.themes) && e.local!.manifest!.contributes!.themes.length > 0)
|| (Array.isArray(e.local?.manifest?.contributes?.iconThemes) && e.local!.manifest!.contributes!.iconThemes.length > 0);
};
if (showThemesOnly) {
const themesExtensions = result.filter(isThemeExtension);
return this.sortExtensions(themesExtensions, options);
}
const isLangaugeBasicExtension = (e: IExtension): boolean => {
return FORCE_FEATURE_EXTENSIONS.indexOf(e.identifier.id) === -1
&& (Array.isArray(e.local?.manifest?.contributes?.grammars) && e.local!.manifest!.contributes!.grammars.length > 0);
};
if (showBasicsOnly) {
const basics = result.filter(isLangaugeBasicExtension);
return this.sortExtensions(basics, options);
}
if (showFeaturesOnly) {
const others = result.filter(e => {
return e.local
&& e.local.manifest
&& !isThemeExtension(e)
&& !isLangaugeBasicExtension(e);
});
return this.sortExtensions(others, options);
}
return this.sortExtensions(result, options);
}
private parseCategories(value: string): { value: string, categories: string[] } {
const categories: string[] = [];
value = value.replace(/\bcategory:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g, (_, quotedCategory, category) => {
const entry = (category || quotedCategory || '').toLowerCase();
if (categories.indexOf(entry) === -1) {
categories.push(entry);
}
return '';
});
return { value, categories };
}
private filterInstalledExtensions(local: IExtension[], runningExtensions: IExtensionDescription[], query: Query, options: IQueryOptions): IExtension[] {
let { value, categories } = this.parseCategories(query.value);
value = value.replace(/@installed/g, '').replace(/@sort:(\w+)(-\w*)?/g, '').trim().toLowerCase();
let result = local
.filter(e => !e.isBuiltin
&& (e.name.toLowerCase().indexOf(value) > -1 || e.displayName.toLowerCase().indexOf(value) > -1)
&& (!categories.length || categories.some(category => (e.local && e.local.manifest.categories || []).some(c => c.toLowerCase() === category))));
if (options.sortBy !== undefined) {
result = this.sortExtensions(result, options);
} else {
const runningExtensionsById = runningExtensions.reduce((result, e) => { result.set(ExtensionIdentifier.toKey(e.identifier.value), e); return result; }, new Map<string, IExtensionDescription>());
result = result.sort((e1, e2) => {
const running1 = runningExtensionsById.get(ExtensionIdentifier.toKey(e1.identifier.id));
const isE1Running = running1 && this.extensionManagementServerService.getExtensionManagementServer(toExtension(running1)) === e1.server;
const running2 = runningExtensionsById.get(ExtensionIdentifier.toKey(e2.identifier.id));
const isE2Running = running2 && this.extensionManagementServerService.getExtensionManagementServer(toExtension(running2)) === e2.server;
if ((isE1Running && isE2Running)) {
return e1.displayName.localeCompare(e2.displayName);
}
const isE1LanguagePackExtension = e1.local && isLanguagePackExtension(e1.local.manifest);
const isE2LanguagePackExtension = e2.local && isLanguagePackExtension(e2.local.manifest);
if (!isE1Running && !isE2Running) {
if (isE1LanguagePackExtension) {
return -1;
}
if (isE2LanguagePackExtension) {
return 1;
}
return e1.displayName.localeCompare(e2.displayName);
}
if ((isE1Running && isE2LanguagePackExtension) || (isE2Running && isE1LanguagePackExtension)) {
return e1.displayName.localeCompare(e2.displayName);
}
return isE1Running ? -1 : 1;
});
}
return result;
}
private filterOutdatedExtensions(local: IExtension[], query: Query, options: IQueryOptions): IExtension[] {
let { value, categories } = this.parseCategories(query.value);
value = value.replace(/@outdated/g, '').replace(/@sort:(\w+)(-\w*)?/g, '').trim().toLowerCase();
const result = local
.sort((e1, e2) => e1.displayName.localeCompare(e2.displayName))
.filter(extension => extension.outdated
&& (extension.name.toLowerCase().indexOf(value) > -1 || extension.displayName.toLowerCase().indexOf(value) > -1)
&& (!categories.length || categories.some(category => !!extension.local && extension.local.manifest.categories!.some(c => c.toLowerCase() === category))));
return this.sortExtensions(result, options);
}
private filterDisabledExtensions(local: IExtension[], runningExtensions: IExtensionDescription[], query: Query, options: IQueryOptions): IExtension[] {
let { value, categories } = this.parseCategories(query.value);
value = value.replace(/@disabled/g, '').replace(/@sort:(\w+)(-\w*)?/g, '').trim().toLowerCase();
const result = local
.sort((e1, e2) => e1.displayName.localeCompare(e2.displayName))
.filter(e => runningExtensions.every(r => !areSameExtensions({ id: r.identifier.value, uuid: r.uuid }, e.identifier))
&& (e.name.toLowerCase().indexOf(value) > -1 || e.displayName.toLowerCase().indexOf(value) > -1)
&& (!categories.length || categories.some(category => (e.local && e.local.manifest.categories || []).some(c => c.toLowerCase() === category))));
return this.sortExtensions(result, options);
}
private filterEnabledExtensions(local: IExtension[], runningExtensions: IExtensionDescription[], query: Query, options: IQueryOptions): IExtension[] {
let { value, categories } = this.parseCategories(query.value);
value = value ? value.replace(/@enabled/g, '').replace(/@sort:(\w+)(-\w*)?/g, '').trim().toLowerCase() : '';
local = local.filter(e => !e.isBuiltin);
const result = local
.sort((e1, e2) => e1.displayName.localeCompare(e2.displayName))
.filter(e => runningExtensions.some(r => areSameExtensions({ id: r.identifier.value, uuid: r.uuid }, e.identifier))
&& (e.name.toLowerCase().indexOf(value) > -1 || e.displayName.toLowerCase().indexOf(value) > -1)
&& (!categories.length || categories.some(category => (e.local && e.local.manifest.categories || []).some(c => c.toLowerCase() === category))));
return this.sortExtensions(result, options);
}
private mergeAddedExtensions(extensions: IExtension[], newExtensions: IExtension[]): IExtension[] | undefined {
const oldExtensions = [...extensions];
const findPreviousExtensionIndex = (from: number): number => {
let index = -1;
const previousExtensionInNew = newExtensions[from];
if (previousExtensionInNew) {
index = oldExtensions.findIndex(e => areSameExtensions(e.identifier, previousExtensionInNew.identifier));
if (index === -1) {
return findPreviousExtensionIndex(from - 1);
}
}
return index;
};
let hasChanged: boolean = false;
for (let index = 0; index < newExtensions.length; index++) {
const extension = newExtensions[index];
if (extensions.every(r => !areSameExtensions(r.identifier, extension.identifier))) {
hasChanged = true;
extensions.splice(findPreviousExtensionIndex(index - 1) + 1, 0, extension);
}
}
return hasChanged ? extensions : undefined;
}
private async queryGallery(query: Query, options: IQueryOptions, token: CancellationToken): Promise<IPagedModel<IExtension>> {
const hasUserDefinedSortOrder = options.sortBy !== undefined;
if (!hasUserDefinedSortOrder && !query.value.trim()) {
options.sortBy = SortBy.InstallCount;
}
if (this.isRecommendationsQuery(query)) {
return this.queryRecommendations(query, options, token);
}
if (/\bcurated:([^\s]+)\b/.test(query.value)) {
return this.getCuratedModel(query, options, token);
}
const text = query.value;
if (/\bext:([^\s]+)\b/g.test(text)) {
options.text = text;
options.source = 'file-extension-tags';
return this.extensionsWorkbenchService.queryGallery(options, token).then(pager => this.getPagedModel(pager));
}
let preferredResults: string[] = [];
if (text) {
options.text = text.substr(0, 350);
options.source = 'searchText';
if (!hasUserDefinedSortOrder) {
const searchExperiments = await this.getSearchExperiments();
for (const experiment of searchExperiments) {
if (experiment.action && text.toLowerCase() === experiment.action.properties['searchText'] && Array.isArray(experiment.action.properties['preferredResults'])) {
preferredResults = experiment.action.properties['preferredResults'];
options.source += `-experiment-${experiment.id}`;
break;
}
}
}
} else {
options.source = 'viewlet';
}
const pager = await this.extensionsWorkbenchService.queryGallery(options, token);
let positionToUpdate = 0;
for (const preferredResult of preferredResults) {
for (let j = positionToUpdate; j < pager.firstPage.length; j++) {
if (areSameExtensions(pager.firstPage[j].identifier, { id: preferredResult })) {
if (positionToUpdate !== j) {
const preferredExtension = pager.firstPage.splice(j, 1)[0];
pager.firstPage.splice(positionToUpdate, 0, preferredExtension);
positionToUpdate++;
}
break;
}
}
}
return this.getPagedModel(pager);
}
private _searchExperiments: Promise<IExperiment[]> | undefined;
private getSearchExperiments(): Promise<IExperiment[]> {
if (!this._searchExperiments) {
this._searchExperiments = this.experimentService.getExperimentsByType(ExperimentActionType.ExtensionSearchResults);
}
return this._searchExperiments;
}
private sortExtensions(extensions: IExtension[], options: IQueryOptions): IExtension[] {
switch (options.sortBy) {
case SortBy.InstallCount:
extensions = extensions.sort((e1, e2) => typeof e2.installCount === 'number' && typeof e1.installCount === 'number' ? e2.installCount - e1.installCount : NaN);
break;
case SortBy.AverageRating:
case SortBy.WeightedRating:
extensions = extensions.sort((e1, e2) => typeof e2.rating === 'number' && typeof e1.rating === 'number' ? e2.rating - e1.rating : NaN);
break;
default:
extensions = extensions.sort((e1, e2) => e1.displayName.localeCompare(e2.displayName));
break;
}
if (options.sortOrder === SortOrder.Descending) {
extensions = extensions.reverse();
}
return extensions;
}
private async getCuratedModel(query: Query, options: IQueryOptions, token: CancellationToken): Promise<IPagedModel<IExtension>> {
const value = query.value.replace(/curated:/g, '').trim();
const names = await this.experimentService.getCuratedExtensionsList(value);
if (Array.isArray(names) && names.length) {
options.source = `curated:${value}`;
options.names = names;
options.pageSize = names.length;
const pager = await this.extensionsWorkbenchService.queryGallery(options, token);
this.sortFirstPage(pager, names);
return this.getPagedModel(pager || []);
}
return new PagedModel([]);
}
private isRecommendationsQuery(query: Query): boolean {
return ExtensionsListView.isWorkspaceRecommendedExtensionsQuery(query.value)
|| ExtensionsListView.isKeymapsRecommendedExtensionsQuery(query.value)
|| ExtensionsListView.isExeRecommendedExtensionsQuery(query.value)
|| /@recommended:all/i.test(query.value)
|| ExtensionsListView.isSearchRecommendedExtensionsQuery(query.value)
|| ExtensionsListView.isRecommendedExtensionsQuery(query.value);
}
private async queryRecommendations(query: Query, options: IQueryOptions, token: CancellationToken): Promise<IPagedModel<IExtension>> {
// Workspace recommendations
if (ExtensionsListView.isWorkspaceRecommendedExtensionsQuery(query.value)) {
return this.getWorkspaceRecommendationsModel(query, options, token);
}
// Keymap recommendations
if (ExtensionsListView.isKeymapsRecommendedExtensionsQuery(query.value)) {
return this.getKeymapRecommendationsModel(query, options, token);
}
// Exe recommendations
if (ExtensionsListView.isExeRecommendedExtensionsQuery(query.value)) {
return this.getExeRecommendationsModel(query, options, token);
}
// All recommendations
if (/@recommended:all/i.test(query.value)) {
return this.getAllRecommendationsModel(options, token);
}
// Search recommendations
if (ExtensionsListView.isSearchRecommendedExtensionsQuery(query.value) ||
(ExtensionsListView.isRecommendedExtensionsQuery(query.value) && options.sortBy !== undefined)) {
return this.searchRecommendations(query, options, token);
}
// Other recommendations
if (ExtensionsListView.isRecommendedExtensionsQuery(query.value)) {
return this.getOtherRecommendationsModel(query, options, token);
}
return new PagedModel([]);
}
protected async getInstallableRecommendations(recommendations: string[], options: IQueryOptions, token: CancellationToken): Promise<IExtension[]> {
const extensions: IExtension[] = [];
if (recommendations.length) {
const pager = await this.extensionsWorkbenchService.queryGallery({ ...options, names: recommendations, pageSize: recommendations.length }, token);
for (const extension of pager.firstPage) {
if (extension.gallery && (await this.extensionManagementService.canInstall(extension.gallery))) {
extensions.push(extension);
}
}
}
return extensions;
}
protected async getWorkspaceRecommendations(): Promise<string[]> {
const recommendations = await this.extensionRecommendationsService.getWorkspaceRecommendations();
const { important } = await this.extensionRecommendationsService.getConfigBasedRecommendations();
for (const configBasedRecommendation of important) {
if (!recommendations.find(extensionId => extensionId === configBasedRecommendation)) {
recommendations.push(configBasedRecommendation);
}
}
return recommendations;
}
private async getWorkspaceRecommendationsModel(query: Query, options: IQueryOptions, token: CancellationToken): Promise<IPagedModel<IExtension>> {
const recommendations = await this.getWorkspaceRecommendations();
const installableRecommendations = (await this.getInstallableRecommendations(recommendations, { ...options, source: 'recommendations-workspace' }, token));
this.telemetryService.publicLog2<{ count: number }, WorkspaceRecommendationsClassification>('extensionWorkspaceRecommendations:open', { count: installableRecommendations.length });
const result: IExtension[] = coalesce(recommendations.map(id => installableRecommendations.find(i => areSameExtensions(i.identifier, { id }))));
return new PagedModel(result);
}
private async getKeymapRecommendationsModel(query: Query, options: IQueryOptions, token: CancellationToken): Promise<IPagedModel<IExtension>> {
const value = query.value.replace(/@recommended:keymaps/g, '').trim().toLowerCase();
const recommendations = this.extensionRecommendationsService.getKeymapRecommendations();
const installableRecommendations = (await this.getInstallableRecommendations(recommendations, { ...options, source: 'recommendations-keymaps' }, token))
.filter(extension => extension.identifier.id.toLowerCase().indexOf(value) > -1);
return new PagedModel(installableRecommendations);
}
private async getExeRecommendationsModel(query: Query, options: IQueryOptions, token: CancellationToken): Promise<IPagedModel<IExtension>> {
const exe = query.value.replace(/@exe:/g, '').trim().toLowerCase();
const { important, others } = await this.extensionRecommendationsService.getExeBasedRecommendations(exe.startsWith('"') ? exe.substring(1, exe.length - 1) : exe);
const installableRecommendations = await this.getInstallableRecommendations([...important, ...others], { ...options, source: 'recommendations-exe' }, token);
return new PagedModel(installableRecommendations);
}
private async getOtherRecommendationsModel(query: Query, options: IQueryOptions, token: CancellationToken): Promise<IPagedModel<IExtension>> {
const otherRecommendations = await this.getOtherRecommendations();
const installableRecommendations = await this.getInstallableRecommendations(otherRecommendations, { ...options, source: 'recommendations-other', sortBy: undefined }, token);
const result = coalesce(otherRecommendations.map(id => installableRecommendations.find(i => areSameExtensions(i.identifier, { id }))));
return new PagedModel(result);
}
private async getOtherRecommendations(): Promise<string[]> {
const local = (await this.extensionsWorkbenchService.queryLocal(this.options.server))
.map(e => e.identifier.id.toLowerCase());
const workspaceRecommendations = (await this.getWorkspaceRecommendations())
.map(extensionId => extensionId.toLowerCase());
return distinct(
flatten(await Promise.all([
// Order is important
this.extensionRecommendationsService.getImportantRecommendations(),
this.extensionRecommendationsService.getFileBasedRecommendations(),
this.extensionRecommendationsService.getOtherRecommendations()
])).filter(extensionId => !local.includes(extensionId.toLowerCase()) && !workspaceRecommendations.includes(extensionId.toLowerCase())
), extensionId => extensionId.toLowerCase());
}
// Get All types of recommendations, trimmed to show a max of 8 at any given time
private async getAllRecommendationsModel(options: IQueryOptions, token: CancellationToken): Promise<IPagedModel<IExtension>> {
const local = (await this.extensionsWorkbenchService.queryLocal(this.options.server)).map(e => e.identifier.id.toLowerCase());
const allRecommendations = distinct(
flatten(await Promise.all([
// Order is important
this.getWorkspaceRecommendations(),
this.extensionRecommendationsService.getImportantRecommendations(),
this.extensionRecommendationsService.getFileBasedRecommendations(),
this.extensionRecommendationsService.getOtherRecommendations()
])).filter(extensionId => !local.includes(extensionId.toLowerCase())
), extensionId => extensionId.toLowerCase());
const installableRecommendations = await this.getInstallableRecommendations(allRecommendations, { ...options, source: 'recommendations-all', sortBy: undefined }, token);
const result: IExtension[] = coalesce(allRecommendations.map(id => installableRecommendations.find(i => areSameExtensions(i.identifier, { id }))));
return new PagedModel(result.slice(0, 8));
}
private async searchRecommendations(query: Query, options: IQueryOptions, token: CancellationToken): Promise<IPagedModel<IExtension>> {
const value = query.value.replace(/@recommended/g, '').trim().toLowerCase();
const recommendations = distinct([...await this.getWorkspaceRecommendations(), ...await this.getOtherRecommendations()]);
const installableRecommendations = (await this.getInstallableRecommendations(recommendations, { ...options, source: 'recommendations', sortBy: undefined }, token))
.filter(extension => extension.identifier.id.toLowerCase().indexOf(value) > -1);
const result = coalesce(recommendations.map(id => installableRecommendations.find(i => areSameExtensions(i.identifier, { id }))));
return new PagedModel(this.sortExtensions(result, options));
}
// Sorts the firstPage of the pager in the same order as given array of extension ids
private sortFirstPage(pager: IPager<IExtension>, ids: string[]) {
ids = ids.map(x => x.toLowerCase());
pager.firstPage.sort((a, b) => {
return ids.indexOf(a.identifier.id.toLowerCase()) < ids.indexOf(b.identifier.id.toLowerCase()) ? -1 : 1;
});
}
private setModel(model: IPagedModel<IExtension>, error?: any) {
if (this.list) {
this.list.model = new DelayedPagedModel(model);
this.list.scrollTop = 0;
this.updateBody(error);
}
}
private updateBody(error?: any): void {
const count = this.count();
if (this.bodyTemplate && this.badge) {
this.bodyTemplate.extensionsList.classList.toggle('hidden', count === 0);
this.bodyTemplate.messageContainer.classList.toggle('hidden', count > 0);
this.badge.setCount(count);
if (count === 0 && this.isBodyVisible()) {
if (error) {
if (error instanceof ExtensionListViewWarning) {
this.bodyTemplate.messageSeverityIcon.className = SeverityIcon.className(Severity.Warning);
this.bodyTemplate.messageBox.textContent = getErrorMessage(error);
} else {
this.bodyTemplate.messageSeverityIcon.className = SeverityIcon.className(Severity.Error);
this.bodyTemplate.messageBox.textContent = localize('error', "Error while loading extensions. {0}", getErrorMessage(error));
}
} else {
this.bodyTemplate.messageSeverityIcon.className = '';
this.bodyTemplate.messageBox.textContent = localize('no extensions found', "No extensions found.");
}
alert(this.bodyTemplate.messageBox.textContent);
}
}
this.updateSize();
}
protected updateSize() {
if (this.options.fixedHeight) {
const length = this.list?.model.length || 0;
this.minimumBodySize = Math.min(length, 3) * EXTENSION_LIST_ELEMENT_HEIGHT;
this.maximumBodySize = length * EXTENSION_LIST_ELEMENT_HEIGHT;
this.storageService.store(this.id, this.maximumBodySize, StorageScope.GLOBAL, StorageTarget.MACHINE);
}
}
private updateModel(model: IPagedModel<IExtension>) {
if (this.list) {
this.list.model = new DelayedPagedModel(model);
this.updateBody();
}
}
private openExtension(extension: IExtension, options: { sideByside?: boolean, preserveFocus?: boolean, pinned?: boolean }): void {
extension = this.extensionsWorkbenchService.local.filter(e => areSameExtensions(e.identifier, extension.identifier))[0] || extension;
this.extensionsWorkbenchService.open(extension, options).then(undefined, err => this.onError(err));
}
private onError(err: any): void {
if (isPromiseCanceledError(err)) {
return;
}
const message = err && err.message || '';
if (/ECONNREFUSED/.test(message)) {
const error = createErrorWithActions(localize('suggestProxyError', "Marketplace returned 'ECONNREFUSED'. Please check the 'http.proxy' setting."), {
actions: [
new Action('open user settings', localize('open user settings', "Open User Settings"), undefined, true, () => this.preferencesService.openGlobalSettings())
]
});
this.notificationService.error(error);
return;
}
this.notificationService.error(err);
}
private getPagedModel(arg: IPager<IExtension> | IExtension[]): IPagedModel<IExtension> {
if (Array.isArray(arg)) {
return new PagedModel(arg);
}
const pager = {
total: arg.total,
pageSize: arg.pageSize,
firstPage: arg.firstPage,
getPage: (pageIndex: number, cancellationToken: CancellationToken) => arg.getPage(pageIndex, cancellationToken)
};
return new PagedModel(pager);
}
dispose(): void {
super.dispose();
if (this.queryRequest) {
this.queryRequest.request.cancel();
this.queryRequest = null;
}
if (this.queryResult) {
this.queryResult.disposables.dispose();
this.queryResult = undefined;
}
this.list = null;
}
static isLocalExtensionsQuery(query: string): boolean {
return this.isInstalledExtensionsQuery(query)
|| this.isOutdatedExtensionsQuery(query)
|| this.isEnabledExtensionsQuery(query)
|| this.isDisabledExtensionsQuery(query)
|| this.isBuiltInExtensionsQuery(query)
|| this.isSearchBuiltInExtensionsQuery(query)
|| this.isBuiltInGroupExtensionsQuery(query);
}
static isSearchBuiltInExtensionsQuery(query: string): boolean {
return /@builtin\s.+/i.test(query);
}
static isBuiltInExtensionsQuery(query: string): boolean {
return /^\s*@builtin$/i.test(query.trim());
}
static isBuiltInGroupExtensionsQuery(query: string): boolean {
return /^\s*@builtin:.+$/i.test(query.trim());
}
static isInstalledExtensionsQuery(query: string): boolean {
return /@installed/i.test(query);
}
static isOutdatedExtensionsQuery(query: string): boolean {
return /@outdated/i.test(query);
}
static isEnabledExtensionsQuery(query: string): boolean {
return /@enabled/i.test(query);
}
static isDisabledExtensionsQuery(query: string): boolean {
return /@disabled/i.test(query);
}
static isRecommendedExtensionsQuery(query: string): boolean {
return /^@recommended$/i.test(query.trim());
}
static isSearchRecommendedExtensionsQuery(query: string): boolean {
return /@recommended\s.+/i.test(query);
}
static isWorkspaceRecommendedExtensionsQuery(query: string): boolean {
return /@recommended:workspace/i.test(query);
}
static isExeRecommendedExtensionsQuery(query: string): boolean {
return /@exe:.+/i.test(query);
}
static isKeymapsRecommendedExtensionsQuery(query: string): boolean {
return /@recommended:keymaps/i.test(query);
}
focus(): void {
super.focus();
if (!this.list) {
return;
}
if (!(this.list.getFocus().length || this.list.getSelection().length)) {
this.list.focusNext();
}
this.list.domFocus();
}
}
export class ServerInstalledExtensionsView extends ExtensionsListView {
async show(query: string): Promise<IPagedModel<IExtension>> {
query = query ? query : '@installed';
if (!ExtensionsListView.isLocalExtensionsQuery(query)) {
query = query += ' @installed';
}
return super.show(query.trim());
}
}
export class EnabledExtensionsView extends ExtensionsListView {
async show(query: string): Promise<IPagedModel<IExtension>> {
query = query || '@enabled';
return ExtensionsListView.isEnabledExtensionsQuery(query) ? super.show(query) : this.showEmptyModel();
}
}
export class DisabledExtensionsView extends ExtensionsListView {
async show(query: string): Promise<IPagedModel<IExtension>> {
query = query || '@disabled';
return ExtensionsListView.isDisabledExtensionsQuery(query) ? super.show(query) : this.showEmptyModel();
}
}
export class BuiltInFeatureExtensionsView extends ExtensionsListView {
async show(query: string): Promise<IPagedModel<IExtension>> {
return (query && query.trim() !== '@builtin') ? this.showEmptyModel() : super.show('@builtin:features');
}
}
export class BuiltInThemesExtensionsView extends ExtensionsListView {
async show(query: string): Promise<IPagedModel<IExtension>> {
return (query && query.trim() !== '@builtin') ? this.showEmptyModel() : super.show('@builtin:themes');
}
}
export class BuiltInProgrammingLanguageExtensionsView extends ExtensionsListView {
async show(query: string): Promise<IPagedModel<IExtension>> {
return (query && query.trim() !== '@builtin') ? this.showEmptyModel() : super.show('@builtin:basics');
}
}
export class DefaultRecommendedExtensionsView extends ExtensionsListView {
private readonly recommendedExtensionsQuery = '@recommended:all';
renderBody(container: HTMLElement): void {
super.renderBody(container);
this._register(this.extensionRecommendationsService.onDidChangeRecommendations(() => {
this.show('');
}));
}
async show(query: string): Promise<IPagedModel<IExtension>> {
if (query && query.trim() !== this.recommendedExtensionsQuery) {
return this.showEmptyModel();
}
const model = await super.show(this.recommendedExtensionsQuery);
if (!this.extensionsWorkbenchService.local.some(e => !e.isBuiltin)) {
// This is part of popular extensions view. Collapse if no installed extensions.
this.setExpanded(model.length > 0);
}
return model;
}
}
export class RecommendedExtensionsView extends ExtensionsListView {
private readonly recommendedExtensionsQuery = '@recommended';
renderBody(container: HTMLElement): void {
super.renderBody(container);
this._register(this.extensionRecommendationsService.onDidChangeRecommendations(() => {
this.show('');
}));
}
async show(query: string): Promise<IPagedModel<IExtension>> {
return (query && query.trim() !== this.recommendedExtensionsQuery) ? this.showEmptyModel() : super.show(this.recommendedExtensionsQuery);
}
}
export class WorkspaceRecommendedExtensionsView extends ExtensionsListView implements IWorkspaceRecommendedExtensionsView {
private readonly recommendedExtensionsQuery = '@recommended:workspace';
renderBody(container: HTMLElement): void {
super.renderBody(container);
this._register(this.extensionRecommendationsService.onDidChangeRecommendations(() => this.show(this.recommendedExtensionsQuery)));
this._register(this.contextService.onDidChangeWorkbenchState(() => this.show(this.recommendedExtensionsQuery)));
}
async show(query: string): Promise<IPagedModel<IExtension>> {
let shouldShowEmptyView = query && query.trim() !== '@recommended' && query.trim() !== '@recommended:workspace';
let model = await (shouldShowEmptyView ? this.showEmptyModel() : super.show(this.recommendedExtensionsQuery));
this.setExpanded(model.length > 0);
return model;
}
private async getInstallableWorkspaceRecommendations() {
const installed = (await this.extensionsWorkbenchService.queryLocal())
.filter(l => l.enablementState !== EnablementState.DisabledByExtensionKind); // Filter extensions disabled by kind
const recommendations = (await this.getWorkspaceRecommendations())
.filter(extensionId => installed.every(local => !areSameExtensions({ id: extensionId }, local.identifier)));
return this.getInstallableRecommendations(recommendations, { source: 'install-all-workspace-recommendations' }, CancellationToken.None);
}
async installWorkspaceRecommendations(): Promise<void> {
const installableRecommendations = await this.getInstallableWorkspaceRecommendations();
if (installableRecommendations.length) {
await this.extensionManagementService.installExtensions(installableRecommendations.map(i => i.gallery!));
} else {
this.notificationService.notify({
severity: Severity.Info,
message: localize('no local extensions', "There are no extensions to install.")
});
}
}
}
| src/vs/workbench/contrib/extensions/browser/extensionsViews.ts | 1 | https://github.com/microsoft/vscode/commit/0657df6e82ff9e6900c32a7edffce9aa98879857 | [
0.18936112523078918,
0.001872700871899724,
0.00016011057596188039,
0.00017188949277624488,
0.017796052619814873
] |
{
"id": 3,
"code_window": [
"\n",
"export class SCMAccessibilityProvider implements IListAccessibilityProvider<TreeElement> {\n",
"\n",
"\tconstructor(@ILabelService private readonly labelService: ILabelService) { }\n",
"\n",
"\tgetWidgetAriaLabel(): string {\n",
"\t\treturn localize('scm', \"Source Control Management\");\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tconstructor(\n",
"\t\t@ILabelService private readonly labelService: ILabelService,\n",
"\t\t@IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService\n",
"\t) { }\n"
],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewPane.ts",
"type": "replace",
"edit_start_line_idx": 688
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { localize } from 'vs/nls';
import { isObject, isString, isUndefined, isNumber, withNullAsUndefined } from 'vs/base/common/types';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { TextCompareEditorVisibleContext, EditorInput, IEditorIdentifier, IEditorCommandsContext, ActiveEditorGroupEmptyContext, MultipleEditorGroupsContext, CloseDirection, IEditorInput, IVisibleEditorPane, ActiveEditorStickyContext, EditorsOrder, viewColumnToEditorGroup, EditorGroupColumn } from 'vs/workbench/common/editor';
import { IEditorService, SIDE_GROUP } from 'vs/workbench/services/editor/common/editorService';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { TextDiffEditor } from 'vs/workbench/browser/parts/editor/textDiffEditor';
import { KeyMod, KeyCode, KeyChord } from 'vs/base/common/keyCodes';
import { URI, UriComponents } from 'vs/base/common/uri';
import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput';
import { IListService, IOpenEvent } from 'vs/platform/list/browser/listService';
import { List } from 'vs/base/browser/ui/list/listWidget';
import { distinct, coalesce } from 'vs/base/common/arrays';
import { IEditorGroupsService, IEditorGroup, GroupDirection, GroupLocation, GroupsOrder, preferredSideBySideGroupDirection, EditorGroupLayout } from 'vs/workbench/services/editor/common/editorGroupsService';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { CommandsRegistry, ICommandHandler } from 'vs/platform/commands/common/commands';
import { MenuRegistry, MenuId } from 'vs/platform/actions/common/actions';
import { ActiveGroupEditorsByMostRecentlyUsedQuickAccess } from 'vs/workbench/browser/parts/editor/editorQuickAccess';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { ITextEditorOptions } from 'vs/platform/editor/common/editor';
export const CLOSE_SAVED_EDITORS_COMMAND_ID = 'workbench.action.closeUnmodifiedEditors';
export const CLOSE_EDITORS_IN_GROUP_COMMAND_ID = 'workbench.action.closeEditorsInGroup';
export const CLOSE_EDITORS_AND_GROUP_COMMAND_ID = 'workbench.action.closeEditorsAndGroup';
export const CLOSE_EDITORS_TO_THE_RIGHT_COMMAND_ID = 'workbench.action.closeEditorsToTheRight';
export const CLOSE_EDITOR_COMMAND_ID = 'workbench.action.closeActiveEditor';
export const CLOSE_PINNED_EDITOR_COMMAND_ID = 'workbench.action.closeActivePinnedEditor';
export const CLOSE_EDITOR_GROUP_COMMAND_ID = 'workbench.action.closeGroup';
export const CLOSE_OTHER_EDITORS_IN_GROUP_COMMAND_ID = 'workbench.action.closeOtherEditors';
export const MOVE_ACTIVE_EDITOR_COMMAND_ID = 'moveActiveEditor';
export const LAYOUT_EDITOR_GROUPS_COMMAND_ID = 'layoutEditorGroups';
export const KEEP_EDITOR_COMMAND_ID = 'workbench.action.keepEditor';
export const TOGGLE_KEEP_EDITORS_COMMAND_ID = 'workbench.action.toggleKeepEditors';
export const SHOW_EDITORS_IN_GROUP = 'workbench.action.showEditorsInGroup';
export const PIN_EDITOR_COMMAND_ID = 'workbench.action.pinEditor';
export const UNPIN_EDITOR_COMMAND_ID = 'workbench.action.unpinEditor';
export const TOGGLE_DIFF_SIDE_BY_SIDE = 'toggle.diff.renderSideBySide';
export const GOTO_NEXT_CHANGE = 'workbench.action.compareEditor.nextChange';
export const GOTO_PREVIOUS_CHANGE = 'workbench.action.compareEditor.previousChange';
export const DIFF_FOCUS_PRIMARY_SIDE = 'workbench.action.compareEditor.focusPrimarySide';
export const DIFF_FOCUS_SECONDARY_SIDE = 'workbench.action.compareEditor.focusSecondarySide';
export const DIFF_FOCUS_OTHER_SIDE = 'workbench.action.compareEditor.focusOtherSide';
export const TOGGLE_DIFF_IGNORE_TRIM_WHITESPACE = 'toggle.diff.ignoreTrimWhitespace';
export const SPLIT_EDITOR_UP = 'workbench.action.splitEditorUp';
export const SPLIT_EDITOR_DOWN = 'workbench.action.splitEditorDown';
export const SPLIT_EDITOR_LEFT = 'workbench.action.splitEditorLeft';
export const SPLIT_EDITOR_RIGHT = 'workbench.action.splitEditorRight';
export const FOCUS_LEFT_GROUP_WITHOUT_WRAP_COMMAND_ID = 'workbench.action.focusLeftGroupWithoutWrap';
export const FOCUS_RIGHT_GROUP_WITHOUT_WRAP_COMMAND_ID = 'workbench.action.focusRightGroupWithoutWrap';
export const FOCUS_ABOVE_GROUP_WITHOUT_WRAP_COMMAND_ID = 'workbench.action.focusAboveGroupWithoutWrap';
export const FOCUS_BELOW_GROUP_WITHOUT_WRAP_COMMAND_ID = 'workbench.action.focusBelowGroupWithoutWrap';
export const OPEN_EDITOR_AT_INDEX_COMMAND_ID = 'workbench.action.openEditorAtIndex';
export const API_OPEN_EDITOR_COMMAND_ID = '_workbench.open';
export const API_OPEN_DIFF_EDITOR_COMMAND_ID = '_workbench.diff';
export const API_OPEN_WITH_EDITOR_COMMAND_ID = '_workbench.openWith';
export interface ActiveEditorMoveArguments {
to: 'first' | 'last' | 'left' | 'right' | 'up' | 'down' | 'center' | 'position' | 'previous' | 'next';
by: 'tab' | 'group';
value: number;
}
const isActiveEditorMoveArg = function (arg: ActiveEditorMoveArguments): boolean {
if (!isObject(arg)) {
return false;
}
if (!isString(arg.to)) {
return false;
}
if (!isUndefined(arg.by) && !isString(arg.by)) {
return false;
}
if (!isUndefined(arg.value) && !isNumber(arg.value)) {
return false;
}
return true;
};
function registerActiveEditorMoveCommand(): void {
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: MOVE_ACTIVE_EDITOR_COMMAND_ID,
weight: KeybindingWeight.WorkbenchContrib,
when: EditorContextKeys.editorTextFocus,
primary: 0,
handler: (accessor, args) => moveActiveEditor(args, accessor),
description: {
description: localize('editorCommand.activeEditorMove.description', "Move the active editor by tabs or groups"),
args: [
{
name: localize('editorCommand.activeEditorMove.arg.name', "Active editor move argument"),
description: localize('editorCommand.activeEditorMove.arg.description', "Argument Properties:\n\t* 'to': String value providing where to move.\n\t* 'by': String value providing the unit for move (by tab or by group).\n\t* 'value': Number value providing how many positions or an absolute position to move."),
constraint: isActiveEditorMoveArg,
schema: {
'type': 'object',
'required': ['to'],
'properties': {
'to': {
'type': 'string',
'enum': ['left', 'right']
},
'by': {
'type': 'string',
'enum': ['tab', 'group']
},
'value': {
'type': 'number'
}
},
}
}
]
}
});
}
function moveActiveEditor(args: ActiveEditorMoveArguments = Object.create(null), accessor: ServicesAccessor): void {
args.to = args.to || 'right';
args.by = args.by || 'tab';
args.value = typeof args.value === 'number' ? args.value : 1;
const activeEditorPane = accessor.get(IEditorService).activeEditorPane;
if (activeEditorPane) {
switch (args.by) {
case 'tab':
return moveActiveTab(args, activeEditorPane, accessor);
case 'group':
return moveActiveEditorToGroup(args, activeEditorPane, accessor);
}
}
}
function moveActiveTab(args: ActiveEditorMoveArguments, control: IVisibleEditorPane, accessor: ServicesAccessor): void {
const group = control.group;
let index = group.getIndexOfEditor(control.input);
switch (args.to) {
case 'first':
index = 0;
break;
case 'last':
index = group.count - 1;
break;
case 'left':
index = index - args.value;
break;
case 'right':
index = index + args.value;
break;
case 'center':
index = Math.round(group.count / 2) - 1;
break;
case 'position':
index = args.value - 1;
break;
}
index = index < 0 ? 0 : index >= group.count ? group.count - 1 : index;
group.moveEditor(control.input, group, { index });
}
function moveActiveEditorToGroup(args: ActiveEditorMoveArguments, control: IVisibleEditorPane, accessor: ServicesAccessor): void {
const editorGroupService = accessor.get(IEditorGroupsService);
const configurationService = accessor.get(IConfigurationService);
const sourceGroup = control.group;
let targetGroup: IEditorGroup | undefined;
switch (args.to) {
case 'left':
targetGroup = editorGroupService.findGroup({ direction: GroupDirection.LEFT }, sourceGroup);
if (!targetGroup) {
targetGroup = editorGroupService.addGroup(sourceGroup, GroupDirection.LEFT);
}
break;
case 'right':
targetGroup = editorGroupService.findGroup({ direction: GroupDirection.RIGHT }, sourceGroup);
if (!targetGroup) {
targetGroup = editorGroupService.addGroup(sourceGroup, GroupDirection.RIGHT);
}
break;
case 'up':
targetGroup = editorGroupService.findGroup({ direction: GroupDirection.UP }, sourceGroup);
if (!targetGroup) {
targetGroup = editorGroupService.addGroup(sourceGroup, GroupDirection.UP);
}
break;
case 'down':
targetGroup = editorGroupService.findGroup({ direction: GroupDirection.DOWN }, sourceGroup);
if (!targetGroup) {
targetGroup = editorGroupService.addGroup(sourceGroup, GroupDirection.DOWN);
}
break;
case 'first':
targetGroup = editorGroupService.findGroup({ location: GroupLocation.FIRST }, sourceGroup);
break;
case 'last':
targetGroup = editorGroupService.findGroup({ location: GroupLocation.LAST }, sourceGroup);
break;
case 'previous':
targetGroup = editorGroupService.findGroup({ location: GroupLocation.PREVIOUS }, sourceGroup);
break;
case 'next':
targetGroup = editorGroupService.findGroup({ location: GroupLocation.NEXT }, sourceGroup);
if (!targetGroup) {
targetGroup = editorGroupService.addGroup(sourceGroup, preferredSideBySideGroupDirection(configurationService));
}
break;
case 'center':
targetGroup = editorGroupService.getGroups(GroupsOrder.GRID_APPEARANCE)[(editorGroupService.count / 2) - 1];
break;
case 'position':
targetGroup = editorGroupService.getGroups(GroupsOrder.GRID_APPEARANCE)[args.value - 1];
break;
}
if (targetGroup) {
sourceGroup.moveEditor(control.input, targetGroup);
targetGroup.focus();
}
}
function registerEditorGroupsLayoutCommand(): void {
function applyEditorLayout(accessor: ServicesAccessor, layout: EditorGroupLayout): void {
if (!layout || typeof layout !== 'object') {
return;
}
const editorGroupService = accessor.get(IEditorGroupsService);
editorGroupService.applyLayout(layout);
}
CommandsRegistry.registerCommand(LAYOUT_EDITOR_GROUPS_COMMAND_ID, (accessor: ServicesAccessor, args: EditorGroupLayout) => {
applyEditorLayout(accessor, args);
});
// API Command
CommandsRegistry.registerCommand({
id: 'vscode.setEditorLayout',
handler: (accessor: ServicesAccessor, args: EditorGroupLayout) => applyEditorLayout(accessor, args),
description: {
description: 'Set Editor Layout',
args: [{
name: 'args',
schema: {
'type': 'object',
'required': ['groups'],
'properties': {
'orientation': {
'type': 'number',
'default': 0,
'enum': [0, 1]
},
'groups': {
'$ref': '#/definitions/editorGroupsSchema',
'default': [{}, {}]
}
}
}
}]
}
});
}
export function mergeAllGroups(editorGroupService: IEditorGroupsService): void {
const target = editorGroupService.activeGroup;
for (const group of editorGroupService.getGroups(GroupsOrder.MOST_RECENTLY_ACTIVE)) {
if (group === target) {
return; // keep target
}
editorGroupService.mergeGroup(group, target);
}
}
function registerDiffEditorCommands(): void {
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: GOTO_NEXT_CHANGE,
weight: KeybindingWeight.WorkbenchContrib,
when: TextCompareEditorVisibleContext,
primary: KeyMod.Alt | KeyCode.F5,
handler: accessor => navigateInDiffEditor(accessor, true)
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: GOTO_PREVIOUS_CHANGE,
weight: KeybindingWeight.WorkbenchContrib,
when: TextCompareEditorVisibleContext,
primary: KeyMod.Alt | KeyMod.Shift | KeyCode.F5,
handler: accessor => navigateInDiffEditor(accessor, false)
});
function getActiveTextDiffEditor(accessor: ServicesAccessor): TextDiffEditor | undefined {
const editorService = accessor.get(IEditorService);
for (const editor of [editorService.activeEditorPane, ...editorService.visibleEditorPanes]) {
if (editor instanceof TextDiffEditor) {
return editor;
}
}
return undefined;
}
function navigateInDiffEditor(accessor: ServicesAccessor, next: boolean): void {
const activeTextDiffEditor = getActiveTextDiffEditor(accessor);
if (activeTextDiffEditor) {
const navigator = activeTextDiffEditor.getDiffNavigator();
if (navigator) {
next ? navigator.next() : navigator.previous();
}
}
}
enum FocusTextDiffEditorMode {
Original,
Modified,
Toggle
}
function focusInDiffEditor(accessor: ServicesAccessor, mode: FocusTextDiffEditorMode): void {
const activeTextDiffEditor = getActiveTextDiffEditor(accessor);
if (activeTextDiffEditor) {
switch (mode) {
case FocusTextDiffEditorMode.Original:
activeTextDiffEditor.getControl()?.getOriginalEditor().focus();
break;
case FocusTextDiffEditorMode.Modified:
activeTextDiffEditor.getControl()?.getModifiedEditor().focus();
break;
case FocusTextDiffEditorMode.Toggle:
if (activeTextDiffEditor.getControl()?.getModifiedEditor().hasWidgetFocus()) {
return focusInDiffEditor(accessor, FocusTextDiffEditorMode.Original);
} else {
return focusInDiffEditor(accessor, FocusTextDiffEditorMode.Modified);
}
}
}
}
function toggleDiffSideBySide(accessor: ServicesAccessor): void {
const configurationService = accessor.get(IConfigurationService);
const newValue = !configurationService.getValue<boolean>('diffEditor.renderSideBySide');
configurationService.updateValue('diffEditor.renderSideBySide', newValue);
}
function toggleDiffIgnoreTrimWhitespace(accessor: ServicesAccessor): void {
const configurationService = accessor.get(IConfigurationService);
const newValue = !configurationService.getValue<boolean>('diffEditor.ignoreTrimWhitespace');
configurationService.updateValue('diffEditor.ignoreTrimWhitespace', newValue);
}
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: TOGGLE_DIFF_SIDE_BY_SIDE,
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: undefined,
handler: accessor => toggleDiffSideBySide(accessor)
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: DIFF_FOCUS_PRIMARY_SIDE,
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: undefined,
handler: accessor => focusInDiffEditor(accessor, FocusTextDiffEditorMode.Modified)
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: DIFF_FOCUS_SECONDARY_SIDE,
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: undefined,
handler: accessor => focusInDiffEditor(accessor, FocusTextDiffEditorMode.Original)
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: DIFF_FOCUS_OTHER_SIDE,
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: undefined,
handler: accessor => focusInDiffEditor(accessor, FocusTextDiffEditorMode.Toggle)
});
MenuRegistry.appendMenuItem(MenuId.CommandPalette, {
command: {
id: TOGGLE_DIFF_SIDE_BY_SIDE,
title: {
value: localize('toggleInlineView', "Toggle Inline View"),
original: 'Compare: Toggle Inline View'
},
category: localize('compare', "Compare")
},
when: ContextKeyExpr.has('textCompareEditorActive')
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: TOGGLE_DIFF_IGNORE_TRIM_WHITESPACE,
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: undefined,
handler: accessor => toggleDiffIgnoreTrimWhitespace(accessor)
});
}
function registerOpenEditorAPICommands(): void {
function mixinContext(context: IOpenEvent<unknown> | undefined, options: ITextEditorOptions | undefined, column: EditorGroupColumn | undefined): [ITextEditorOptions | undefined, EditorGroupColumn | undefined] {
if (!context) {
return [options, column];
}
return [
{ ...context.editorOptions, ...(options ?? Object.create(null)) },
context.sideBySide ? SIDE_GROUP : column
];
}
CommandsRegistry.registerCommand(API_OPEN_EDITOR_COMMAND_ID, async function (accessor: ServicesAccessor, resourceArg: UriComponents, columnAndOptions?: [EditorGroupColumn?, ITextEditorOptions?], label?: string, context?: IOpenEvent<unknown>) {
const editorService = accessor.get(IEditorService);
const editorGroupService = accessor.get(IEditorGroupsService);
const openerService = accessor.get(IOpenerService);
const resource = URI.revive(resourceArg);
const [columnArg, optionsArg] = columnAndOptions ?? [];
// use editor options or editor view column as a hint to use the editor service for opening
if (optionsArg || typeof columnArg === 'number') {
const [options, column] = mixinContext(context, optionsArg, columnArg);
await editorService.openEditor({ resource, options, label }, viewColumnToEditorGroup(editorGroupService, column));
}
// do not allow to execute commands from here
else if (resource.scheme === 'command') {
return;
}
// finally, delegate to opener service
else {
await openerService.open(resource, { openToSide: context?.sideBySide, editorOptions: context?.editorOptions });
}
});
CommandsRegistry.registerCommand(API_OPEN_DIFF_EDITOR_COMMAND_ID, async function (accessor: ServicesAccessor, leftResource: UriComponents, rightResource: UriComponents, label?: string, columnAndOptions?: [EditorGroupColumn?, ITextEditorOptions?], context?: IOpenEvent<unknown>) {
const editorService = accessor.get(IEditorService);
const editorGroupService = accessor.get(IEditorGroupsService);
const [columnArg, optionsArg] = columnAndOptions ?? [];
const [options, column] = mixinContext(context, optionsArg, columnArg);
await editorService.openEditor({
leftResource: URI.revive(leftResource),
rightResource: URI.revive(rightResource),
label,
options
}, viewColumnToEditorGroup(editorGroupService, column));
});
CommandsRegistry.registerCommand(API_OPEN_WITH_EDITOR_COMMAND_ID, (accessor: ServicesAccessor, resource: UriComponents, id: string, columnAndOptions?: [EditorGroupColumn?, ITextEditorOptions?]) => {
const editorService = accessor.get(IEditorService);
const editorGroupsService = accessor.get(IEditorGroupsService);
const configurationService = accessor.get(IConfigurationService);
const [columnArg, optionsArg] = columnAndOptions ?? [];
let group: IEditorGroup | undefined = undefined;
if (columnArg === SIDE_GROUP) {
const direction = preferredSideBySideGroupDirection(configurationService);
let neighbourGroup = editorGroupsService.findGroup({ direction });
if (!neighbourGroup) {
neighbourGroup = editorGroupsService.addGroup(editorGroupsService.activeGroup, direction);
}
group = neighbourGroup;
} else {
group = editorGroupsService.getGroup(viewColumnToEditorGroup(editorGroupsService, columnArg)) ?? editorGroupsService.activeGroup;
}
const input = editorService.createEditorInput({ resource: URI.revive(resource) });
return editorService.openEditor(input, { ...optionsArg, override: id }, group);
});
}
function registerOpenEditorAtIndexCommands(): void {
const openEditorAtIndex: ICommandHandler = (accessor: ServicesAccessor, editorIndex: number): void => {
const editorService = accessor.get(IEditorService);
const activeEditorPane = editorService.activeEditorPane;
if (activeEditorPane) {
const editor = activeEditorPane.group.getEditorByIndex(editorIndex);
if (editor) {
editorService.openEditor(editor);
}
}
};
// This command takes in the editor index number to open as an argument
CommandsRegistry.registerCommand({
id: OPEN_EDITOR_AT_INDEX_COMMAND_ID,
handler: openEditorAtIndex
});
// Keybindings to focus a specific index in the tab folder if tabs are enabled
for (let i = 0; i < 9; i++) {
const editorIndex = i;
const visibleIndex = i + 1;
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: OPEN_EDITOR_AT_INDEX_COMMAND_ID + visibleIndex,
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: KeyMod.Alt | toKeyCode(visibleIndex),
mac: { primary: KeyMod.WinCtrl | toKeyCode(visibleIndex) },
handler: accessor => openEditorAtIndex(accessor, editorIndex)
});
}
function toKeyCode(index: number): KeyCode {
switch (index) {
case 0: return KeyCode.KEY_0;
case 1: return KeyCode.KEY_1;
case 2: return KeyCode.KEY_2;
case 3: return KeyCode.KEY_3;
case 4: return KeyCode.KEY_4;
case 5: return KeyCode.KEY_5;
case 6: return KeyCode.KEY_6;
case 7: return KeyCode.KEY_7;
case 8: return KeyCode.KEY_8;
case 9: return KeyCode.KEY_9;
}
throw new Error('invalid index');
}
}
function registerFocusEditorGroupAtIndexCommands(): void {
// Keybindings to focus a specific group (2-8) in the editor area
for (let groupIndex = 1; groupIndex < 8; groupIndex++) {
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: toCommandId(groupIndex),
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: KeyMod.CtrlCmd | toKeyCode(groupIndex),
handler: accessor => {
const editorGroupService = accessor.get(IEditorGroupsService);
const configurationService = accessor.get(IConfigurationService);
// To keep backwards compatibility (pre-grid), allow to focus a group
// that does not exist as long as it is the next group after the last
// opened group. Otherwise we return.
if (groupIndex > editorGroupService.count) {
return;
}
// Group exists: just focus
const groups = editorGroupService.getGroups(GroupsOrder.GRID_APPEARANCE);
if (groups[groupIndex]) {
return groups[groupIndex].focus();
}
// Group does not exist: create new by splitting the active one of the last group
const direction = preferredSideBySideGroupDirection(configurationService);
const lastGroup = editorGroupService.findGroup({ location: GroupLocation.LAST });
const newGroup = editorGroupService.addGroup(lastGroup, direction);
// Focus
newGroup.focus();
}
});
}
function toCommandId(index: number): string {
switch (index) {
case 1: return 'workbench.action.focusSecondEditorGroup';
case 2: return 'workbench.action.focusThirdEditorGroup';
case 3: return 'workbench.action.focusFourthEditorGroup';
case 4: return 'workbench.action.focusFifthEditorGroup';
case 5: return 'workbench.action.focusSixthEditorGroup';
case 6: return 'workbench.action.focusSeventhEditorGroup';
case 7: return 'workbench.action.focusEighthEditorGroup';
}
throw new Error('Invalid index');
}
function toKeyCode(index: number): KeyCode {
switch (index) {
case 1: return KeyCode.KEY_2;
case 2: return KeyCode.KEY_3;
case 3: return KeyCode.KEY_4;
case 4: return KeyCode.KEY_5;
case 5: return KeyCode.KEY_6;
case 6: return KeyCode.KEY_7;
case 7: return KeyCode.KEY_8;
}
throw new Error('Invalid index');
}
}
export function splitEditor(editorGroupService: IEditorGroupsService, direction: GroupDirection, context?: IEditorCommandsContext): void {
let sourceGroup: IEditorGroup | undefined;
if (context && typeof context.groupId === 'number') {
sourceGroup = editorGroupService.getGroup(context.groupId);
} else {
sourceGroup = editorGroupService.activeGroup;
}
if (!sourceGroup) {
return;
}
// Add group
const newGroup = editorGroupService.addGroup(sourceGroup, direction);
// Split editor (if it can be split)
let editorToCopy: IEditorInput | undefined;
if (context && typeof context.editorIndex === 'number') {
editorToCopy = sourceGroup.getEditorByIndex(context.editorIndex);
} else {
editorToCopy = withNullAsUndefined(sourceGroup.activeEditor);
}
if (editorToCopy && (editorToCopy as EditorInput).supportsSplitEditor()) {
sourceGroup.copyEditor(editorToCopy, newGroup);
}
// Focus
newGroup.focus();
}
function registerSplitEditorCommands() {
[
{ id: SPLIT_EDITOR_UP, direction: GroupDirection.UP },
{ id: SPLIT_EDITOR_DOWN, direction: GroupDirection.DOWN },
{ id: SPLIT_EDITOR_LEFT, direction: GroupDirection.LEFT },
{ id: SPLIT_EDITOR_RIGHT, direction: GroupDirection.RIGHT }
].forEach(({ id, direction }) => {
CommandsRegistry.registerCommand(id, function (accessor, resourceOrContext?: URI | IEditorCommandsContext, context?: IEditorCommandsContext) {
splitEditor(accessor.get(IEditorGroupsService), direction, getCommandsContext(resourceOrContext, context));
});
});
}
function registerCloseEditorCommands() {
// A special handler for "Close Editor" depending on context
// - keybindining: do not close sticky editors, rather open the next non-sticky editor
// - menu: always close editor, even sticky ones
function closeEditorHandler(accessor: ServicesAccessor, forceCloseStickyEditors: boolean, resourceOrContext?: URI | IEditorCommandsContext, context?: IEditorCommandsContext): Promise<unknown> {
const editorGroupsService = accessor.get(IEditorGroupsService);
const editorService = accessor.get(IEditorService);
let keepStickyEditors = true;
if (forceCloseStickyEditors) {
keepStickyEditors = false; // explicitly close sticky editors
} else if (resourceOrContext || context) {
keepStickyEditors = false; // we have a context, as such this command was used e.g. from the tab context menu
}
// Without context: skip over sticky editor and select next if active editor is sticky
if (keepStickyEditors && !resourceOrContext && !context) {
const activeGroup = editorGroupsService.activeGroup;
const activeEditor = activeGroup.activeEditor;
if (activeEditor && activeGroup.isSticky(activeEditor)) {
// Open next recently active in same group
const nextNonStickyEditorInGroup = activeGroup.getEditors(EditorsOrder.MOST_RECENTLY_ACTIVE, { excludeSticky: true })[0];
if (nextNonStickyEditorInGroup) {
return activeGroup.openEditor(nextNonStickyEditorInGroup);
}
// Open next recently active across all groups
const nextNonStickyEditorInAllGroups = editorService.getEditors(EditorsOrder.MOST_RECENTLY_ACTIVE, { excludeSticky: true })[0];
if (nextNonStickyEditorInAllGroups) {
return Promise.resolve(editorGroupsService.getGroup(nextNonStickyEditorInAllGroups.groupId)?.openEditor(nextNonStickyEditorInAllGroups.editor));
}
}
}
// With context: proceed to close editors as instructed
const { editors, groups } = getEditorsContext(accessor, resourceOrContext, context);
return Promise.all(groups.map(async group => {
if (group) {
const editorsToClose = coalesce(editors
.filter(editor => editor.groupId === group.id)
.map(editor => typeof editor.editorIndex === 'number' ? group.getEditorByIndex(editor.editorIndex) : group.activeEditor))
.filter(editor => !keepStickyEditors || !group.isSticky(editor));
return group.closeEditors(editorsToClose);
}
}));
}
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: CLOSE_EDITOR_COMMAND_ID,
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: KeyMod.CtrlCmd | KeyCode.KEY_W,
win: { primary: KeyMod.CtrlCmd | KeyCode.F4, secondary: [KeyMod.CtrlCmd | KeyCode.KEY_W] },
handler: (accessor, resourceOrContext?: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
return closeEditorHandler(accessor, false, resourceOrContext, context);
}
});
CommandsRegistry.registerCommand(CLOSE_PINNED_EDITOR_COMMAND_ID, (accessor, resourceOrContext?: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
return closeEditorHandler(accessor, true /* force close pinned editors */, resourceOrContext, context);
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: CLOSE_EDITORS_IN_GROUP_COMMAND_ID,
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyCode.KEY_W),
handler: (accessor, resourceOrContext?: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
return Promise.all(getEditorsContext(accessor, resourceOrContext, context).groups.map(async group => {
if (group) {
return group.closeAllEditors({ excludeSticky: true });
}
}));
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: CLOSE_EDITOR_GROUP_COMMAND_ID,
weight: KeybindingWeight.WorkbenchContrib,
when: ContextKeyExpr.and(ActiveEditorGroupEmptyContext, MultipleEditorGroupsContext),
primary: KeyMod.CtrlCmd | KeyCode.KEY_W,
win: { primary: KeyMod.CtrlCmd | KeyCode.F4, secondary: [KeyMod.CtrlCmd | KeyCode.KEY_W] },
handler: (accessor, resourceOrContext?: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
const editorGroupService = accessor.get(IEditorGroupsService);
const commandsContext = getCommandsContext(resourceOrContext, context);
let group: IEditorGroup | undefined;
if (commandsContext && typeof commandsContext.groupId === 'number') {
group = editorGroupService.getGroup(commandsContext.groupId);
} else {
group = editorGroupService.activeGroup;
}
if (group) {
editorGroupService.removeGroup(group);
}
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: CLOSE_SAVED_EDITORS_COMMAND_ID,
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyCode.KEY_U),
handler: (accessor, resourceOrContext?: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
return Promise.all(getEditorsContext(accessor, resourceOrContext, context).groups.map(async group => {
if (group) {
return group.closeEditors({ savedOnly: true, excludeSticky: true });
}
}));
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: CLOSE_OTHER_EDITORS_IN_GROUP_COMMAND_ID,
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: undefined,
mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_T },
handler: (accessor, resourceOrContext?: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
const { editors, groups } = getEditorsContext(accessor, resourceOrContext, context);
return Promise.all(groups.map(async group => {
if (group) {
const editorsToKeep = editors
.filter(editor => editor.groupId === group.id)
.map(editor => typeof editor.editorIndex === 'number' ? group.getEditorByIndex(editor.editorIndex) : group.activeEditor);
const editorsToClose = group.getEditors(EditorsOrder.SEQUENTIAL, { excludeSticky: true }).filter(editor => !editorsToKeep.includes(editor));
for (const editorToKeep of editorsToKeep) {
if (editorToKeep) {
group.pinEditor(editorToKeep);
}
}
return group.closeEditors(editorsToClose);
}
}));
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: CLOSE_EDITORS_TO_THE_RIGHT_COMMAND_ID,
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: undefined,
handler: async (accessor, resourceOrContext?: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
const editorGroupService = accessor.get(IEditorGroupsService);
const { group, editor } = resolveCommandsContext(editorGroupService, getCommandsContext(resourceOrContext, context));
if (group && editor) {
if (group.activeEditor) {
group.pinEditor(group.activeEditor);
}
return group.closeEditors({ direction: CloseDirection.RIGHT, except: editor, excludeSticky: true });
}
}
});
CommandsRegistry.registerCommand(CLOSE_EDITORS_AND_GROUP_COMMAND_ID, async (accessor: ServicesAccessor, resourceOrContext?: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
const editorGroupService = accessor.get(IEditorGroupsService);
const { group } = resolveCommandsContext(editorGroupService, getCommandsContext(resourceOrContext, context));
if (group) {
await group.closeAllEditors();
if (group.count === 0 && editorGroupService.getGroup(group.id) /* could be gone by now */) {
editorGroupService.removeGroup(group); // only remove group if it is now empty
}
}
});
}
function registerFocusEditorGroupWihoutWrapCommands(): void {
const commands = [
{
id: FOCUS_LEFT_GROUP_WITHOUT_WRAP_COMMAND_ID,
direction: GroupDirection.LEFT
},
{
id: FOCUS_RIGHT_GROUP_WITHOUT_WRAP_COMMAND_ID,
direction: GroupDirection.RIGHT
},
{
id: FOCUS_ABOVE_GROUP_WITHOUT_WRAP_COMMAND_ID,
direction: GroupDirection.UP,
},
{
id: FOCUS_BELOW_GROUP_WITHOUT_WRAP_COMMAND_ID,
direction: GroupDirection.DOWN
}
];
for (const command of commands) {
CommandsRegistry.registerCommand(command.id, async (accessor: ServicesAccessor) => {
const editorGroupService = accessor.get(IEditorGroupsService);
const group = editorGroupService.findGroup({ direction: command.direction }, editorGroupService.activeGroup, false);
if (group) {
group.focus();
}
});
}
}
function registerOtherEditorCommands(): void {
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: KEEP_EDITOR_COMMAND_ID,
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyCode.Enter),
handler: async (accessor, resourceOrContext?: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
const editorGroupService = accessor.get(IEditorGroupsService);
const { group, editor } = resolveCommandsContext(editorGroupService, getCommandsContext(resourceOrContext, context));
if (group && editor) {
return group.pinEditor(editor);
}
}
});
CommandsRegistry.registerCommand({
id: TOGGLE_KEEP_EDITORS_COMMAND_ID,
handler: accessor => {
const configurationService = accessor.get(IConfigurationService);
const currentSetting = configurationService.getValue<boolean>('workbench.editor.enablePreview');
const newSetting = currentSetting === true ? false : true;
configurationService.updateValue('workbench.editor.enablePreview', newSetting);
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: PIN_EDITOR_COMMAND_ID,
weight: KeybindingWeight.WorkbenchContrib,
when: ActiveEditorStickyContext.toNegated(),
primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.Shift | KeyCode.Enter),
handler: async (accessor, resourceOrContext?: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
const editorGroupService = accessor.get(IEditorGroupsService);
const { group, editor } = resolveCommandsContext(editorGroupService, getCommandsContext(resourceOrContext, context));
if (group && editor) {
return group.stickEditor(editor);
}
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: UNPIN_EDITOR_COMMAND_ID,
weight: KeybindingWeight.WorkbenchContrib,
when: ActiveEditorStickyContext,
primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.Shift | KeyCode.Enter),
handler: async (accessor, resourceOrContext?: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
const editorGroupService = accessor.get(IEditorGroupsService);
const { group, editor } = resolveCommandsContext(editorGroupService, getCommandsContext(resourceOrContext, context));
if (group && editor) {
return group.unstickEditor(editor);
}
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: SHOW_EDITORS_IN_GROUP,
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: undefined,
handler: (accessor, resourceOrContext?: URI | IEditorCommandsContext, context?: IEditorCommandsContext) => {
const editorGroupService = accessor.get(IEditorGroupsService);
const quickInputService = accessor.get(IQuickInputService);
const commandsContext = getCommandsContext(resourceOrContext, context);
if (commandsContext && typeof commandsContext.groupId === 'number') {
const group = editorGroupService.getGroup(commandsContext.groupId);
if (group) {
editorGroupService.activateGroup(group); // we need the group to be active
}
}
return quickInputService.quickAccess.show(ActiveGroupEditorsByMostRecentlyUsedQuickAccess.PREFIX);
}
});
}
function getEditorsContext(accessor: ServicesAccessor, resourceOrContext?: URI | IEditorCommandsContext, context?: IEditorCommandsContext): { editors: IEditorCommandsContext[], groups: Array<IEditorGroup | undefined> } {
const editorGroupService = accessor.get(IEditorGroupsService);
const listService = accessor.get(IListService);
const editorContext = getMultiSelectedEditorContexts(getCommandsContext(resourceOrContext, context), listService, editorGroupService);
const activeGroup = editorGroupService.activeGroup;
if (editorContext.length === 0 && activeGroup.activeEditor) {
// add the active editor as fallback
editorContext.push({
groupId: activeGroup.id,
editorIndex: activeGroup.getIndexOfEditor(activeGroup.activeEditor)
});
}
return {
editors: editorContext,
groups: distinct(editorContext.map(context => context.groupId)).map(groupId => editorGroupService.getGroup(groupId))
};
}
function getCommandsContext(resourceOrContext?: URI | IEditorCommandsContext, context?: IEditorCommandsContext): IEditorCommandsContext | undefined {
if (URI.isUri(resourceOrContext)) {
return context;
}
if (resourceOrContext && typeof resourceOrContext.groupId === 'number') {
return resourceOrContext;
}
if (context && typeof context.groupId === 'number') {
return context;
}
return undefined;
}
function resolveCommandsContext(editorGroupService: IEditorGroupsService, context?: IEditorCommandsContext): { group: IEditorGroup, editor?: IEditorInput } {
// Resolve from context
let group = context && typeof context.groupId === 'number' ? editorGroupService.getGroup(context.groupId) : undefined;
let editor = group && context && typeof context.editorIndex === 'number' ? withNullAsUndefined(group.getEditorByIndex(context.editorIndex)) : undefined;
// Fallback to active group as needed
if (!group) {
group = editorGroupService.activeGroup;
}
// Fallback to active editor as needed
if (!editor) {
editor = withNullAsUndefined(group.activeEditor);
}
return { group, editor };
}
export function getMultiSelectedEditorContexts(editorContext: IEditorCommandsContext | undefined, listService: IListService, editorGroupService: IEditorGroupsService): IEditorCommandsContext[] {
// First check for a focused list to return the selected items from
const list = listService.lastFocusedList;
if (list instanceof List && list.getHTMLElement() === document.activeElement) {
const elementToContext = (element: IEditorIdentifier | IEditorGroup) => {
if (isEditorGroup(element)) {
return { groupId: element.id, editorIndex: undefined };
}
const group = editorGroupService.getGroup(element.groupId);
return { groupId: element.groupId, editorIndex: group ? group.getIndexOfEditor(element.editor) : -1 };
};
const onlyEditorGroupAndEditor = (e: IEditorIdentifier | IEditorGroup) => isEditorGroup(e) || isEditorIdentifier(e);
const focusedElements: Array<IEditorIdentifier | IEditorGroup> = list.getFocusedElements().filter(onlyEditorGroupAndEditor);
const focus = editorContext ? editorContext : focusedElements.length ? focusedElements.map(elementToContext)[0] : undefined; // need to take into account when editor context is { group: group }
if (focus) {
const selection: Array<IEditorIdentifier | IEditorGroup> = list.getSelectedElements().filter(onlyEditorGroupAndEditor);
// Only respect selection if it contains focused element
if (selection?.some(s => {
if (isEditorGroup(s)) {
return s.id === focus.groupId;
}
const group = editorGroupService.getGroup(s.groupId);
return s.groupId === focus.groupId && (group ? group.getIndexOfEditor(s.editor) : -1) === focus.editorIndex;
})) {
return selection.map(elementToContext);
}
return [focus];
}
}
// Otherwise go with passed in context
return !!editorContext ? [editorContext] : [];
}
function isEditorGroup(thing: unknown): thing is IEditorGroup {
const group = thing as IEditorGroup;
return group && typeof group.id === 'number' && Array.isArray(group.editors);
}
function isEditorIdentifier(thing: unknown): thing is IEditorIdentifier {
const identifier = thing as IEditorIdentifier;
return identifier && typeof identifier.groupId === 'number';
}
export function setup(): void {
registerActiveEditorMoveCommand();
registerEditorGroupsLayoutCommand();
registerDiffEditorCommands();
registerOpenEditorAPICommands();
registerOpenEditorAtIndexCommands();
registerCloseEditorCommands();
registerOtherEditorCommands();
registerFocusEditorGroupAtIndexCommands();
registerSplitEditorCommands();
registerFocusEditorGroupWihoutWrapCommands();
}
| src/vs/workbench/browser/parts/editor/editorCommands.ts | 0 | https://github.com/microsoft/vscode/commit/0657df6e82ff9e6900c32a7edffce9aa98879857 | [
0.002192371990531683,
0.0001930200232891366,
0.00016557681374251842,
0.00017204973846673965,
0.00019311028881929815
] |
{
"id": 3,
"code_window": [
"\n",
"export class SCMAccessibilityProvider implements IListAccessibilityProvider<TreeElement> {\n",
"\n",
"\tconstructor(@ILabelService private readonly labelService: ILabelService) { }\n",
"\n",
"\tgetWidgetAriaLabel(): string {\n",
"\t\treturn localize('scm', \"Source Control Management\");\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tconstructor(\n",
"\t\t@ILabelService private readonly labelService: ILabelService,\n",
"\t\t@IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService\n",
"\t) { }\n"
],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewPane.ts",
"type": "replace",
"edit_start_line_idx": 688
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
//@ts-check
'use strict';
const withDefaults = require('../shared.webpack.config');
module.exports = withDefaults({
context: __dirname,
entry: {
main: './src/main.ts',
},
resolve: {
mainFields: ['module', 'main']
}
});
| extensions/gulp/extension.webpack.config.js | 0 | https://github.com/microsoft/vscode/commit/0657df6e82ff9e6900c32a7edffce9aa98879857 | [
0.0001775814889697358,
0.00017484011186752468,
0.00017139526607934386,
0.00017554360965732485,
0.000002574038262537215
] |
{
"id": 3,
"code_window": [
"\n",
"export class SCMAccessibilityProvider implements IListAccessibilityProvider<TreeElement> {\n",
"\n",
"\tconstructor(@ILabelService private readonly labelService: ILabelService) { }\n",
"\n",
"\tgetWidgetAriaLabel(): string {\n",
"\t\treturn localize('scm', \"Source Control Management\");\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tconstructor(\n",
"\t\t@ILabelService private readonly labelService: ILabelService,\n",
"\t\t@IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService\n",
"\t) { }\n"
],
"file_path": "src/vs/workbench/contrib/scm/browser/scmViewPane.ts",
"type": "replace",
"edit_start_line_idx": 688
} | /*---------------------------------------------------------------------------------------------
* 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/paneviewlet';
import * as nls from 'vs/nls';
import { Event, Emitter } from 'vs/base/common/event';
import { foreground } from 'vs/platform/theme/common/colorRegistry';
import { attachButtonStyler, attachLinkStyler, attachProgressBarStyler } from 'vs/platform/theme/common/styler';
import { PANEL_BACKGROUND, SIDE_BAR_BACKGROUND } from 'vs/workbench/common/theme';
import { after, append, $, trackFocus, EventType, addDisposableListener, createCSSRule, asCSSUrl } from 'vs/base/browser/dom';
import { IDisposable, Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { IAction } from 'vs/base/common/actions';
import { ActionsOrientation, IActionViewItem, prepareActions } from 'vs/base/browser/ui/actionbar/actionbar';
import { Registry } from 'vs/platform/registry/common/platform';
import { ToolBar } from 'vs/base/browser/ui/toolbar/toolbar';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IThemeService, ThemeIcon } from 'vs/platform/theme/common/themeService';
import { IPaneOptions, Pane, IPaneStyles } from 'vs/base/browser/ui/splitview/paneview';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { Extensions as ViewContainerExtensions, IView, IViewDescriptorService, ViewContainerLocation, IViewsRegistry, IViewContentDescriptor, defaultViewIcon, IViewsService, ViewContainerLocationToString } from 'vs/workbench/common/views';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { assertIsDefined } from 'vs/base/common/types';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { MenuId, Action2, IAction2Options, IMenuService } from 'vs/platform/actions/common/actions';
import { createActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem';
import { parseLinkedText } from 'vs/base/common/linkedText';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { Button } from 'vs/base/browser/ui/button/button';
import { Link } from 'vs/platform/opener/browser/link';
import { Orientation } from 'vs/base/browser/ui/sash/sash';
import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar';
import { CompositeProgressIndicator } from 'vs/workbench/services/progress/browser/progressIndicator';
import { IProgressIndicator } from 'vs/platform/progress/common/progress';
import { DomScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement';
import { ScrollbarVisibility } from 'vs/base/common/scrollable';
import { URI } from 'vs/base/common/uri';
import { registerIcon } from 'vs/platform/theme/common/iconRegistry';
import { Codicon } from 'vs/base/common/codicons';
import { CompositeMenuActions } from 'vs/workbench/browser/menuActions';
export interface IViewPaneOptions extends IPaneOptions {
id: string;
showActionsAlways?: boolean;
titleMenuId?: MenuId;
}
type WelcomeActionClassification = {
viewId: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
uri: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
};
const viewPaneContainerExpandedIcon = registerIcon('view-pane-container-expanded', Codicon.chevronDown, nls.localize('viewPaneContainerExpandedIcon', 'Icon for an expanded view pane container.'));
const viewPaneContainerCollapsedIcon = registerIcon('view-pane-container-collapsed', Codicon.chevronRight, nls.localize('viewPaneContainerCollapsedIcon', 'Icon for a collapsed view pane container.'));
const viewsRegistry = Registry.as<IViewsRegistry>(ViewContainerExtensions.ViewsRegistry);
interface IItem {
readonly descriptor: IViewContentDescriptor;
visible: boolean;
}
class ViewWelcomeController {
private _onDidChange = new Emitter<void>();
readonly onDidChange = this._onDidChange.event;
private defaultItem: IItem | undefined;
private items: IItem[] = [];
get contents(): IViewContentDescriptor[] {
const visibleItems = this.items.filter(v => v.visible);
if (visibleItems.length === 0 && this.defaultItem) {
return [this.defaultItem.descriptor];
}
return visibleItems.map(v => v.descriptor);
}
private disposables = new DisposableStore();
constructor(
private id: string,
@IContextKeyService private contextKeyService: IContextKeyService,
) {
contextKeyService.onDidChangeContext(this.onDidChangeContext, this, this.disposables);
Event.filter(viewsRegistry.onDidChangeViewWelcomeContent, id => id === this.id)(this.onDidChangeViewWelcomeContent, this, this.disposables);
this.onDidChangeViewWelcomeContent();
}
private onDidChangeViewWelcomeContent(): void {
const descriptors = viewsRegistry.getViewWelcomeContent(this.id);
this.items = [];
for (const descriptor of descriptors) {
if (descriptor.when === 'default') {
this.defaultItem = { descriptor, visible: true };
} else {
const visible = descriptor.when ? this.contextKeyService.contextMatchesRules(descriptor.when) : true;
this.items.push({ descriptor, visible });
}
}
this._onDidChange.fire();
}
private onDidChangeContext(): void {
let didChange = false;
for (const item of this.items) {
if (!item.descriptor.when || item.descriptor.when === 'default') {
continue;
}
const visible = this.contextKeyService.contextMatchesRules(item.descriptor.when);
if (item.visible === visible) {
continue;
}
item.visible = visible;
didChange = true;
}
if (didChange) {
this._onDidChange.fire();
}
}
dispose(): void {
this.disposables.dispose();
}
}
class ViewMenuActions extends CompositeMenuActions {
constructor(
element: HTMLElement,
viewId: string,
menuId: MenuId,
contextMenuId: MenuId,
@IContextKeyService contextKeyService: IContextKeyService,
@IMenuService menuService: IMenuService,
@IViewDescriptorService viewDescriptorService: IViewDescriptorService,
) {
const scopedContextKeyService = contextKeyService.createScoped(element);
scopedContextKeyService.createKey('view', viewId);
const viewLocationKey = scopedContextKeyService.createKey('viewLocation', ViewContainerLocationToString(viewDescriptorService.getViewLocationById(viewId)!));
super(menuId, contextMenuId, { shouldForwardArgs: true }, scopedContextKeyService, menuService);
this._register(scopedContextKeyService);
this._register(Event.filter(viewDescriptorService.onDidChangeLocation, e => e.views.some(view => view.id === viewId))(() => viewLocationKey.set(ViewContainerLocationToString(viewDescriptorService.getViewLocationById(viewId)!))));
}
}
export abstract class ViewPane extends Pane implements IView {
private static readonly AlwaysShowActionsConfig = 'workbench.view.alwaysShowHeaderActions';
private _onDidFocus = this._register(new Emitter<void>());
readonly onDidFocus: Event<void> = this._onDidFocus.event;
private _onDidBlur = this._register(new Emitter<void>());
readonly onDidBlur: Event<void> = this._onDidBlur.event;
private _onDidChangeBodyVisibility = this._register(new Emitter<boolean>());
readonly onDidChangeBodyVisibility: Event<boolean> = this._onDidChangeBodyVisibility.event;
protected _onDidChangeTitleArea = this._register(new Emitter<void>());
readonly onDidChangeTitleArea: Event<void> = this._onDidChangeTitleArea.event;
protected _onDidChangeViewWelcomeState = this._register(new Emitter<void>());
readonly onDidChangeViewWelcomeState: Event<void> = this._onDidChangeViewWelcomeState.event;
private _isVisible: boolean = false;
readonly id: string;
private _title: string;
public get title(): string {
return this._title;
}
private _titleDescription: string | undefined;
public get titleDescription(): string | undefined {
return this._titleDescription;
}
readonly menuActions: ViewMenuActions;
private progressBar!: ProgressBar;
private progressIndicator!: IProgressIndicator;
private toolbar?: ToolBar;
private readonly showActionsAlways: boolean = false;
private headerContainer?: HTMLElement;
private titleContainer?: HTMLElement;
private titleDescriptionContainer?: HTMLElement;
private iconContainer?: HTMLElement;
protected twistiesContainer?: HTMLElement;
private bodyContainer!: HTMLElement;
private viewWelcomeContainer!: HTMLElement;
private viewWelcomeDisposable: IDisposable = Disposable.None;
private viewWelcomeController: ViewWelcomeController;
constructor(
options: IViewPaneOptions,
@IKeybindingService protected keybindingService: IKeybindingService,
@IContextMenuService protected contextMenuService: IContextMenuService,
@IConfigurationService protected readonly configurationService: IConfigurationService,
@IContextKeyService protected contextKeyService: IContextKeyService,
@IViewDescriptorService protected viewDescriptorService: IViewDescriptorService,
@IInstantiationService protected instantiationService: IInstantiationService,
@IOpenerService protected openerService: IOpenerService,
@IThemeService protected themeService: IThemeService,
@ITelemetryService protected telemetryService: ITelemetryService,
) {
super({ ...options, ...{ orientation: viewDescriptorService.getViewLocationById(options.id) === ViewContainerLocation.Panel ? Orientation.HORIZONTAL : Orientation.VERTICAL } });
this.id = options.id;
this._title = options.title;
this._titleDescription = options.titleDescription;
this.showActionsAlways = !!options.showActionsAlways;
this.menuActions = this._register(this.instantiationService.createInstance(ViewMenuActions, this.element, this.id, options.titleMenuId || MenuId.ViewTitle, MenuId.ViewTitleContext));
this._register(this.menuActions.onDidChange(() => this.updateActions()));
this.viewWelcomeController = new ViewWelcomeController(this.id, contextKeyService);
}
get headerVisible(): boolean {
return super.headerVisible;
}
set headerVisible(visible: boolean) {
super.headerVisible = visible;
this.element.classList.toggle('merged-header', !visible);
}
setVisible(visible: boolean): void {
if (this._isVisible !== visible) {
this._isVisible = visible;
if (this.isExpanded()) {
this._onDidChangeBodyVisibility.fire(visible);
}
}
}
isVisible(): boolean {
return this._isVisible;
}
isBodyVisible(): boolean {
return this._isVisible && this.isExpanded();
}
setExpanded(expanded: boolean): boolean {
const changed = super.setExpanded(expanded);
if (changed) {
this._onDidChangeBodyVisibility.fire(expanded);
}
if (this.twistiesContainer) {
this.twistiesContainer.classList.remove(...ThemeIcon.asClassNameArray(this.getTwistyIcon(!expanded)));
this.twistiesContainer.classList.add(...ThemeIcon.asClassNameArray(this.getTwistyIcon(expanded)));
}
return changed;
}
render(): void {
super.render();
const focusTracker = trackFocus(this.element);
this._register(focusTracker);
this._register(focusTracker.onDidFocus(() => this._onDidFocus.fire()));
this._register(focusTracker.onDidBlur(() => this._onDidBlur.fire()));
}
protected renderHeader(container: HTMLElement): void {
this.headerContainer = container;
this.twistiesContainer = append(container, $(ThemeIcon.asCSSSelector(this.getTwistyIcon(this.isExpanded()))));
this.renderHeaderTitle(container, this.title);
const actions = append(container, $('.actions'));
actions.classList.toggle('show', this.showActionsAlways);
this.toolbar = new ToolBar(actions, this.contextMenuService, {
orientation: ActionsOrientation.HORIZONTAL,
actionViewItemProvider: action => this.getActionViewItem(action),
ariaLabel: nls.localize('viewToolbarAriaLabel', "{0} actions", this.title),
getKeyBinding: action => this.keybindingService.lookupKeybinding(action.id),
renderDropdownAsChildElement: true
});
this._register(this.toolbar);
this.setActions();
this._register(addDisposableListener(actions, EventType.CLICK, e => e.preventDefault()));
this._register(this.viewDescriptorService.getViewContainerModel(this.viewDescriptorService.getViewContainerByViewId(this.id)!)!.onDidChangeContainerInfo(({ title }) => {
this.updateTitle(this.title);
}));
const onDidRelevantConfigurationChange = Event.filter(this.configurationService.onDidChangeConfiguration, e => e.affectsConfiguration(ViewPane.AlwaysShowActionsConfig));
this._register(onDidRelevantConfigurationChange(this.updateActionsVisibility, this));
this.updateActionsVisibility();
}
protected getTwistyIcon(expanded: boolean): ThemeIcon {
return expanded ? viewPaneContainerExpandedIcon : viewPaneContainerCollapsedIcon;
}
style(styles: IPaneStyles): void {
super.style(styles);
const icon = this.getIcon();
if (this.iconContainer) {
const fgColor = styles.headerForeground || this.themeService.getColorTheme().getColor(foreground);
if (URI.isUri(icon)) {
// Apply background color to activity bar item provided with iconUrls
this.iconContainer.style.backgroundColor = fgColor ? fgColor.toString() : '';
this.iconContainer.style.color = '';
} else {
// Apply foreground color to activity bar items provided with codicons
this.iconContainer.style.color = fgColor ? fgColor.toString() : '';
this.iconContainer.style.backgroundColor = '';
}
}
}
private getIcon(): ThemeIcon | URI {
return this.viewDescriptorService.getViewDescriptorById(this.id)?.containerIcon || defaultViewIcon;
}
protected renderHeaderTitle(container: HTMLElement, title: string): void {
this.iconContainer = append(container, $('.icon', undefined));
const icon = this.getIcon();
let cssClass: string | undefined = undefined;
if (URI.isUri(icon)) {
cssClass = `view-${this.id.replace(/[\.\:]/g, '-')}`;
const iconClass = `.pane-header .icon.${cssClass}`;
createCSSRule(iconClass, `
mask: ${asCSSUrl(icon)} no-repeat 50% 50%;
mask-size: 24px;
-webkit-mask: ${asCSSUrl(icon)} no-repeat 50% 50%;
-webkit-mask-size: 16px;
`);
} else if (ThemeIcon.isThemeIcon(icon)) {
cssClass = ThemeIcon.asClassName(icon);
}
if (cssClass) {
this.iconContainer.classList.add(...cssClass.split(' '));
}
const calculatedTitle = this.calculateTitle(title);
this.titleContainer = append(container, $('h3.title', { title: calculatedTitle }, calculatedTitle));
if (this._titleDescription) {
this.setTitleDescription(this._titleDescription);
}
this.iconContainer.title = calculatedTitle;
this.iconContainer.setAttribute('aria-label', calculatedTitle);
}
protected updateTitle(title: string): void {
const calculatedTitle = this.calculateTitle(title);
if (this.titleContainer) {
this.titleContainer.textContent = calculatedTitle;
this.titleContainer.setAttribute('title', calculatedTitle);
}
if (this.iconContainer) {
this.iconContainer.title = calculatedTitle;
this.iconContainer.setAttribute('aria-label', calculatedTitle);
}
this._title = title;
this._onDidChangeTitleArea.fire();
}
private setTitleDescription(description: string | undefined) {
if (this.titleDescriptionContainer) {
this.titleDescriptionContainer.textContent = description ?? '';
this.titleDescriptionContainer.setAttribute('title', description ?? '');
}
else if (description && this.titleContainer) {
this.titleDescriptionContainer = after(this.titleContainer, $('span.description', { title: description }, description));
}
}
protected updateTitleDescription(description?: string | undefined): void {
this.setTitleDescription(description);
this._titleDescription = description;
this._onDidChangeTitleArea.fire();
}
private calculateTitle(title: string): string {
const viewContainer = this.viewDescriptorService.getViewContainerByViewId(this.id)!;
const model = this.viewDescriptorService.getViewContainerModel(viewContainer);
const viewDescriptor = this.viewDescriptorService.getViewDescriptorById(this.id);
const isDefault = this.viewDescriptorService.getDefaultContainerById(this.id) === viewContainer;
if (!isDefault && viewDescriptor?.containerTitle && model.title !== viewDescriptor.containerTitle) {
return `${viewDescriptor.containerTitle}: ${title}`;
}
return title;
}
private scrollableElement!: DomScrollableElement;
protected renderBody(container: HTMLElement): void {
this.bodyContainer = container;
const viewWelcomeContainer = append(container, $('.welcome-view'));
this.viewWelcomeContainer = $('.welcome-view-content', { tabIndex: 0 });
this.scrollableElement = this._register(new DomScrollableElement(this.viewWelcomeContainer, {
alwaysConsumeMouseWheel: true,
horizontal: ScrollbarVisibility.Hidden,
vertical: ScrollbarVisibility.Visible,
}));
append(viewWelcomeContainer, this.scrollableElement.getDomNode());
const onViewWelcomeChange = Event.any(this.viewWelcomeController.onDidChange, this.onDidChangeViewWelcomeState);
this._register(onViewWelcomeChange(this.updateViewWelcome, this));
this.updateViewWelcome();
}
protected layoutBody(height: number, width: number): void {
this.viewWelcomeContainer.style.height = `${height}px`;
this.viewWelcomeContainer.style.width = `${width}px`;
this.viewWelcomeContainer.classList.toggle('wide', width > 640);
this.scrollableElement.scanDomNode();
}
getProgressIndicator() {
if (this.progressBar === undefined) {
// Progress bar
this.progressBar = this._register(new ProgressBar(this.element));
this._register(attachProgressBarStyler(this.progressBar, this.themeService));
this.progressBar.hide();
}
if (this.progressIndicator === undefined) {
this.progressIndicator = this.instantiationService.createInstance(CompositeProgressIndicator, assertIsDefined(this.progressBar), this.id, this.isBodyVisible());
}
return this.progressIndicator;
}
protected getProgressLocation(): string {
return this.viewDescriptorService.getViewContainerByViewId(this.id)!.id;
}
protected getBackgroundColor(): string {
return this.viewDescriptorService.getViewLocationById(this.id) === ViewContainerLocation.Panel ? PANEL_BACKGROUND : SIDE_BAR_BACKGROUND;
}
focus(): void {
if (this.shouldShowWelcome()) {
this.viewWelcomeContainer.focus();
} else if (this.element) {
this.element.focus();
this._onDidFocus.fire();
}
}
private setActions(): void {
if (this.toolbar) {
this.toolbar.setActions(prepareActions(this.menuActions.getPrimaryActions()), prepareActions(this.menuActions.getSecondaryActions()));
this.toolbar.context = this.getActionsContext();
}
}
private updateActionsVisibility(): void {
if (!this.headerContainer) {
return;
}
const shouldAlwaysShowActions = this.configurationService.getValue<boolean>('workbench.view.alwaysShowHeaderActions');
this.headerContainer.classList.toggle('actions-always-visible', shouldAlwaysShowActions);
}
protected updateActions(): void {
this.setActions();
this._onDidChangeTitleArea.fire();
}
getActionViewItem(action: IAction): IActionViewItem | undefined {
return createActionViewItem(this.instantiationService, action);
}
getActionsContext(): unknown {
return undefined;
}
getOptimalWidth(): number {
return 0;
}
saveState(): void {
// Subclasses to implement for saving state
}
private updateViewWelcome(): void {
this.viewWelcomeDisposable.dispose();
if (!this.shouldShowWelcome()) {
this.bodyContainer.classList.remove('welcome');
this.viewWelcomeContainer.innerText = '';
this.scrollableElement.scanDomNode();
return;
}
const contents = this.viewWelcomeController.contents;
if (contents.length === 0) {
this.bodyContainer.classList.remove('welcome');
this.viewWelcomeContainer.innerText = '';
this.scrollableElement.scanDomNode();
return;
}
const disposables = new DisposableStore();
this.bodyContainer.classList.add('welcome');
this.viewWelcomeContainer.innerText = '';
for (const { content, precondition } of contents) {
const lines = content.split('\n');
for (let line of lines) {
line = line.trim();
if (!line) {
continue;
}
const linkedText = parseLinkedText(line);
if (linkedText.nodes.length === 1 && typeof linkedText.nodes[0] !== 'string') {
const node = linkedText.nodes[0];
const buttonContainer = append(this.viewWelcomeContainer, $('.button-container'));
const button = new Button(buttonContainer, { title: node.title, supportIcons: true });
button.label = node.label;
button.onDidClick(_ => {
this.telemetryService.publicLog2<{ viewId: string, uri: string }, WelcomeActionClassification>('views.welcomeAction', { viewId: this.id, uri: node.href });
this.openerService.open(node.href);
}, null, disposables);
disposables.add(button);
disposables.add(attachButtonStyler(button, this.themeService));
if (precondition) {
const updateEnablement = () => button.enabled = this.contextKeyService.contextMatchesRules(precondition);
updateEnablement();
const keys = new Set();
precondition.keys().forEach(key => keys.add(key));
const onDidChangeContext = Event.filter(this.contextKeyService.onDidChangeContext, e => e.affectsSome(keys));
onDidChangeContext(updateEnablement, null, disposables);
}
} else {
const p = append(this.viewWelcomeContainer, $('p'));
for (const node of linkedText.nodes) {
if (typeof node === 'string') {
append(p, document.createTextNode(node));
} else {
const link = this.instantiationService.createInstance(Link, node);
append(p, link.el);
disposables.add(link);
disposables.add(attachLinkStyler(link, this.themeService));
if (precondition && node.href.startsWith('command:')) {
const updateEnablement = () => link.style({ disabled: !this.contextKeyService.contextMatchesRules(precondition) });
updateEnablement();
const keys = new Set();
precondition.keys().forEach(key => keys.add(key));
const onDidChangeContext = Event.filter(this.contextKeyService.onDidChangeContext, e => e.affectsSome(keys));
onDidChangeContext(updateEnablement, null, disposables);
}
}
}
}
}
}
this.scrollableElement.scanDomNode();
this.viewWelcomeDisposable = disposables;
}
shouldShowWelcome(): boolean {
return false;
}
}
export abstract class ViewAction<T extends IView> extends Action2 {
constructor(readonly desc: Readonly<IAction2Options> & { viewId: string }) {
super(desc);
}
run(accessor: ServicesAccessor, ...args: any[]) {
const view = accessor.get(IViewsService).getActiveViewWithId(this.desc.viewId);
if (view) {
return this.runInView(accessor, <T>view, ...args);
}
}
abstract runInView(accessor: ServicesAccessor, view: T, ...args: any[]): any;
}
| src/vs/workbench/browser/parts/views/viewPane.ts | 0 | https://github.com/microsoft/vscode/commit/0657df6e82ff9e6900c32a7edffce9aa98879857 | [
0.00017643717001192272,
0.00017074863717425615,
0.0001599091774551198,
0.00017101000412367284,
0.000003130310915366863
] |
{
"id": 0,
"code_window": [
" this.actionSheetRef = actionSheetRef;\n",
" });\n",
" }\n",
"\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" onPageWillLeave() {\n",
" let actionSheet = this.actionSheet.get();\n",
" if (actionSheet) {\n",
" actionSheet.close();\n",
" }\n",
" }\n",
"\n"
],
"file_path": "demos/component-docs/actionSheet/actionSheet.ts",
"type": "add",
"edit_start_line_idx": 67
} | import {Page, Popup} from 'ionic/ionic';
import {AndroidAttribute} from '../helpers';
import {forwardRef} from 'angular2/angular2';
@Page({
templateUrl: 'popups/popups.html',
directives: [forwardRef(() => AndroidAttribute)]
})
export class PopupsPage {
constructor(popup: Popup) {
this.popup = popup;
}
doAlert() {
this.popup.alert({
title: "New Friend!",
template: "Your friend, Obi wan Kenobi, just accepted your friend request!",
cssClass: 'my-alert'
});
}
doPrompt() {
this.popup.prompt({
title: "New Album",
template: "Enter a name for this new album you're so keen on adding",
inputPlaceholder: "Title",
okText: "Save"
});
}
doConfirm() {
this.popup.confirm({
title: "Use this lightsaber?",
subTitle: "You can't exchange lightsabers",
template: "Do you agree to use this lightsaber to do good across the intergalactic galaxy?",
cancelText: "Disagree",
okText: "Agree"
});
}
}
| demos/component-docs/popups/popups.ts | 1 | https://github.com/ionic-team/ionic-framework/commit/7b13051a52d37c16f0bfc5fa118a58cffd901c3a | [
0.00017838674830272794,
0.000172135783941485,
0.00016664483700878918,
0.00017172899970319122,
0.0000037863487705180887
] |
{
"id": 0,
"code_window": [
" this.actionSheetRef = actionSheetRef;\n",
" });\n",
" }\n",
"\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" onPageWillLeave() {\n",
" let actionSheet = this.actionSheet.get();\n",
" if (actionSheet) {\n",
" actionSheet.close();\n",
" }\n",
" }\n",
"\n"
],
"file_path": "demos/component-docs/actionSheet/actionSheet.ts",
"type": "add",
"edit_start_line_idx": 67
} | import {IonicView, Animation, IonicApp} from 'ionic/ionic';
import {SinkPage} from '../sink-page';
let opacity = 0.2;
let rotateZ = '180deg';
let translateX = '100px';
let scale = 0.6;
@IonicView({
template: `
<ion-navbar *navbar><ion-nav-items primary><button icon (click)="toggleMenu()"><i class="icon ion-navicon"></i></button></ion-nav-items><ion-title>Animation</ion-title></ion-navbar>
<style>
.ball-container {
position: absolute;
top: 300px;
left: 20px;
border: 1px solid gray;
width: 300px;
height: 51px;
}
.ball {
position: absolute;
width: 50px;
height: 50px;
background: blue;
}
</style>
<ion-content padding>
<h2>Animation</h2>
<p>
Ionic comes with a powerful Animation library based on the emerging Web Animation API. Trigger
animations based on user actions, step (or "scrub") through during a drag gesture, or add
realistic physics effects to your app. The Animation API is a major improvement over CSS animations.
</p>
<p>
<button (click)="play($event)">Play</button>
<button (click)="pause($event)">Pause</button>
</p>
<div class="ball-container">
<div class="ball"></div>
</div>
<div style="position: absolute; top: 400px; left: 20px;">
<div class="red square" style="position:absolute; width:100px; height:100px; background:red; top: 0; left: 0;"></div>
<div class="green square" style="position:absolute; width:100px; height:100px; background:green; top: 0; left: 100px;"></div>
<div class="blue square" style="position:absolute; width:100px; height:100px; background:blue; top: 0; left: 200px;"></div>
</div>
<div style="position: absolute; top: 500px; left: 20px;">
<div class="yellow square2" style="position:absolute; width:100px; height:100px; background:yellow; top: 0; left: 0;"></div>
<div class="purple square2" style="position:absolute; width:100px; height:100px; background:purple; top: 0; left: 100px;"></div>
<div class="maroon square2" style="position:absolute; width:100px; height:100px; background:maroon; top: 0; left: 200px;"></div>
</div>
<p>
<input type="range" (input)="progress($event)" value="0" min="0" step="0.001" max="1" style="width:200px; margin-left: 100px">
</p>
</ion-content>
`
})
export class AnimationPage extends SinkPage {
constructor(app: IonicApp) {
super(app);
this.animation = new Animation();
this.animation
.duration(2000)
.easing('spring', { damping: 6, elasticity: 10 });
var ball = new Animation( document.querySelector('.ball') );
ball
.from('translateX', '0px')
.to('translateX', '250px')
this.animation.add(ball);
var row1 = new Animation( document.querySelectorAll('.square') );
row1
.from('opacity', 0.8)
.to('opacity', 0.2)
this.animation.add(row1);
var row2 = new Animation( document.querySelectorAll('.square2') );
row2
.from('rotate', '0deg')
.from('scale', '1')
.to('rotate', '90deg')
.to('scale', '0.5')
.before.addClass('added-before-play')
.after.addClass('added-after-finish')
this.animation.add(row1, row2);
this.animation.onReady(animation => {
console.log('onReady', animation);
});
this.animation.onPlay(animation => {
console.log('onPlay', animation);
});
this.animation.onFinish(animation => {
console.log('onFinish', animation);
});
}
play() {
this.animation.play();
}
pause() {
this.animation.pause();
}
progress(ev) {
this.animation.progress( parseFloat(ev.srcElement.value) );
}
}
| demos/sink/pages/animation.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/7b13051a52d37c16f0bfc5fa118a58cffd901c3a | [
0.0001740860752761364,
0.00017074598872568458,
0.00016772277012933046,
0.0001709620119072497,
0.000001981154127861373
] |
{
"id": 0,
"code_window": [
" this.actionSheetRef = actionSheetRef;\n",
" });\n",
" }\n",
"\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" onPageWillLeave() {\n",
" let actionSheet = this.actionSheet.get();\n",
" if (actionSheet) {\n",
" actionSheet.close();\n",
" }\n",
" }\n",
"\n"
],
"file_path": "demos/component-docs/actionSheet/actionSheet.ts",
"type": "add",
"edit_start_line_idx": 67
} |
export class Transition {
static create(navCtrl, opts = {}) {
const name = opts.animation || 'ios';
let TransitionClass = transitionRegistry[name];
if (!TransitionClass) {
TransitionClass = transitionRegistry.ios;
}
return new TransitionClass(navCtrl, opts);
}
static register(name, TransitionClass) {
transitionRegistry[name] = TransitionClass;
}
}
let transitionRegistry = {};
| ionic/transitions/transition.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/7b13051a52d37c16f0bfc5fa118a58cffd901c3a | [
0.00017399713397026062,
0.00017026647401507944,
0.00016647283337078989,
0.0001703294547041878,
0.0000030721057555638254
] |
{
"id": 0,
"code_window": [
" this.actionSheetRef = actionSheetRef;\n",
" });\n",
" }\n",
"\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" onPageWillLeave() {\n",
" let actionSheet = this.actionSheet.get();\n",
" if (actionSheet) {\n",
" actionSheet.close();\n",
" }\n",
" }\n",
"\n"
],
"file_path": "demos/component-docs/actionSheet/actionSheet.ts",
"type": "add",
"edit_start_line_idx": 67
} | import {App, IonicApp} from 'ionic/ionic';
@App({
templateUrl: 'main.html'
})
class MyApp {
constructor(private app: IonicApp) {
this.extraOptions = {
loop: true
};
this.images = [];
let tags = "amsterdam";
let FLICKR_API_KEY = '504fd7414f6275eb5b657ddbfba80a2c';
let baseUrl = 'https://api.flickr.com/services/rest/';
// TODO: update to use angular2's HTTP Service
Http.get(baseUrl + '?method=flickr.groups.pools.getPhotos&group_id=1463451@N25&safe_search=1&api_key=' + FLICKR_API_KEY + '&jsoncallback=JSON_CALLBACK&format=json&tags=' + tags, {
method: 'jsonp'
}).then((val) => {
this.images = val.photos.photo.slice(0, 20);
setTimeout(() => {
this.slider.update();
});
}, (err) => {
alert('Unable to load images');
console.error(err);
})
}
onInit() {
setTimeout(() => {
this.slider = this.app.getComponent('slider');
console.log('Got slider', this.slider);
});
}
getImageUrl(item) {
return "http://farm"+ item.farm +".static.flickr.com/"+ item.server +"/"+ item.id +"_"+ item.secret + "_z.jpg";
}
doRefresh() {
console.log('DOREFRESH')
}
}
| ionic/components/slides/test/basic/index.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/7b13051a52d37c16f0bfc5fa118a58cffd901c3a | [
0.00017511696205474436,
0.00017096677038352937,
0.00016816989227663726,
0.00016975338803604245,
0.0000025305303097411525
] |
{
"id": 1,
"code_window": [
"\n",
"@Page({\n",
" template: '<ion-nav [root]=\"rootView\"></ion-nav>'\n",
"})\n",
"export class ModalsPage {\n",
" constructor() {\n",
" this.rootView = ModalsFirstPage;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" constructor(modal: Modal) {\n"
],
"file_path": "demos/component-docs/modals/modals.ts",
"type": "replace",
"edit_start_line_idx": 52
} | import {App, IonicApp, Animation, Modal, NavController, Page, Events} from 'ionic/ionic';
import {forwardRef} from 'angular2/angular2';
import * as helpers from '../helpers';
@Page({
templateUrl: 'modals/modals.html',
directives: [forwardRef(() => helpers.AndroidAttribute)]
})
class ModalsFirstPage {
constructor(
nav: NavController,
modal: Modal,
events: Events
) {
this.nav = nav;
this.modal = modal;
}
openModal() {
this.modal.open(ModalsContentPage);
}
}
@Page({
templateUrl: 'modals/modals-content.html',
directives: [forwardRef(() => helpers.AndroidAttribute)]
})
class ModalsContentPage {
constructor(
modal: Modal,
events: Events
) {
this.modal = modal;
}
closeModal() {
let modal = this.modal.get();
if (modal) {
modal.close();
}
}
}
@Page({
template: '<ion-nav [root]="rootView"></ion-nav>'
})
export class ModalsPage {
constructor() {
this.rootView = ModalsFirstPage;
}
}
| demos/component-docs/modals/modals.ts | 1 | https://github.com/ionic-team/ionic-framework/commit/7b13051a52d37c16f0bfc5fa118a58cffd901c3a | [
0.9987815022468567,
0.4177762269973755,
0.0023714201524853706,
0.24735262989997864,
0.43602845072746277
] |
{
"id": 1,
"code_window": [
"\n",
"@Page({\n",
" template: '<ion-nav [root]=\"rootView\"></ion-nav>'\n",
"})\n",
"export class ModalsPage {\n",
" constructor() {\n",
" this.rootView = ModalsFirstPage;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" constructor(modal: Modal) {\n"
],
"file_path": "demos/component-docs/modals/modals.ts",
"type": "replace",
"edit_start_line_idx": 52
} | import {IonicApp, IonicView} from 'ionic/ionic';
import {SinkPage} from '../sink-page';
@IonicView({
template: `
<ion-navbar *navbar><ion-nav-items primary><button icon (click)="toggleMenu()"><i class="icon ion-navicon"></i></button></ion-nav-items><ion-title>Menu</ion-title></ion-navbar>
<ion-content padding>
<h2>Menu</h2>
<p>
Menus slide or swipe in to show more information.
</p>
<p>
Try it! Just swipe from the left edge of the screen to the right to expose
the app menu, or tap the button to toggle the menu:
</p>
<p>
<div class="height: 50px; background-color: E05780; width: 5px; margin-left: -15px"></div>
</p>
<p>
<button (click)="toggleMenu()">Toggle</button>
</p>
</ion-content>
`
})
export class MenuPage extends SinkPage {
constructor(app: IonicApp) {
super(app);
}
openMenu() {
}
}
| demos/sink/pages/aside.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/7b13051a52d37c16f0bfc5fa118a58cffd901c3a | [
0.0043449741788208485,
0.0015991554828360677,
0.000169604696566239,
0.000941021426115185,
0.0017051565228030086
] |
{
"id": 1,
"code_window": [
"\n",
"@Page({\n",
" template: '<ion-nav [root]=\"rootView\"></ion-nav>'\n",
"})\n",
"export class ModalsPage {\n",
" constructor() {\n",
" this.rootView = ModalsFirstPage;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" constructor(modal: Modal) {\n"
],
"file_path": "demos/component-docs/modals/modals.ts",
"type": "replace",
"edit_start_line_idx": 52
} | import {Component, Directive, ElementRef, NgIf, Host, Optional, Renderer, NgZone} from 'angular2/angular2';
import {Gesture} from 'ionic/gestures/gesture';
import {DragGesture} from 'ionic/gestures/drag-gesture';
import {Hammer} from 'ionic/gestures/hammer';
import {List} from 'ionic/components/list/list';
import * as util from 'ionic/util';
import {CSS, raf} from 'ionic/util/dom';
/**
* @name ionItem
* @description
* Creates a list-item that can easily be swiped,
* deleted, reordered, edited, and more.
*
* @usage
* ```html
* <ion-list>
* <ion-item-sliding *ng-for="#item of items" (click)="itemTapped($event, item)">
* {{item.title}}
* <div class="item-note" item-right>
* {{item.note}}
* </div>
* </ion-item>
* </ion-list>
* ```
*/
@Component({
selector: 'ion-item-sliding,[ion-item-sliding]',
inputs: [
'sliding'
],
template:
'<ng-content select="ion-item-options"></ng-content>' +
'<ion-item-sliding-content>' +
'<ng-content select="[item-left]"></ng-content>' +
'<ng-content select="[item-right]"></ng-content>' +
'<ion-item-content>' +
'<ng-content></ng-content>'+
'</ion-item-content>' +
'</ion-item-sliding-content>',
directives: [NgIf]
})
export class ItemSliding {
/**
* TODO
* @param {ElementRef} elementRef A reference to the component's DOM element.
*/
constructor(elementRef: ElementRef, renderer: Renderer, @Optional() @Host() list: List, zone: NgZone) {
this._zone = zone;
renderer.setElementClass(elementRef, 'item', true);
this._isOpen = false;
this._isSlideActive = false;
this._isTransitioning = false;
this._transform = '';
this.list = list;
this.elementRef = elementRef;
this.swipeButtons = {};
this.optionButtons = {};
}
onInit() {
let ele = this.elementRef.nativeElement;
this.itemSlidingContent = ele.querySelector('ion-item-sliding-content');
this.itemOptions = ele.querySelector('ion-item-options');
this.openAmount = 0;
this._zone.runOutsideAngular(() => {
this.gesture = new ItemSlideGesture(this, this.itemSlidingContent, this._zone);
});
}
onDestroy() {
this.gesture && this.gesture.unlisten();
this.itemSlidingContent = this.itemOptionsContent = null;
}
close(andStopDrag) {
this.openAmount = 0;
// Enable it once, it'll get disabled on the next drag
raf(() => {
this.enableAnimation();
if (this.itemSlidingContent) {
this.itemSlidingContent.style[CSS.transform] = 'translateX(0)';
}
});
}
open(amt) {
let el = this.itemSlidingContent;
this.openAmount = amt || 0;
if (this.list) {
this.list.setOpenItem(this);
}
if (amt === '') {
el.style[CSS.transform] = '';
} else {
el.style[CSS.transform] = 'translateX(' + -amt + 'px)';
}
}
isOpen() {
return this.openAmount > 0;
}
getOpenAmt() {
return this.openAmount;
}
disableAnimation() {
this.itemSlidingContent.style[CSS.transition] = 'none';
}
enableAnimation() {
// Clear the explicit transition, allow for CSS one to take over
this.itemSlidingContent.style[CSS.transition] = '';
}
/**
* User did a touchstart
*/
didTouch() {
if (this.isOpen()) {
this.close();
this.didClose = true;
} else {
let openItem = this.list.getOpenItem();
if (openItem && openItem !== this) {
this.didClose = true;
}
if (this.list) {
this.list.closeOpenItem();
}
}
}
}
class ItemSlideGesture extends DragGesture {
constructor(item: ItemSliding, el: Element, zone) {
super(el, {
direction: 'x',
threshold: el.offsetWidth
});
this.item = item;
this.canDrag = true;
this.listen();
zone.runOutsideAngular(() => {
let touchStart = (e) => {
this.item.didTouch();
raf(() => {
this.item.itemOptionsWidth = this.item.itemOptions && this.item.itemOptions.offsetWidth || 0;
})
};
el.addEventListener('touchstart', touchStart);
el.addEventListener('mousedown', touchStart);
let touchEnd = (e) => {
this.item.didClose = false;
};
el.addEventListener('touchend', touchEnd);
el.addEventListener('mouseup', touchEnd);
el.addEventListener('mouseout', touchEnd);
el.addEventListener('mouseleave', touchEnd);
el.addEventListener('touchcancel', touchEnd);
});
}
onDragStart(ev) {
if (this.item.didClose) { return; }
if (!this.item.itemOptionsWidth) { return; }
this.slide = {};
this.slide.offsetX = this.item.getOpenAmt();
this.slide.startX = ev.center[this.direction];
this.slide.started = true;
this.item.disableAnimation();
}
onDrag(ev) {
if (!this.slide || !this.slide.started) return;
this.slide.x = ev.center[this.direction];
this.slide.delta = this.slide.x - this.slide.startX;
let newX = Math.max(0, this.slide.offsetX - this.slide.delta);
let buttonsWidth = this.item.itemOptionsWidth;
if (newX > this.item.itemOptionsWidth) {
// Calculate the new X position, capped at the top of the buttons
newX = -Math.min(-buttonsWidth, -buttonsWidth + (((this.slide.delta + buttonsWidth) * 0.4)));
}
this.item.open(newX);
}
onDragEnd(ev) {
if (!this.slide || !this.slide.started) return;
let buttonsWidth = this.item.itemOptionsWidth;
// If we are currently dragging, we want to snap back into place
// The final resting point X will be the width of the exposed buttons
var restingPoint = this.item.itemOptionsWidth;
// Check if the drag didn't clear the buttons mid-point
// and we aren't moving fast enough to swipe open
if (this.item.openAmount < (buttonsWidth / 2)) {
// If we are going left but too slow, or going right, go back to resting
if (ev.direction & Hammer.DIRECTION_RIGHT) {
// Left
restingPoint = 0;
} else if (Math.abs(ev.velocityX) < 0.3) {
// Right
restingPoint = 0;
}
}
raf(() => {
if (restingPoint === 0) {
// Reset to zero
this.item.open('');
var buttons = this.item.itemOptions;
clearTimeout(this.hideButtonsTimeout);
this.hideButtonsTimeout = setTimeout(() => {
buttons && buttons.classList.add('invisible');
}, 250);
} else {
this.item.open(restingPoint);
}
this.item.enableAnimation();
this.slide = null;
});
}
}
| ionic/components/item/item-sliding.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/7b13051a52d37c16f0bfc5fa118a58cffd901c3a | [
0.0007700326386839151,
0.00022673535568173975,
0.00016528026026207954,
0.00016973703168332577,
0.0001481571380281821
] |
{
"id": 1,
"code_window": [
"\n",
"@Page({\n",
" template: '<ion-nav [root]=\"rootView\"></ion-nav>'\n",
"})\n",
"export class ModalsPage {\n",
" constructor() {\n",
" this.rootView = ModalsFirstPage;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" constructor(modal: Modal) {\n"
],
"file_path": "demos/component-docs/modals/modals.ts",
"type": "replace",
"edit_start_line_idx": 52
} | module.exports = function removePrivateMembers() {
return {
name: 'remove-private-members',
description: 'Remove member docs with @private tags',
$runAfter: ['tags-parsed'],
$runBefore: ['rendering-docs'],
$process: function(docs) {
docs.forEach(function(doc){
if (doc.members) {
doc.members = doc.members.filter(function(member){
return !member.tags.tagsByName.get("private");
})
}
})
return docs;
}
}
};
| scripts/docs/processors/remove-private-members.js | 0 | https://github.com/ionic-team/ionic-framework/commit/7b13051a52d37c16f0bfc5fa118a58cffd901c3a | [
0.00017305831715930253,
0.00017194289830513299,
0.00017082747945096344,
0.00017194289830513299,
0.0000011154188541695476
] |
{
"id": 2,
"code_window": [
" this.rootView = ModalsFirstPage;\n",
" }\n",
"}"
],
"labels": [
"add",
"keep",
"keep"
],
"after_edit": [
" this.modal = modal;\n",
" }\n",
" onPageWillLeave() {\n",
" let modal = this.modal.get();\n",
" if (modal) {\n",
" modal.close();\n",
" }\n"
],
"file_path": "demos/component-docs/modals/modals.ts",
"type": "add",
"edit_start_line_idx": 54
} | import {Platform, Page, ActionSheet} from 'ionic/ionic';
import {AndroidAttribute} from '../helpers';
@Page({
templateUrl: 'actionSheet/actionSheet.html',
directives: [AndroidAttribute]
})
export class ActionSheetPage {
constructor(actionSheet: ActionSheet, platform: Platform) {
this.actionSheet = actionSheet;
this.platform = platform;
}
openMenu() {
if (this.platform.is('android')) {
var androidSheet = {
buttons: [
{ text: 'Share', icon: 'share' },
{ text: 'Play', icon: 'arrow-dropright-circle'},
{ text: 'Favorite', icon: 'ion-md-heart-outline'}
],
destructiveText: 'Delete',
titleText: 'Albums',
cancelText: 'Cancel',
cancel: function() {
console.log('Canceled');
},
destructiveButtonClicked: () => {
console.log('Destructive clicked');
},
buttonClicked: function(index) {
console.log('Button clicked', index);
if (index == 1) { return false; }
return true;
}
};
}
this.actionSheet.open(androidSheet || {
buttons: [
{ text: 'Share'},
{ text: 'Play'},
{ text: 'Favorite'}
],
destructiveText: 'Delete',
titleText: 'Albums',
cancelText: 'Cancel',
cancel: function() {
console.log('Canceled');
},
destructiveButtonClicked: () => {
console.log('Destructive clicked');
},
buttonClicked: function(index) {
console.log('Button clicked', index);
if (index == 1) { return false; }
return true;
}
}).then(actionSheetRef => {
console.log(actionSheetRef);
this.actionSheetRef = actionSheetRef;
});
}
}
| demos/component-docs/actionSheet/actionSheet.ts | 1 | https://github.com/ionic-team/ionic-framework/commit/7b13051a52d37c16f0bfc5fa118a58cffd901c3a | [
0.0001733813842292875,
0.0001693635422270745,
0.00016576670168433338,
0.00016915427113417536,
0.000002471333118592156
] |
{
"id": 2,
"code_window": [
" this.rootView = ModalsFirstPage;\n",
" }\n",
"}"
],
"labels": [
"add",
"keep",
"keep"
],
"after_edit": [
" this.modal = modal;\n",
" }\n",
" onPageWillLeave() {\n",
" let modal = this.modal.get();\n",
" if (modal) {\n",
" modal.close();\n",
" }\n"
],
"file_path": "demos/component-docs/modals/modals.ts",
"type": "add",
"edit_start_line_idx": 54
} |
// Material Design Button
// --------------------------------------------------
$button-md-font-size: 1.4rem !default;
$button-md-min-height: 3.6rem !default;
$button-md-padding: 0 1.1em !default;
$button-md-box-shadow: 0 2px 2px 0 rgba(0,0,0,.14), 0 3px 1px -2px rgba(0,0,0,.2), 0 1px 5px 0 rgba(0,0,0,.12) !default;
$button-md-box-shadow-active: 0 3px 5px rgba(0, 0, 0, 0.14), 0 3px 5px rgba(0, 0, 0, 0.21) !default;
$button-md-border-radius: 2px !default;
$button-md-animation-curve: cubic-bezier(0.4, 0, 0.2, 1) !default;
$button-md-transition-duration: 300ms !default;
$button-md-clear-hover-background-color: rgba(158, 158, 158, 0.1) !default;
$button-md-clear-active-background-color: rgba(158, 158, 158, 0.2) !default;
$button-md-fab-box-shadow: 0 4px 6px 0 rgba(0, 0, 0, 0.14), 0 4px 5px rgba(0, 0, 0, 0.1) !default;
button,
[button] {
border-radius: $button-md-border-radius;
min-height: $button-md-min-height;
padding: $button-md-padding;
text-transform: uppercase;
font-weight: 500;
font-size: $button-md-font-size;
box-shadow: $button-md-box-shadow;
transition: box-shadow $button-md-transition-duration $button-md-animation-curve,
background-color $button-md-transition-duration $button-md-animation-curve,
color $button-md-transition-duration $button-md-animation-curve;
:hover:not(.disable-hover) {
background-color: $button-md-clear-hover-background-color;
}
&.activated {
box-shadow: $button-md-box-shadow-active;
}
&[full] {
border-radius: 0;
}
&[clear] {
opacity: 1;
box-shadow: none;
&.activated {
background-color: $button-md-clear-active-background-color;
}
}
&[outline] {
box-shadow: none;
&.activated {
opacity: 1;
}
md-ripple {
background: rgba( red($button-color), green($button-color), blue($button-color), 0.1);
}
}
&[round] {
border-radius: $button-round-border-radius;
padding: $button-round-padding;
}
&[large] {
padding: 0 $button-large-padding;
min-height: $button-large-height;
font-size: $button-large-font-size;
}
&[small] {
padding: 0 $button-small-padding;
min-height: $button-small-height;
font-size: $button-small-font-size;
}
&[fab] {
border-radius: 50%;
box-shadow: $button-md-fab-box-shadow !important;
}
&.icon-only {
padding: 0;
}
}
// Material Design Button Color Mixin
// --------------------------------------------------
@mixin button-theme-md($color-name, $color-value) {
button[#{$color-name}],
[button][#{$color-name}] {
&.activated {
opacity: 1;
}
&[outline] {
md-ripple {
background: rgba( red($color-value), green($color-value), blue($color-value), 0.2);
}
&.activated {
opacity: 1;
md-ripple {
background: rgba(0, 0, 0, 0.1);
}
}
}
}
}
// Generate Material Design Button Auxiliary Colors
// --------------------------------------------------
@each $color-name, $color-value in auxiliary-colors() {
@include button-theme-md($color-name, $color-value);
}
| ionic/components/button/modes/md.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/7b13051a52d37c16f0bfc5fa118a58cffd901c3a | [
0.0002229059173259884,
0.00017216175911016762,
0.0001630966435186565,
0.00016939737542998046,
0.000014273864508140832
] |
{
"id": 2,
"code_window": [
" this.rootView = ModalsFirstPage;\n",
" }\n",
"}"
],
"labels": [
"add",
"keep",
"keep"
],
"after_edit": [
" this.modal = modal;\n",
" }\n",
" onPageWillLeave() {\n",
" let modal = this.modal.get();\n",
" if (modal) {\n",
" modal.close();\n",
" }\n"
],
"file_path": "demos/component-docs/modals/modals.ts",
"type": "add",
"edit_start_line_idx": 54
} |
// Radio
// --------------------------------------------------
ion-radio {
display: block;
cursor: pointer;
@include user-select-none();
}
ion-radio[aria-disabled=true] {
opacity: 0.5;
color: $subdued-text-color;
pointer-events: none;
}
| ionic/components/radio/radio.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/7b13051a52d37c16f0bfc5fa118a58cffd901c3a | [
0.0001732397504383698,
0.000173074149643071,
0.00017290854884777218,
0.000173074149643071,
1.6560079529881477e-7
] |
{
"id": 2,
"code_window": [
" this.rootView = ModalsFirstPage;\n",
" }\n",
"}"
],
"labels": [
"add",
"keep",
"keep"
],
"after_edit": [
" this.modal = modal;\n",
" }\n",
" onPageWillLeave() {\n",
" let modal = this.modal.get();\n",
" if (modal) {\n",
" modal.close();\n",
" }\n"
],
"file_path": "demos/component-docs/modals/modals.ts",
"type": "add",
"edit_start_line_idx": 54
} | # Ionic
Ionic makes it easy for web developers to best-in-class build mobile apps across major platforms, like iOS
and Android.
Since the initial release of Ionic in November 2013, 700,000 apps have been created with the Ionic SDK,
and many have been featured as top apps in the Apple App Store, Google Play Store, and Amazon App Store.
Ionic is a collection of CSS and Javascript components based on Angular 2. The core philosophy behind
Ionic is that a web developer can use the standard HTML5/CSS/Javascript stack they already know and love,
but get real mobile components underneath that adapt automatically to the device and platform they
run on.
## New to Ionic?
If Ionic 2 is your first exposure to Ionic, jump right in with the [Getting Started]() guide. Otherwise,
read below for some design philosophy changes from v1.
## New Concepts in Ionic 2
Ionic 2 brings even more parity to native SDKs like iOS and Android for the web stack.
With that in mind, some core components (like routing) work differently in v2 than v1.
### Navigation
In Ionic 1, we used UI Router with URL routing heavily to define navigation in your app.
The overwhelming feedback from Ionic 1 developers is that the routing and navigation
system was too difficult to use in practice. It was challenging to correctly map
URLs to views, and the navigation system didn't give the developer enough fine-grained control.
With v2, we've taken a more native-friendly navigation approach with a simpler `push/pop` system.
For example, in v1 we'd create a `ContactDetail` page like this:
```javascript
$stateProvider
.state('contact', {
url: "/contact/:contactId",
templateUrl: "templates/contact.html",
controller: 'ContactCtrl'
});
```
Then, to navigate to this, you'd do `<a ui-sref="contact({contact: contact})">{{contact.name}}</a>`
We'd also need to make sure we wired up the current `<ion-nav-view name>` which was considerably more
challenging when using nested navigation.
In v2, this works a bit differently. Instead of navigating through URLs and routing (which is still
possible as we will see a bit later), we push and pop views onto the stack:
`<ion-item (^click)="showContact(contact)">{{contact.name}}</ion-item>``
```javascript
class ContactsPage {
showContact(contact) {
this.nav.push(ContactDetail, {
contact: contact
});
}
}
```
There are also shortcut directives we can use for links much like `ui-sref`, such as
`nav-push` and `nav-pop` which can be used like this:
```html
<button [nav-push]="myContactComponent" [push-data]="contact">See contact</button>
```
```html
<button nav-pop>Go back</button>
```
The really nice thing about this is you can infinitely navigate now (for example,
you can keep pushing new `ContactDetail` pages onto the stack), and
control things like animation and the history stack the user has to navigate through.
You can also navigate inside of practically any container. For example, a modal window that slides up
can have its own navigation, and two split views can navigate independently, something
that was not possible before.
It also makes it incredibly easy to navigate to the same page in completely different
contexts. For example, if you were building something similar to Apple's App Store
app where there are multiple tabs at the bottom and each tab navigates independently,
you could navigate to an `AppDetail` page from any tab, which is exactly how the App Store app works.
For example, here's how the Minecraft `AppDetail` page looks in different tabs:
<img src="http://ionic-io-assets.s3.amazonaws.com/images/mc1.PNG" width="300" style="width: 300px">
<img src="http://ionic-io-assets.s3.amazonaws.com/images/mc2.PNG" width="300" style="width: 300px">
Notice the page is exactly the same, but the way the user navigated to it is different.
This hits on a core change in Ionic 2: the history state of the app is now your
responsibility as a developer. It's up to you to make sure navigation provides
a good UX, but you have the freedom to navigate as you see fit.
### Routing
In Ionic, routing is used more for breadcrumbs and loading state than it is for active
navigation.
| GUIDE.md | 0 | https://github.com/ionic-team/ionic-framework/commit/7b13051a52d37c16f0bfc5fa118a58cffd901c3a | [
0.00017931428737938404,
0.00016768871864769608,
0.00016299156413879246,
0.00016713942750357091,
0.000004265106781531358
] |
{
"id": 3,
"code_window": [
" this.popup = popup;\n",
" }\n",
"\n",
" doAlert() {\n",
" this.popup.alert({\n",
" title: \"New Friend!\",\n",
" template: \"Your friend, Obi wan Kenobi, just accepted your friend request!\",\n",
" cssClass: 'my-alert'\n",
" });\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" title: \"New Friend!\",\n",
" template: \"Your friend, Obi wan Kenobi, just accepted your friend request!\",\n",
" cssClass: 'my-alert'\n"
],
"file_path": "demos/component-docs/popups/popups.ts",
"type": "replace",
"edit_start_line_idx": 17
} | import {Page, Popup} from 'ionic/ionic';
import {AndroidAttribute} from '../helpers';
import {forwardRef} from 'angular2/angular2';
@Page({
templateUrl: 'popups/popups.html',
directives: [forwardRef(() => AndroidAttribute)]
})
export class PopupsPage {
constructor(popup: Popup) {
this.popup = popup;
}
doAlert() {
this.popup.alert({
title: "New Friend!",
template: "Your friend, Obi wan Kenobi, just accepted your friend request!",
cssClass: 'my-alert'
});
}
doPrompt() {
this.popup.prompt({
title: "New Album",
template: "Enter a name for this new album you're so keen on adding",
inputPlaceholder: "Title",
okText: "Save"
});
}
doConfirm() {
this.popup.confirm({
title: "Use this lightsaber?",
subTitle: "You can't exchange lightsabers",
template: "Do you agree to use this lightsaber to do good across the intergalactic galaxy?",
cancelText: "Disagree",
okText: "Agree"
});
}
}
| demos/component-docs/popups/popups.ts | 1 | https://github.com/ionic-team/ionic-framework/commit/7b13051a52d37c16f0bfc5fa118a58cffd901c3a | [
0.9976287484169006,
0.19981630146503448,
0.00017678677977528423,
0.00034176974440924823,
0.39890629053115845
] |
{
"id": 3,
"code_window": [
" this.popup = popup;\n",
" }\n",
"\n",
" doAlert() {\n",
" this.popup.alert({\n",
" title: \"New Friend!\",\n",
" template: \"Your friend, Obi wan Kenobi, just accepted your friend request!\",\n",
" cssClass: 'my-alert'\n",
" });\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" title: \"New Friend!\",\n",
" template: \"Your friend, Obi wan Kenobi, just accepted your friend request!\",\n",
" cssClass: 'my-alert'\n"
],
"file_path": "demos/component-docs/popups/popups.ts",
"type": "replace",
"edit_start_line_idx": 17
} |
// Button Sizes
// --------------------------------------------------
$button-large-font-size: 2rem !default;
$button-large-height: 2.8em !default;
$button-large-padding: 1.0em !default;
$button-small-font-size: 1.3rem !default;
$button-small-height: 2.1em !default;
$button-small-padding: 0.9em !default;
button,
[button] {
&[large] {
padding: 0 $button-large-padding;
min-height: $button-large-height;
font-size: $button-large-font-size;
}
&[small] {
padding: 0 $button-small-padding;
min-height: $button-small-height;
font-size: $button-small-font-size;
}
}
| ionic/components/button/button-size.scss | 0 | https://github.com/ionic-team/ionic-framework/commit/7b13051a52d37c16f0bfc5fa118a58cffd901c3a | [
0.0001775515265762806,
0.00017052552720997483,
0.00016677056555636227,
0.00016725451860111207,
0.0000049720520109985955
] |
{
"id": 3,
"code_window": [
" this.popup = popup;\n",
" }\n",
"\n",
" doAlert() {\n",
" this.popup.alert({\n",
" title: \"New Friend!\",\n",
" template: \"Your friend, Obi wan Kenobi, just accepted your friend request!\",\n",
" cssClass: 'my-alert'\n",
" });\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" title: \"New Friend!\",\n",
" template: \"Your friend, Obi wan Kenobi, just accepted your friend request!\",\n",
" cssClass: 'my-alert'\n"
],
"file_path": "demos/component-docs/popups/popups.ts",
"type": "replace",
"edit_start_line_idx": 17
} | import {AppViewManager, ElementRef, Directive} from 'angular2/angular2';
import {IonicApp} from './app';
/**
* IdRef is an easy way to identify unique components in an app and access them
* no matter where in the UI heirarchy you are. For example, this makes toggling
* a global side menu feasible from any place in the application.
*
* See the [Menu section](http://localhost:4000/docs/v2/components/#menus) of
* the Component docs for an example of how Menus rely on ID's.
*
* To give any component an ID, simply set its `id` property:
* ```html
* <ion-checkbox id="myCheckbox"></ion-checkbox>
* ```
*
* To get a reference to the registered component, inject the [IonicApp](../app/IonicApp/)
* service:
* ```ts
* constructor(app: IonicApp) {
* var checkbox = app.getComponent("myCheckbox");
* if (checkbox.checked) console.log('checkbox is checked');
* }
* ```
*
* *NOTE:* It is not recommended to use ID's across Pages, as there is often no
* guarantee that the registered component has not been destroyed if its Page
* has been navigated away from.
*/
@Directive({
selector: '[id]',
inputs: ['id']
})
export class IdRef {
constructor(private app: IonicApp, private elementRef: ElementRef, private appViewManager: AppViewManager) {
// Grab the component this directive is attached to
this.component = appViewManager.getComponent(elementRef);
}
onInit() {
this.app.register(this.id, this.component);
}
onDestroy() {
this.app.unregister(this.id);
}
}
| ionic/components/app/id.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/7b13051a52d37c16f0bfc5fa118a58cffd901c3a | [
0.00017349467088934034,
0.00016863543714862317,
0.0001628865284146741,
0.0001680456625763327,
0.000004150314907747088
] |
{
"id": 3,
"code_window": [
" this.popup = popup;\n",
" }\n",
"\n",
" doAlert() {\n",
" this.popup.alert({\n",
" title: \"New Friend!\",\n",
" template: \"Your friend, Obi wan Kenobi, just accepted your friend request!\",\n",
" cssClass: 'my-alert'\n",
" });\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" title: \"New Friend!\",\n",
" template: \"Your friend, Obi wan Kenobi, just accepted your friend request!\",\n",
" cssClass: 'my-alert'\n"
],
"file_path": "demos/component-docs/popups/popups.ts",
"type": "replace",
"edit_start_line_idx": 17
} | <ion-view nav-title="Stream">
<ion-content padding>
<h2>Posts</h2>
<ion-list>
<ion-item *for="#post of posts" (click)="selectPost(post)">
{{post.title}}
</ion-item>
</ion-list>
</ion-content>
</ion-view>
| demos/barkpark/pages/tabs/home.html | 0 | https://github.com/ionic-team/ionic-framework/commit/7b13051a52d37c16f0bfc5fa118a58cffd901c3a | [
0.00017710970132611692,
0.00017585964815225452,
0.00017460959497839212,
0.00017585964815225452,
0.0000012500531738623977
] |
{
"id": 4,
"code_window": [
" cancelText: \"Disagree\",\n",
" okText: \"Agree\"\n",
" });\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\n",
" onPageWillLeave() {\n",
" let popup = this.popup.get();\n",
" // only try to close if there is an active popup\n",
" if (popup) {\n",
" popup.close();\n",
" }\n",
" }\n",
"\n"
],
"file_path": "demos/component-docs/popups/popups.ts",
"type": "add",
"edit_start_line_idx": 41
} | import {App, IonicApp, Animation, Modal, NavController, Page, Events} from 'ionic/ionic';
import {forwardRef} from 'angular2/angular2';
import * as helpers from '../helpers';
@Page({
templateUrl: 'modals/modals.html',
directives: [forwardRef(() => helpers.AndroidAttribute)]
})
class ModalsFirstPage {
constructor(
nav: NavController,
modal: Modal,
events: Events
) {
this.nav = nav;
this.modal = modal;
}
openModal() {
this.modal.open(ModalsContentPage);
}
}
@Page({
templateUrl: 'modals/modals-content.html',
directives: [forwardRef(() => helpers.AndroidAttribute)]
})
class ModalsContentPage {
constructor(
modal: Modal,
events: Events
) {
this.modal = modal;
}
closeModal() {
let modal = this.modal.get();
if (modal) {
modal.close();
}
}
}
@Page({
template: '<ion-nav [root]="rootView"></ion-nav>'
})
export class ModalsPage {
constructor() {
this.rootView = ModalsFirstPage;
}
}
| demos/component-docs/modals/modals.ts | 1 | https://github.com/ionic-team/ionic-framework/commit/7b13051a52d37c16f0bfc5fa118a58cffd901c3a | [
0.00017461975221522152,
0.00017055892385542393,
0.00016628166486043483,
0.00017095393559429795,
0.000002729804236878408
] |
{
"id": 4,
"code_window": [
" cancelText: \"Disagree\",\n",
" okText: \"Agree\"\n",
" });\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\n",
" onPageWillLeave() {\n",
" let popup = this.popup.get();\n",
" // only try to close if there is an active popup\n",
" if (popup) {\n",
" popup.close();\n",
" }\n",
" }\n",
"\n"
],
"file_path": "demos/component-docs/popups/popups.ts",
"type": "add",
"edit_start_line_idx": 41
} | <ion-navbar *navbar class="android-attr">
<ion-title>Action Sheet</ion-title>
</ion-navbar>
<ion-content padding class="has-header components-demo">
<button block (click)="openMenu()" class="android-attr">
Show Actionsheet
</button>
</ion-content>
| demos/component-docs/actionSheet/actionSheet.html | 0 | https://github.com/ionic-team/ionic-framework/commit/7b13051a52d37c16f0bfc5fa118a58cffd901c3a | [
0.00018036407709587365,
0.00018036407709587365,
0.00018036407709587365,
0.00018036407709587365,
0
] |
{
"id": 4,
"code_window": [
" cancelText: \"Disagree\",\n",
" okText: \"Agree\"\n",
" });\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\n",
" onPageWillLeave() {\n",
" let popup = this.popup.get();\n",
" // only try to close if there is an active popup\n",
" if (popup) {\n",
" popup.close();\n",
" }\n",
" }\n",
"\n"
],
"file_path": "demos/component-docs/popups/popups.ts",
"type": "add",
"edit_start_line_idx": 41
} | import {Component, Directive, ElementRef, Renderer, Host, Optional, NgControl, Query, QueryList} from 'angular2/angular2';
import {Config} from '../../config/config';
import {Ion} from '../ion';
import {ListHeader} from '../list/list';
/**
* A radio group is a group of radio components.
*
* Selecting a radio button in the group unselects all others in the group.
*
* New radios can be registered dynamically.
*
* See the [Angular 2 Docs](https://angular.io/docs/js/latest/api/forms/) for more info on forms and input.
*
* @usage
* ```html
* <ion-radio-group ng-control="clientside">
*
* <ion-header>
* Clientside
* </ion-header>
*
* <ion-radio value="ember">
* Ember
* </ion-radio>
*
* <ion-radio value="angular1">
* Angular 1
* </ion-radio>
*
* <ion-radio value="angular2" checked="true">
* Angular 2
* </ion-radio>
*
* <ion-radio value="react">
* React
* </ion-radio>
*
* </ion-radio-group>
* ```
*/
@Directive({
selector: 'ion-radio-group',
host: {
'role': 'radiogroup',
'[attr.aria-activedescendant]': 'activeId',
'[attr.aria-describedby]': 'describedById'
}
})
export class RadioGroup extends Ion {
radios: Array<RadioButton> = [];
/**
* TODO
* @param {ElementRef} elementRef TODO
* @param {Config} config TODO
* @param {NgControl=} ngControl TODO
* @param {QueryList<ListHeader>} headerQuery TODO
*/
constructor(
elementRef: ElementRef,
config: Config,
renderer: Renderer,
@Optional() ngControl: NgControl,
@Query(ListHeader) private headerQuery: QueryList<ListHeader>
) {
super(elementRef, config);
renderer.setElementClass(elementRef, 'list', true);
this.id = ++radioGroupIds;
this.radioIds = -1;
this.onChange = (_) => {};
this.onTouched = (_) => {};
if (ngControl) ngControl.valueAccessor = this;
}
onInit() {
let header = this.headerQuery.first;
if (header) {
if (!header.id) {
header.id = 'radio-header-' + this.id;
}
this.describedById = header.id;
}
}
/**
* Register the specified radio button with the radio group.
* @param {RadioButton} radio The radio button to register.
*/
registerRadio(radio) {
radio.id = radio.id || ('radio-' + this.id + '-' + (++this.radioIds));
this.radios.push(radio);
if (radio.checked) {
this.value = radio.value;
this.activeId = radio.id;
}
}
/**
* Update which radio button in the group is checked, unchecking all others.
* @param {RadioButton} checkedRadio The radio button to check.
*/
update(checkedRadio) {
this.value = checkedRadio.value;
this.activeId = checkedRadio.id;
for (let radio of this.radios) {
radio.checked = (radio === checkedRadio);
}
this.onChange(this.value);
}
/**
* @private
* Angular2 Forms API method called by the model (Control) on change to update
* the checked value.
* https://github.com/angular/angular/blob/master/modules/angular2/src/forms/directives/shared.ts#L34
*/
writeValue(value) {
this.value = value;
for (let radio of this.radios) {
radio.checked = (radio.value == value);
}
}
/**
* @private
* Angular2 Forms API method called by the view (NgControl) to register the
* onChange event handler that updates the model (Control).
* https://github.com/angular/angular/blob/master/modules/angular2/src/forms/directives/shared.ts#L27
* @param {Function} fn the onChange event handler.
*/
registerOnChange(fn) { this.onChange = fn; }
/**
* @private
* Angular2 Forms API method called by the the view (NgControl) to register
* the onTouched event handler that marks the model (Control) as touched.
* @param {Function} fn onTouched event handler.
*/
registerOnTouched(fn) { this.onTouched = fn; }
}
/**
* @name ionRadio
* @description
* A single radio component.
*
* See the [Angular 2 Docs](https://angular.io/docs/js/latest/api/forms/) for more info on forms and input.
*
* @usage
* ```html
* <ion-radio value="isChecked" checked="true">
* Radio Label
* </ion-radio>
* ```
*
*/
@Component({
selector: 'ion-radio',
inputs: [
'value',
'checked',
'disabled',
'id'
],
host: {
'role': 'radio',
'tappable': 'true',
'[attr.id]': 'id',
'[attr.tab-index]': 'tabIndex',
'[attr.aria-checked]': 'checked',
'[attr.aria-disabled]': 'disabled',
'[attr.aria-labelledby]': 'labelId',
'(click)': 'click($event)'
},
template:
'<ion-item-content id="{{labelId}}">' +
'<ng-content></ng-content>' +
'</ion-item-content>' +
'<media-radio>' +
'<radio-icon></radio-icon>' +
'</media-radio>'
})
export class RadioButton extends Ion {
/**
* Radio button constructor.
* @param {RadioGroup=} group The parent radio group, if any.
* @param {ElementRef} elementRef TODO
* @param {Config} config TODO
*/
constructor(
@Host() @Optional() group: RadioGroup,
elementRef: ElementRef,
config: Config,
renderer: Renderer
) {
super(elementRef, config);
renderer.setElementClass(elementRef, 'item', true);
this.group = group;
this.tabIndex = 0;
}
onInit() {
super.onInit();
this.group.registerRadio(this);
this.labelId = 'label-' + this.id;
}
click(ev) {
ev.preventDefault();
ev.stopPropagation();
this.check();
}
/**
* Update the checked state of this radio button.
* TODO: Call this toggle? Since unchecks as well
*/
check() {
this.checked = !this.checked;
this.group.update(this);
}
}
let radioGroupIds = -1;
| ionic/components/radio/radio.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/7b13051a52d37c16f0bfc5fa118a58cffd901c3a | [
0.00018123621703125536,
0.00016843459161464125,
0.0001642106508370489,
0.00016779860015958548,
0.0000033731857911334373
] |
{
"id": 4,
"code_window": [
" cancelText: \"Disagree\",\n",
" okText: \"Agree\"\n",
" });\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\n",
" onPageWillLeave() {\n",
" let popup = this.popup.get();\n",
" // only try to close if there is an active popup\n",
" if (popup) {\n",
" popup.close();\n",
" }\n",
" }\n",
"\n"
],
"file_path": "demos/component-docs/popups/popups.ts",
"type": "add",
"edit_start_line_idx": 41
} | import * as util from 'ionic/util';
import {Hammer} from 'ionic/gestures/hammer';
/**
* A gesture recognizer class.
*
* TODO(mlynch): Re-enable the DOM event simulation that was causing issues (or verify hammer does this already, it might);
*/
export class Gesture {
constructor(element, opts = {}) {
util.defaults(opts, {
domEvents: true
});
this.element = element;
// Map 'x' or 'y' string to hammerjs opts
this.direction = opts.direction || 'x';
opts.direction = this.direction === 'x' ?
Hammer.DIRECTION_HORIZONTAL :
Hammer.DIRECTION_VERTICAL;
this._options = opts;
this._callbacks = {};
}
options(opts = {}) {
util.extend(this._options, opts);
}
on(type, cb) {
if(type == 'pinch' || type == 'rotate') {
this.hammertime.get('pinch').set({enable: true});
}
this.hammertime.on(type, cb);
(this._callbacks[type] || (this._callbacks[type] = [])).push(cb);
//this.element.addEventListener(type, cb);
}
listen() {
this.hammertime = Hammer(this.element, this._options);
}
unlisten() {
if (this.hammertime) {
for (let type in this._callbacks) {
for (let i = 0; i < this._callbacks[type].length; i++) {
//this.element.removeEventListener(type, this._callbacks[type][i]);
this.hammertime.off(type, this._callbacks[type]);
}
}
this.hammertime.destroy();
this.hammertime = null;
this._callbacks = {}
}
}
destroy() {
this.unlisten()
}
}
| ionic/gestures/gesture.ts | 0 | https://github.com/ionic-team/ionic-framework/commit/7b13051a52d37c16f0bfc5fa118a58cffd901c3a | [
0.00019450650142971426,
0.0001715805847197771,
0.00016487480024807155,
0.00016674115613568574,
0.00000985699261946138
] |
{
"id": 0,
"code_window": [
"import Code from '@strapi/icons/Code';\n",
"import Image from '@strapi/icons/Picture';\n",
"import Link from '@strapi/icons/Link';\n",
"import Quote from '@strapi/icons/Quote';\n",
"import More from '@strapi/icons/More';\n",
"import { MainButtons, CustomIconButton, MoreButton, IconButtonGroupMargin } from './WysiwygStyles';\n",
"\n",
"const WysiwygNav = ({\n",
" editorRef,\n",
" isPreviewMode,\n",
" onActionClick,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {\n",
" MainButtons,\n",
" CustomIconButton,\n",
" MoreButton,\n",
" IconButtonGroupMargin,\n",
" CustomLinkIconButton,\n",
"} from './WysiwygStyles';\n"
],
"file_path": "packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygNav.js",
"type": "replace",
"edit_start_line_idx": 20
} | import React from 'react';
import { render, waitFor, waitForElementToBeRemoved } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ThemeProvider, lightTheme } from '@strapi/design-system';
import { Router, Switch, Route } from 'react-router-dom';
import { IntlProvider } from 'react-intl';
import { createMemoryHistory } from 'history';
import pluginId from '../../../../pluginId';
import RolesEditPage from '..';
import server from './server';
jest.mock('@strapi/helper-plugin', () => {
// Make sure the references of the mock functions stay the same, otherwise we get an endless loop
const mockToggleNotification = jest.fn();
const mockUseNotification = jest.fn(() => {
return mockToggleNotification;
});
return {
...jest.requireActual('@strapi/helper-plugin'),
useNotification: mockUseNotification,
useOverlayBlocker: jest.fn(() => ({ lockApp: jest.fn(), unlockApp: jest.fn() })),
};
});
function makeAndRenderApp() {
const history = createMemoryHistory();
const app = (
<IntlProvider locale="en" messages={{}} textComponent="span">
<ThemeProvider theme={lightTheme}>
<Router history={history}>
<Switch>
<Route path={`/settings/${pluginId}/roles/:id`} component={RolesEditPage} />
</Switch>
</Router>
</ThemeProvider>
</IntlProvider>
);
const renderResult = render(app);
history.push(`/settings/${pluginId}/roles/1`);
return renderResult;
}
describe('Admin | containers | RoleEditPage', () => {
beforeAll(() => server.listen());
beforeEach(() => jest.clearAllMocks());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
it('renders users-permissions edit role and matches snapshot', async () => {
const { container, getByTestId, getByRole } = makeAndRenderApp();
await waitForElementToBeRemoved(() => getByTestId('loader'));
await waitFor(() => expect(getByRole('heading', { name: /permissions/i })).toBeInTheDocument());
expect(container.firstChild).toMatchInlineSnapshot(`
.c1 {
background: #f6f6f9;
padding-top: 24px;
padding-right: 56px;
padding-bottom: 56px;
padding-left: 56px;
}
.c2 {
padding-bottom: 12px;
}
.c21 {
padding-right: 56px;
padding-left: 56px;
}
.c9 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-box-pack: justify;
-webkit-justify-content: space-between;
-ms-flex-pack: justify;
justify-content: space-between;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c10 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c11 {
font-weight: 600;
font-size: 2rem;
line-height: 1.25;
color: #32324d;
}
.c19 {
font-weight: 400;
font-size: 0.875rem;
line-height: 1.43;
color: #666687;
}
.c20 {
font-size: 1rem;
line-height: 1.5;
}
.c0 {
outline: none;
}
.c18 {
font-weight: 500;
font-size: 0.75rem;
line-height: 1.33;
color: #32324d;
}
.c15 {
padding-right: 8px;
}
.c12 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
cursor: pointer;
padding: 8px;
border-radius: 4px;
background: #ffffff;
border: 1px solid #dcdce4;
position: relative;
outline: none;
}
.c12 svg {
height: 12px;
width: 12px;
}
.c12 svg > g,
.c12 svg path {
fill: #ffffff;
}
.c12[aria-disabled='true'] {
pointer-events: none;
}
.c12:after {
-webkit-transition-property: all;
transition-property: all;
-webkit-transition-duration: 0.2s;
transition-duration: 0.2s;
border-radius: 8px;
content: '';
position: absolute;
top: -4px;
bottom: -4px;
left: -4px;
right: -4px;
border: 2px solid transparent;
}
.c12:focus-visible {
outline: none;
}
.c12:focus-visible:after {
border-radius: 8px;
content: '';
position: absolute;
top: -5px;
bottom: -5px;
left: -5px;
right: -5px;
border: 2px solid #4945ff;
}
.c16 {
height: 100%;
}
.c13 {
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
padding: 8px 16px;
background: #4945ff;
border: none;
border: 1px solid #4945ff;
background: #4945ff;
}
.c13 .c14 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c13 .c17 {
color: #ffffff;
}
.c13[aria-disabled='true'] {
border: 1px solid #dcdce4;
background: #eaeaef;
}
.c13[aria-disabled='true'] .c17 {
color: #666687;
}
.c13[aria-disabled='true'] svg > g,
.c13[aria-disabled='true'] svg path {
fill: #666687;
}
.c13[aria-disabled='true']:active {
border: 1px solid #dcdce4;
background: #eaeaef;
}
.c13[aria-disabled='true']:active .c17 {
color: #666687;
}
.c13[aria-disabled='true']:active svg > g,
.c13[aria-disabled='true']:active svg path {
fill: #666687;
}
.c13:hover {
border: 1px solid #7b79ff;
background: #7b79ff;
}
.c13:active {
border: 1px solid #4945ff;
background: #4945ff;
}
.c22 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
}
.c22 > * {
margin-top: 0;
margin-bottom: 0;
}
.c22 > * + * {
margin-top: 32px;
}
.c24 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
}
.c24 > * {
margin-top: 0;
margin-bottom: 0;
}
.c24 > * + * {
margin-top: 16px;
}
.c44 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
}
.c44 > * {
margin-top: 0;
margin-bottom: 0;
}
.c44 > * + * {
margin-top: 8px;
}
.c23 {
background: #ffffff;
padding-top: 24px;
padding-right: 32px;
padding-bottom: 24px;
padding-left: 32px;
border-radius: 4px;
box-shadow: 0px 1px 4px rgba(33,33,52,0.1);
}
.c30 {
font-weight: 500;
font-size: 0.75rem;
line-height: 1.33;
color: #32324d;
}
.c29 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c31 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-box-pack: justify;
-webkit-justify-content: space-between;
-ms-flex-pack: justify;
justify-content: space-between;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c33 {
border: none;
border-radius: 4px;
padding-left: 16px;
padding-right: 16px;
color: #32324d;
font-weight: 400;
font-size: 0.875rem;
display: block;
width: 100%;
}
.c33::-webkit-input-placeholder {
color: #8e8ea9;
opacity: 1;
}
.c33::-moz-placeholder {
color: #8e8ea9;
opacity: 1;
}
.c33:-ms-input-placeholder {
color: #8e8ea9;
opacity: 1;
}
.c33::placeholder {
color: #8e8ea9;
opacity: 1;
}
.c33[aria-disabled='true'] {
background: inherit;
color: inherit;
}
.c33:focus {
outline: none;
box-shadow: none;
}
.c32 {
border: 1px solid #dcdce4;
border-radius: 4px;
background: #ffffff;
height: 2.5rem;
outline: none;
box-shadow: 0;
-webkit-transition-property: border-color,box-shadow,fill;
transition-property: border-color,box-shadow,fill;
-webkit-transition-duration: 0.2s;
transition-duration: 0.2s;
}
.c32:focus-within {
border: 1px solid #4945ff;
box-shadow: #4945ff 0px 0px 0px 2px;
}
.c28 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
}
.c28 > * {
margin-top: 0;
margin-bottom: 0;
}
.c28 > * + * {
margin-top: 4px;
}
.c37 {
font-weight: 500;
font-size: 0.75rem;
line-height: 1.33;
color: #32324d;
}
.c36 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c38 {
border: 1px solid #dcdce4;
border-radius: 4px;
padding-left: 16px;
padding-right: 16px;
padding-top: 12px;
padding-bottom: 12px;
background: #ffffff;
outline: none;
box-shadow: 0;
-webkit-transition-property: border-color,box-shadow,fill;
transition-property: border-color,box-shadow,fill;
-webkit-transition-duration: 0.2s;
transition-duration: 0.2s;
}
.c38:focus-within {
border: 1px solid #4945ff;
box-shadow: #4945ff 0px 0px 0px 2px;
}
.c39 {
display: block;
width: 100%;
font-weight: 400;
font-size: 0.875rem;
border: none;
color: #32324d;
resize: none;
}
.c39::-webkit-input-placeholder {
color: #8e8ea9;
opacity: 1;
}
.c39::-moz-placeholder {
color: #8e8ea9;
opacity: 1;
}
.c39:-ms-input-placeholder {
color: #8e8ea9;
opacity: 1;
}
.c39::placeholder {
color: #8e8ea9;
opacity: 1;
}
.c39:focus-within {
outline: none;
}
.c35 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
}
.c35 > * {
margin-top: 0;
margin-bottom: 0;
}
.c35 > * + * {
margin-top: 4px;
}
.c34 textarea {
height: 5rem;
line-height: 1.25rem;
}
.c34 textarea::-webkit-input-placeholder {
font-weight: 400;
font-size: 0.875rem;
line-height: 1.43;
color: #8e8ea9;
opacity: 1;
}
.c34 textarea::-moz-placeholder {
font-weight: 400;
font-size: 0.875rem;
line-height: 1.43;
color: #8e8ea9;
opacity: 1;
}
.c34 textarea:-ms-input-placeholder {
font-weight: 400;
font-size: 0.875rem;
line-height: 1.43;
color: #8e8ea9;
opacity: 1;
}
.c34 textarea::placeholder {
font-weight: 400;
font-size: 0.875rem;
line-height: 1.43;
color: #8e8ea9;
opacity: 1;
}
.c25 {
font-weight: 500;
font-size: 1rem;
line-height: 1.25;
color: #32324d;
}
.c45 {
font-weight: 400;
font-size: 0.875rem;
line-height: 1.43;
color: #666687;
}
.c6 {
font-weight: 400;
font-size: 0.875rem;
line-height: 1.43;
color: #4945ff;
}
.c7 {
font-weight: 600;
line-height: 1.14;
}
.c8 {
font-weight: 600;
font-size: 0.6875rem;
line-height: 1.45;
text-transform: uppercase;
}
.c4 {
padding-right: 8px;
}
.c3 {
display: -webkit-inline-box;
display: -webkit-inline-flex;
display: -ms-inline-flexbox;
display: inline-flex;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
text-transform: uppercase;
-webkit-text-decoration: none;
text-decoration: none;
position: relative;
outline: none;
}
.c3 svg path {
fill: #4945ff;
}
.c3 svg {
font-size: 0.625rem;
}
.c3:after {
-webkit-transition-property: all;
transition-property: all;
-webkit-transition-duration: 0.2s;
transition-duration: 0.2s;
border-radius: 8px;
content: '';
position: absolute;
top: -4px;
bottom: -4px;
left: -4px;
right: -4px;
border: 2px solid transparent;
}
.c3:focus-visible {
outline: none;
}
.c3:focus-visible:after {
border-radius: 8px;
content: '';
position: absolute;
top: -5px;
bottom: -5px;
left: -5px;
right: -5px;
border: 2px solid #4945ff;
}
.c5 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
}
.c40 {
background: #ffffff;
border-radius: 4px;
box-shadow: 0px 1px 4px rgba(33,33,52,0.1);
}
.c43 {
padding-top: 24px;
padding-right: 32px;
padding-bottom: 24px;
padding-left: 32px;
}
.c67 {
background: #eaeaef;
padding-top: 24px;
padding-right: 32px;
padding-bottom: 24px;
padding-left: 32px;
}
.c26 {
display: grid;
grid-template-columns: repeat(12,1fr);
gap: 16px;
}
.c41 {
display: grid;
grid-template-columns: repeat(12,1fr);
gap: 0px;
}
.c27 {
grid-column: span 6;
}
.c42 {
grid-column: span 7;
}
.c66 {
grid-column: span 5;
}
.c59 {
font-weight: 500;
font-size: 1rem;
line-height: 1.25;
color: #4a4a6a;
}
.c57 {
font-weight: 400;
font-size: 0.75rem;
line-height: 1.33;
color: #4945ff;
}
.c60 {
font-weight: 400;
font-size: 0.875rem;
line-height: 1.43;
color: #666687;
}
.c46 {
border-radius: 4px;
}
.c49 {
background: #ffffff;
padding-right: 24px;
padding-left: 24px;
}
.c52 {
-webkit-flex: 1;
-ms-flex: 1;
flex: 1;
}
.c62 {
background: #dcdce4;
border-radius: 50%;
cursor: pointer;
width: 2rem;
height: 2rem;
cursor: pointer;
}
.c64 {
color: #666687;
width: 0.6875rem;
}
.c50 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-box-pack: justify;
-webkit-justify-content: space-between;
-ms-flex-pack: justify;
justify-content: space-between;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c53 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c63 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c47 {
border: 1px solid #ffffff;
overflow: hidden;
}
.c47:hover:not([aria-disabled='true']) {
border: 1px solid #4945ff;
}
.c47:hover:not([aria-disabled='true']) .c58 {
color: #271fe0;
}
.c47:hover:not([aria-disabled='true']) .c56 {
color: #4945ff;
}
.c47:hover:not([aria-disabled='true']) > .c48 {
background: #f0f0ff;
}
.c47:hover:not([aria-disabled='true']) [data-strapi-dropdown='true'] {
background: #d9d8ff;
}
.c47:hover:not([aria-disabled='true']) svg path {
fill: #4945ff;
}
.c54 {
background: transparent;
border: none;
position: relative;
outline: none;
}
.c54[aria-disabled='true'] {
pointer-events: none;
}
.c54[aria-disabled='true'] svg path {
fill: #666687;
}
.c54 svg {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
font-size: 0.625rem;
}
.c54 svg path {
fill: #4945ff;
}
.c54:after {
-webkit-transition-property: all;
transition-property: all;
-webkit-transition-duration: 0.2s;
transition-duration: 0.2s;
border-radius: 8px;
content: '';
position: absolute;
top: -4px;
bottom: -4px;
left: -4px;
right: -4px;
border: 2px solid transparent;
}
.c54:focus-visible {
outline: none;
}
.c54:focus-visible:after {
border-radius: 8px;
content: '';
position: absolute;
top: -5px;
bottom: -5px;
left: -5px;
right: -5px;
border: 2px solid #4945ff;
}
.c61 > * {
margin-left: 0;
margin-right: 0;
}
.c61 > * + * {
margin-left: 12px;
}
.c65 path {
fill: #666687;
}
.c55 {
text-align: left;
}
.c55 svg {
width: 0.875rem;
height: 0.875rem;
}
.c55 svg path {
fill: #8e8ea9;
}
.c51 {
height: 5.5rem;
}
@media (max-width:68.75rem) {
.c27 {
grid-column: span;
}
}
@media (max-width:34.375rem) {
.c27 {
grid-column: span;
}
}
@media (max-width:68.75rem) {
.c42 {
grid-column: span;
}
}
@media (max-width:34.375rem) {
.c42 {
grid-column: span;
}
}
@media (max-width:68.75rem) {
.c66 {
grid-column: span;
}
}
@media (max-width:34.375rem) {
.c66 {
grid-column: span;
}
}
<main
aria-labelledby="main-content-title"
class="c0"
id="main-content"
tabindex="-1"
>
<form
action="#"
novalidate=""
>
<div
style="height: 0px;"
>
<div
class="c1"
data-strapi-header="true"
>
<div
class="c2"
>
<a
aria-current="page"
class="c3 active"
href="/settings/users-permissions/roles"
>
<span
aria-hidden="true"
class="c4 c5"
>
<svg
fill="none"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M24 13.3a.2.2 0 01-.2.2H5.74l8.239 8.239a.2.2 0 010 .282L12.14 23.86a.2.2 0 01-.282 0L.14 12.14a.2.2 0 010-.282L11.86.14a.2.2 0 01.282 0L13.98 1.98a.2.2 0 010 .282L5.74 10.5H23.8c.11 0 .2.09.2.2v2.6z"
fill="#212134"
/>
</svg>
</span>
<span
class="c6 c7 c8"
>
Go back
</span>
</a>
</div>
<div
class="c9"
>
<div
class="c10"
>
<h1
class="c11"
id="main-content-title"
>
Authenticated
</h1>
</div>
<button
aria-disabled="false"
class="c12 c13"
type="submit"
>
<div
aria-hidden="true"
class="c14 c15 c16"
>
<svg
fill="none"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M20.727 2.97a.2.2 0 01.286 0l2.85 2.89a.2.2 0 010 .28L9.554 20.854a.2.2 0 01-.285 0l-9.13-9.243a.2.2 0 010-.281l2.85-2.892a.2.2 0 01.284 0l6.14 6.209L20.726 2.97z"
fill="#212134"
/>
</svg>
</div>
<span
class="c17 c18"
>
Save
</span>
</button>
</div>
<p
class="c19 c20"
>
Default role given to authenticated user.
</p>
</div>
</div>
<div
class="c21"
>
<div
class="c22"
>
<div
class="c23"
>
<div
class="c24"
>
<h2
class="c25"
>
Role details
</h2>
<div
class="c26"
>
<div
class="c27"
>
<div
class=""
>
<div>
<div>
<div
class="c28"
>
<div
class="c29"
>
<label
class="c30"
for="textinput-1"
>
Name
</label>
</div>
<div
class="c31 c32"
>
<input
aria-disabled="false"
aria-invalid="false"
class="c33"
id="textinput-1"
name="name"
value="Authenticated"
/>
</div>
</div>
</div>
</div>
</div>
</div>
<div
class="c27"
>
<div
class=""
>
<div
class="c34"
>
<div>
<div
class="c35"
>
<div
class="c36"
>
<label
class="c37"
for="textarea-1"
>
Description
</label>
</div>
<div
class="c38"
>
<textarea
aria-invalid="false"
class="c39"
id="textarea-1"
name="description"
>
Default role given to authenticated user.
</textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div
class="c40 c41"
>
<div
class="c42"
>
<div
class="c43"
>
<div
class="c24"
>
<div
class="c44"
>
<h2
class="c25"
>
Permissions
</h2>
<p
class="c45"
>
Only actions bound by a route are listed below.
</p>
</div>
<div
aria-disabled="false"
class="c46 c47"
data-strapi-expanded="false"
>
<div
class="c48 c49 c50 c51"
cursor=""
>
<button
aria-controls="accordion-content-accordion-1"
aria-disabled="false"
aria-expanded="false"
aria-labelledby="accordion-label-accordion-1"
class="c48 c52 c53 c54 c55"
data-strapi-accordion-toggle="true"
type="button"
>
<span
class="c56 c57"
>
<span
class="c58 c59"
id="accordion-label-accordion-1"
>
Address
</span>
<p
class="c56 c60"
id="accordion-desc-accordion-1"
>
Define all allowed actions for the api::address plugin.
</p>
</span>
</button>
<div
class="c48 c53 c61"
>
<span
aria-hidden="true"
class="c48 c62 c63"
cursor="pointer"
data-strapi-dropdown="true"
height="2rem"
width="2rem"
>
<svg
class="c64 c65"
fill="none"
height="1em"
viewBox="0 0 14 8"
width="0.6875rem"
xmlns="http://www.w3.org/2000/svg"
>
<path
clip-rule="evenodd"
d="M14 .889a.86.86 0 01-.26.625L7.615 7.736A.834.834 0 017 8a.834.834 0 01-.615-.264L.26 1.514A.861.861 0 010 .889c0-.24.087-.45.26-.625A.834.834 0 01.875 0h12.25c.237 0 .442.088.615.264a.86.86 0 01.26.625z"
fill="#32324D"
fill-rule="evenodd"
/>
</svg>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div
class="c66"
>
<div
class="c67"
style="min-height: 100%;"
>
<div
class="c44"
>
<h3
class="c25"
>
Advanced settings
</h3>
<p
class="c45"
>
Select the application's actions or the plugin's actions and click on the cog icon to display the bound route
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</main>
`);
});
it("can edit a users-permissions role's name and description", async () => {
const { getByLabelText, getByRole, getByTestId, getAllByText } = makeAndRenderApp();
// Check loading screen
const loader = getByTestId('loader');
expect(loader).toBeInTheDocument();
// After loading, check other elements
await waitForElementToBeRemoved(loader);
const saveButton = getByRole('button', { name: /save/i });
expect(saveButton).toBeInTheDocument();
const nameField = getByLabelText(/name/i);
expect(nameField).toBeInTheDocument();
const descriptionField = getByLabelText(/description/i);
expect(descriptionField).toBeInTheDocument();
// Shows error when name is missing
await userEvent.clear(nameField);
expect(nameField).toHaveValue('');
await userEvent.clear(descriptionField);
expect(descriptionField).toHaveValue('');
// Show errors after form submit
await userEvent.click(saveButton);
await waitFor(() => expect(saveButton).not.toBeDisabled());
const errorMessages = await getAllByText(/invalid value/i);
errorMessages.forEach(errorMessage => expect(errorMessage).toBeInTheDocument());
});
it('can toggle the permissions accordions and actions', async () => {
// Create app and wait for loading
const {
getByLabelText,
queryByText,
getByTestId,
getByText,
getAllByRole,
} = makeAndRenderApp();
const loader = getByTestId('loader');
await waitForElementToBeRemoved(loader);
// Open the collapse
const collapse = getByText(/define all allowed actions for the api::address plugin/i);
await userEvent.click(collapse);
expect(getByLabelText(/select all/i)).toBeInTheDocument();
// Display the selected action's bound route
const actionCogButton = getByTestId('action-cog');
await userEvent.click(actionCogButton);
expect(getByText(/bound route to/i)).toBeInTheDocument();
expect(getByText('POST')).toBeInTheDocument();
expect(getByText('/addresses')).toBeInTheDocument();
// Select all actions with the "select all" checkbox
const [selectAllCheckbox, ...actionCheckboxes] = getAllByRole('checkbox');
expect(selectAllCheckbox.checked).toBe(false);
await userEvent.click(selectAllCheckbox);
actionCheckboxes.forEach(actionCheckbox => {
expect(actionCheckbox.checked).toBe(true);
});
// Close the collapse
await userEvent.click(collapse);
expect(queryByText(/select all/i)).not.toBeInTheDocument();
});
});
| packages/plugins/users-permissions/admin/src/pages/Roles/EditPage/tests/index.test.js | 1 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.00017976778326556087,
0.0001751595555106178,
0.00016407028306275606,
0.0001758090074872598,
0.0000033159562917717267
] |
{
"id": 0,
"code_window": [
"import Code from '@strapi/icons/Code';\n",
"import Image from '@strapi/icons/Picture';\n",
"import Link from '@strapi/icons/Link';\n",
"import Quote from '@strapi/icons/Quote';\n",
"import More from '@strapi/icons/More';\n",
"import { MainButtons, CustomIconButton, MoreButton, IconButtonGroupMargin } from './WysiwygStyles';\n",
"\n",
"const WysiwygNav = ({\n",
" editorRef,\n",
" isPreviewMode,\n",
" onActionClick,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {\n",
" MainButtons,\n",
" CustomIconButton,\n",
" MoreButton,\n",
" IconButtonGroupMargin,\n",
" CustomLinkIconButton,\n",
"} from './WysiwygStyles';\n"
],
"file_path": "packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygNav.js",
"type": "replace",
"edit_start_line_idx": 20
} | import reducer, { initialState } from '../reducer';
describe('Upload | pages | HomePage | reducer', () => {
describe('GET_DATA', () => {
it('should set isLoading to true', () => {
const state = {
isLoading: false,
test: true,
};
const action = {
type: 'GET_DATA',
};
const expected = {
isLoading: true,
test: true,
};
expect(reducer(state, action)).toEqual(expected);
});
});
describe('GET_DATA_ERROR', () => {
it('should set isLoading to false', () => {
const state = {
isLoading: true,
test: true,
};
const action = {
type: 'GET_DATA_ERROR',
};
const expected = {
isLoading: false,
test: true,
};
expect(reducer(state, action)).toEqual(expected);
});
});
describe('GET_DATA_SUCCEEDED', () => {
it('should update data with received data', () => {
const state = { ...initialState };
const receivedData = [
{
id: 1,
name: 'Capture d’écran 2020-02-25 à 15.43.44.png',
ext: '.png',
mime: 'image/png',
size: 146.25,
url: '/uploads/ba0c3352c4b14132aed3fcf3110b481c.png',
createdAt: '2020-03-04T09:45:32.444Z',
updatedAt: '2020-03-04T09:45:32.444Z',
},
{
id: 2,
name: 'photo_2020-02-27 17.07.08.jpeg',
ext: '.jpeg',
mime: 'image/jpeg',
size: 140.64,
url: '/uploads/1d2ac677ea194b48bbe55ecec1b452d6.jpeg',
createdAt: '2020-03-04T14:16:35.148Z',
updatedAt: '2020-03-04T14:16:35.148Z',
},
];
const receivedDataCount = 2;
const action = {
type: 'GET_DATA_SUCCEEDED',
data: receivedData,
count: receivedDataCount,
};
const expectedState = {
...state,
data: receivedData,
dataCount: receivedDataCount,
isLoading: false,
};
expect(reducer(state, action)).toEqual(expectedState);
});
});
describe('ON_CHANGE_DATA_TO_DELETE', () => {
it('should add a media to dataToDelete if value is true', () => {
const data = [
{
id: 1,
name: 'Capture d’écran 2020-02-25 à 15.43.44.png',
ext: '.png',
mime: 'image/png',
size: 146.25,
url: '/uploads/ba0c3352c4b14132aed3fcf3110b481c.png',
createdAt: '2020-03-04T09:45:32.444Z',
updatedAt: '2020-03-04T09:45:32.444Z',
},
{
id: 2,
name: 'photo_2020-02-27 17.07.08.jpeg',
ext: '.jpeg',
mime: 'image/jpeg',
size: 140.64,
url: '/uploads/1d2ac677ea194b48bbe55ecec1b452d6.jpeg',
createdAt: '2020-03-04T14:16:35.148Z',
updatedAt: '2020-03-04T14:16:35.148Z',
},
];
const state = { ...initialState, data };
const action = {
type: 'ON_CHANGE_DATA_TO_DELETE',
id: 2,
};
const expectedState = {
...state,
dataToDelete: [
{
id: 2,
name: 'photo_2020-02-27 17.07.08.jpeg',
ext: '.jpeg',
mime: 'image/jpeg',
size: 140.64,
url: '/uploads/1d2ac677ea194b48bbe55ecec1b452d6.jpeg',
createdAt: '2020-03-04T14:16:35.148Z',
updatedAt: '2020-03-04T14:16:35.148Z',
},
],
};
expect(reducer(state, action)).toEqual(expectedState);
});
it('should remove a media to dataToDelete if value is false', () => {
const data = [
{
id: 1,
name: 'Capture d’écran 2020-02-25 à 15.43.44.png',
ext: '.png',
mime: 'image/png',
size: 146.25,
url: '/uploads/ba0c3352c4b14132aed3fcf3110b481c.png',
createdAt: '2020-03-04T09:45:32.444Z',
updatedAt: '2020-03-04T09:45:32.444Z',
},
{
id: 2,
name: 'photo_2020-02-27 17.07.08.jpeg',
ext: '.jpeg',
mime: 'image/jpeg',
size: 140.64,
url: '/uploads/1d2ac677ea194b48bbe55ecec1b452d6.jpeg',
createdAt: '2020-03-04T14:16:35.148Z',
updatedAt: '2020-03-04T14:16:35.148Z',
},
];
const dataToDelete = [
{
id: 1,
name: 'Capture d’écran 2020-02-25 à 15.43.44.png',
ext: '.png',
mime: 'image/png',
size: 146.25,
url: '/uploads/ba0c3352c4b14132aed3fcf3110b481c.png',
createdAt: '2020-03-04T09:45:32.444Z',
updatedAt: '2020-03-04T09:45:32.444Z',
},
{
id: 2,
name: 'photo_2020-02-27 17.07.08.jpeg',
ext: '.jpeg',
mime: 'image/jpeg',
size: 140.64,
url: '/uploads/1d2ac677ea194b48bbe55ecec1b452d6.jpeg',
createdAt: '2020-03-04T14:16:35.148Z',
updatedAt: '2020-03-04T14:16:35.148Z',
},
];
const state = { ...initialState, data, dataToDelete };
const action = {
type: 'ON_CHANGE_DATA_TO_DELETE',
id: 2,
};
const expectedState = {
...state,
dataToDelete: [
{
id: 1,
name: 'Capture d’écran 2020-02-25 à 15.43.44.png',
ext: '.png',
mime: 'image/png',
size: 146.25,
url: '/uploads/ba0c3352c4b14132aed3fcf3110b481c.png',
createdAt: '2020-03-04T09:45:32.444Z',
updatedAt: '2020-03-04T09:45:32.444Z',
},
],
};
expect(reducer(state, action)).toEqual(expectedState);
});
});
describe('TOGGLE_SELECT_ALL', () => {
it('should empty dataToDelete if all items are selected', () => {
const data = [
{
id: 1,
name: 'Capture d’écran 2020-02-25 à 15.43.44.png',
ext: '.png',
mime: 'image/png',
size: 146.25,
url: '/uploads/ba0c3352c4b14132aed3fcf3110b481c.png',
createdAt: '2020-03-04T09:45:32.444Z',
updatedAt: '2020-03-04T09:45:32.444Z',
},
{
id: 2,
name: 'photo_2020-02-27 17.07.08.jpeg',
ext: '.jpeg',
mime: 'image/jpeg',
size: 140.64,
url: '/uploads/1d2ac677ea194b48bbe55ecec1b452d6.jpeg',
createdAt: '2020-03-04T14:16:35.148Z',
updatedAt: '2020-03-04T14:16:35.148Z',
},
];
const dataToDelete = [
{
id: 1,
name: 'Capture d’écran 2020-02-25 à 15.43.44.png',
ext: '.png',
mime: 'image/png',
size: 146.25,
url: '/uploads/ba0c3352c4b14132aed3fcf3110b481c.png',
createdAt: '2020-03-04T09:45:32.444Z',
updatedAt: '2020-03-04T09:45:32.444Z',
},
{
id: 2,
name: 'photo_2020-02-27 17.07.08.jpeg',
ext: '.jpeg',
mime: 'image/jpeg',
size: 140.64,
url: '/uploads/1d2ac677ea194b48bbe55ecec1b452d6.jpeg',
createdAt: '2020-03-04T14:16:35.148Z',
updatedAt: '2020-03-04T14:16:35.148Z',
},
];
const state = { ...initialState, data, dataToDelete };
const action = {
type: 'TOGGLE_SELECT_ALL',
};
const expectedState = { ...state, dataToDelete: [] };
expect(reducer(state, action)).toEqual(expectedState);
});
it('should fill dataToDelete if all items are not selected', () => {
const data = [
{
id: 1,
name: 'Capture d’écran 2020-02-25 à 15.43.44.png',
ext: '.png',
mime: 'image/png',
size: 146.25,
url: '/uploads/ba0c3352c4b14132aed3fcf3110b481c.png',
createdAt: '2020-03-04T09:45:32.444Z',
updatedAt: '2020-03-04T09:45:32.444Z',
},
{
id: 2,
name: 'photo_2020-02-27 17.07.08.jpeg',
ext: '.jpeg',
mime: 'image/jpeg',
size: 140.64,
url: '/uploads/1d2ac677ea194b48bbe55ecec1b452d6.jpeg',
createdAt: '2020-03-04T14:16:35.148Z',
updatedAt: '2020-03-04T14:16:35.148Z',
},
];
const dataToDelete = [];
const state = { ...initialState, data, dataToDelete };
const action = {
type: 'TOGGLE_SELECT_ALL',
};
const expectedState = {
...state,
dataToDelete: [
{
id: 1,
name: 'Capture d’écran 2020-02-25 à 15.43.44.png',
ext: '.png',
mime: 'image/png',
size: 146.25,
url: '/uploads/ba0c3352c4b14132aed3fcf3110b481c.png',
createdAt: '2020-03-04T09:45:32.444Z',
updatedAt: '2020-03-04T09:45:32.444Z',
},
{
id: 2,
name: 'photo_2020-02-27 17.07.08.jpeg',
ext: '.jpeg',
mime: 'image/jpeg',
size: 140.64,
url: '/uploads/1d2ac677ea194b48bbe55ecec1b452d6.jpeg',
createdAt: '2020-03-04T14:16:35.148Z',
updatedAt: '2020-03-04T14:16:35.148Z',
},
],
};
expect(reducer(state, action)).toEqual(expectedState);
});
});
});
| packages/core/upload/admin/src/pages/HomePage/tests/reducer.test.js | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.00017715276044327766,
0.00017358656623400748,
0.0001675526873441413,
0.00017360471247229725,
0.000002050737521130941
] |
{
"id": 0,
"code_window": [
"import Code from '@strapi/icons/Code';\n",
"import Image from '@strapi/icons/Picture';\n",
"import Link from '@strapi/icons/Link';\n",
"import Quote from '@strapi/icons/Quote';\n",
"import More from '@strapi/icons/More';\n",
"import { MainButtons, CustomIconButton, MoreButton, IconButtonGroupMargin } from './WysiwygStyles';\n",
"\n",
"const WysiwygNav = ({\n",
" editorRef,\n",
" isPreviewMode,\n",
" onActionClick,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {\n",
" MainButtons,\n",
" CustomIconButton,\n",
" MoreButton,\n",
" IconButtonGroupMargin,\n",
" CustomLinkIconButton,\n",
"} from './WysiwygStyles';\n"
],
"file_path": "packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygNav.js",
"type": "replace",
"edit_start_line_idx": 20
} | 'use strict';
const _ = require('lodash');
const removeEmptyDefaults = data => {
if (_.has(data, 'attributes')) {
Object.keys(data.attributes).forEach(attribute => {
if (data.attributes[attribute].default === '') {
data.attributes[attribute].default = undefined;
}
});
}
};
const removeDeletedUIDTargetFields = data => {
if (_.has(data, 'attributes')) {
Object.values(data.attributes).forEach(attribute => {
if (
attribute.type === 'uid' &&
!_.isUndefined(attribute.targetField) &&
!_.has(data.attributes, attribute.targetField)
) {
attribute.targetField = undefined;
}
});
}
};
module.exports = {
removeDeletedUIDTargetFields,
removeEmptyDefaults,
};
| packages/core/content-type-builder/server/controllers/validation/data-transform.js | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.00017365305393468589,
0.00017023652617353946,
0.00016605523705948144,
0.00017061890684999526,
0.000002734731879172614
] |
{
"id": 0,
"code_window": [
"import Code from '@strapi/icons/Code';\n",
"import Image from '@strapi/icons/Picture';\n",
"import Link from '@strapi/icons/Link';\n",
"import Quote from '@strapi/icons/Quote';\n",
"import More from '@strapi/icons/More';\n",
"import { MainButtons, CustomIconButton, MoreButton, IconButtonGroupMargin } from './WysiwygStyles';\n",
"\n",
"const WysiwygNav = ({\n",
" editorRef,\n",
" isPreviewMode,\n",
" onActionClick,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {\n",
" MainButtons,\n",
" CustomIconButton,\n",
" MoreButton,\n",
" IconButtonGroupMargin,\n",
" CustomLinkIconButton,\n",
"} from './WysiwygStyles';\n"
],
"file_path": "packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygNav.js",
"type": "replace",
"edit_start_line_idx": 20
} | 'use strict';
module.exports = ({ strapi }) => ({
buildDynamicZoneResolver({ contentTypeUID, attributeName }) {
return async parent => {
return strapi.entityService.load(contentTypeUID, parent, attributeName);
};
},
});
| packages/plugins/graphql/server/services/builders/resolvers/dynamic-zone.js | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.0001712683297228068,
0.0001712683297228068,
0.0001712683297228068,
0.0001712683297228068,
0
] |
{
"id": 1,
"code_window": [
" />\n",
" </MainButtons>\n",
"\n",
" <MoreButton disabled ref={buttonMoreRef} id=\"more\" label=\"more\" icon={<More />} />\n",
" </Flex>\n",
"\n",
" <Button onClick={onTogglePreviewMode} variant=\"tertiary\" size=\"L\" id=\"preview\">\n",
" {formatMessage({\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <MoreButton disabled ref={buttonMoreRef} id=\"more\" label=\"More\" icon={<More />} />\n"
],
"file_path": "packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygNav.js",
"type": "replace",
"edit_start_line_idx": 77
} | import React from 'react';
import { render, waitFor, waitForElementToBeRemoved } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ThemeProvider, lightTheme } from '@strapi/design-system';
import { Router, Switch, Route } from 'react-router-dom';
import { IntlProvider } from 'react-intl';
import { createMemoryHistory } from 'history';
import pluginId from '../../../../pluginId';
import RolesEditPage from '..';
import server from './server';
jest.mock('@strapi/helper-plugin', () => {
// Make sure the references of the mock functions stay the same, otherwise we get an endless loop
const mockToggleNotification = jest.fn();
const mockUseNotification = jest.fn(() => {
return mockToggleNotification;
});
return {
...jest.requireActual('@strapi/helper-plugin'),
useNotification: mockUseNotification,
useOverlayBlocker: jest.fn(() => ({ lockApp: jest.fn(), unlockApp: jest.fn() })),
};
});
function makeAndRenderApp() {
const history = createMemoryHistory();
const app = (
<IntlProvider locale="en" messages={{}} textComponent="span">
<ThemeProvider theme={lightTheme}>
<Router history={history}>
<Switch>
<Route path={`/settings/${pluginId}/roles/:id`} component={RolesEditPage} />
</Switch>
</Router>
</ThemeProvider>
</IntlProvider>
);
const renderResult = render(app);
history.push(`/settings/${pluginId}/roles/1`);
return renderResult;
}
describe('Admin | containers | RoleEditPage', () => {
beforeAll(() => server.listen());
beforeEach(() => jest.clearAllMocks());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
it('renders users-permissions edit role and matches snapshot', async () => {
const { container, getByTestId, getByRole } = makeAndRenderApp();
await waitForElementToBeRemoved(() => getByTestId('loader'));
await waitFor(() => expect(getByRole('heading', { name: /permissions/i })).toBeInTheDocument());
expect(container.firstChild).toMatchInlineSnapshot(`
.c1 {
background: #f6f6f9;
padding-top: 24px;
padding-right: 56px;
padding-bottom: 56px;
padding-left: 56px;
}
.c2 {
padding-bottom: 12px;
}
.c21 {
padding-right: 56px;
padding-left: 56px;
}
.c9 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-box-pack: justify;
-webkit-justify-content: space-between;
-ms-flex-pack: justify;
justify-content: space-between;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c10 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c11 {
font-weight: 600;
font-size: 2rem;
line-height: 1.25;
color: #32324d;
}
.c19 {
font-weight: 400;
font-size: 0.875rem;
line-height: 1.43;
color: #666687;
}
.c20 {
font-size: 1rem;
line-height: 1.5;
}
.c0 {
outline: none;
}
.c18 {
font-weight: 500;
font-size: 0.75rem;
line-height: 1.33;
color: #32324d;
}
.c15 {
padding-right: 8px;
}
.c12 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
cursor: pointer;
padding: 8px;
border-radius: 4px;
background: #ffffff;
border: 1px solid #dcdce4;
position: relative;
outline: none;
}
.c12 svg {
height: 12px;
width: 12px;
}
.c12 svg > g,
.c12 svg path {
fill: #ffffff;
}
.c12[aria-disabled='true'] {
pointer-events: none;
}
.c12:after {
-webkit-transition-property: all;
transition-property: all;
-webkit-transition-duration: 0.2s;
transition-duration: 0.2s;
border-radius: 8px;
content: '';
position: absolute;
top: -4px;
bottom: -4px;
left: -4px;
right: -4px;
border: 2px solid transparent;
}
.c12:focus-visible {
outline: none;
}
.c12:focus-visible:after {
border-radius: 8px;
content: '';
position: absolute;
top: -5px;
bottom: -5px;
left: -5px;
right: -5px;
border: 2px solid #4945ff;
}
.c16 {
height: 100%;
}
.c13 {
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
padding: 8px 16px;
background: #4945ff;
border: none;
border: 1px solid #4945ff;
background: #4945ff;
}
.c13 .c14 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c13 .c17 {
color: #ffffff;
}
.c13[aria-disabled='true'] {
border: 1px solid #dcdce4;
background: #eaeaef;
}
.c13[aria-disabled='true'] .c17 {
color: #666687;
}
.c13[aria-disabled='true'] svg > g,
.c13[aria-disabled='true'] svg path {
fill: #666687;
}
.c13[aria-disabled='true']:active {
border: 1px solid #dcdce4;
background: #eaeaef;
}
.c13[aria-disabled='true']:active .c17 {
color: #666687;
}
.c13[aria-disabled='true']:active svg > g,
.c13[aria-disabled='true']:active svg path {
fill: #666687;
}
.c13:hover {
border: 1px solid #7b79ff;
background: #7b79ff;
}
.c13:active {
border: 1px solid #4945ff;
background: #4945ff;
}
.c22 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
}
.c22 > * {
margin-top: 0;
margin-bottom: 0;
}
.c22 > * + * {
margin-top: 32px;
}
.c24 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
}
.c24 > * {
margin-top: 0;
margin-bottom: 0;
}
.c24 > * + * {
margin-top: 16px;
}
.c44 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
}
.c44 > * {
margin-top: 0;
margin-bottom: 0;
}
.c44 > * + * {
margin-top: 8px;
}
.c23 {
background: #ffffff;
padding-top: 24px;
padding-right: 32px;
padding-bottom: 24px;
padding-left: 32px;
border-radius: 4px;
box-shadow: 0px 1px 4px rgba(33,33,52,0.1);
}
.c30 {
font-weight: 500;
font-size: 0.75rem;
line-height: 1.33;
color: #32324d;
}
.c29 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c31 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-box-pack: justify;
-webkit-justify-content: space-between;
-ms-flex-pack: justify;
justify-content: space-between;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c33 {
border: none;
border-radius: 4px;
padding-left: 16px;
padding-right: 16px;
color: #32324d;
font-weight: 400;
font-size: 0.875rem;
display: block;
width: 100%;
}
.c33::-webkit-input-placeholder {
color: #8e8ea9;
opacity: 1;
}
.c33::-moz-placeholder {
color: #8e8ea9;
opacity: 1;
}
.c33:-ms-input-placeholder {
color: #8e8ea9;
opacity: 1;
}
.c33::placeholder {
color: #8e8ea9;
opacity: 1;
}
.c33[aria-disabled='true'] {
background: inherit;
color: inherit;
}
.c33:focus {
outline: none;
box-shadow: none;
}
.c32 {
border: 1px solid #dcdce4;
border-radius: 4px;
background: #ffffff;
height: 2.5rem;
outline: none;
box-shadow: 0;
-webkit-transition-property: border-color,box-shadow,fill;
transition-property: border-color,box-shadow,fill;
-webkit-transition-duration: 0.2s;
transition-duration: 0.2s;
}
.c32:focus-within {
border: 1px solid #4945ff;
box-shadow: #4945ff 0px 0px 0px 2px;
}
.c28 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
}
.c28 > * {
margin-top: 0;
margin-bottom: 0;
}
.c28 > * + * {
margin-top: 4px;
}
.c37 {
font-weight: 500;
font-size: 0.75rem;
line-height: 1.33;
color: #32324d;
}
.c36 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c38 {
border: 1px solid #dcdce4;
border-radius: 4px;
padding-left: 16px;
padding-right: 16px;
padding-top: 12px;
padding-bottom: 12px;
background: #ffffff;
outline: none;
box-shadow: 0;
-webkit-transition-property: border-color,box-shadow,fill;
transition-property: border-color,box-shadow,fill;
-webkit-transition-duration: 0.2s;
transition-duration: 0.2s;
}
.c38:focus-within {
border: 1px solid #4945ff;
box-shadow: #4945ff 0px 0px 0px 2px;
}
.c39 {
display: block;
width: 100%;
font-weight: 400;
font-size: 0.875rem;
border: none;
color: #32324d;
resize: none;
}
.c39::-webkit-input-placeholder {
color: #8e8ea9;
opacity: 1;
}
.c39::-moz-placeholder {
color: #8e8ea9;
opacity: 1;
}
.c39:-ms-input-placeholder {
color: #8e8ea9;
opacity: 1;
}
.c39::placeholder {
color: #8e8ea9;
opacity: 1;
}
.c39:focus-within {
outline: none;
}
.c35 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
}
.c35 > * {
margin-top: 0;
margin-bottom: 0;
}
.c35 > * + * {
margin-top: 4px;
}
.c34 textarea {
height: 5rem;
line-height: 1.25rem;
}
.c34 textarea::-webkit-input-placeholder {
font-weight: 400;
font-size: 0.875rem;
line-height: 1.43;
color: #8e8ea9;
opacity: 1;
}
.c34 textarea::-moz-placeholder {
font-weight: 400;
font-size: 0.875rem;
line-height: 1.43;
color: #8e8ea9;
opacity: 1;
}
.c34 textarea:-ms-input-placeholder {
font-weight: 400;
font-size: 0.875rem;
line-height: 1.43;
color: #8e8ea9;
opacity: 1;
}
.c34 textarea::placeholder {
font-weight: 400;
font-size: 0.875rem;
line-height: 1.43;
color: #8e8ea9;
opacity: 1;
}
.c25 {
font-weight: 500;
font-size: 1rem;
line-height: 1.25;
color: #32324d;
}
.c45 {
font-weight: 400;
font-size: 0.875rem;
line-height: 1.43;
color: #666687;
}
.c6 {
font-weight: 400;
font-size: 0.875rem;
line-height: 1.43;
color: #4945ff;
}
.c7 {
font-weight: 600;
line-height: 1.14;
}
.c8 {
font-weight: 600;
font-size: 0.6875rem;
line-height: 1.45;
text-transform: uppercase;
}
.c4 {
padding-right: 8px;
}
.c3 {
display: -webkit-inline-box;
display: -webkit-inline-flex;
display: -ms-inline-flexbox;
display: inline-flex;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
text-transform: uppercase;
-webkit-text-decoration: none;
text-decoration: none;
position: relative;
outline: none;
}
.c3 svg path {
fill: #4945ff;
}
.c3 svg {
font-size: 0.625rem;
}
.c3:after {
-webkit-transition-property: all;
transition-property: all;
-webkit-transition-duration: 0.2s;
transition-duration: 0.2s;
border-radius: 8px;
content: '';
position: absolute;
top: -4px;
bottom: -4px;
left: -4px;
right: -4px;
border: 2px solid transparent;
}
.c3:focus-visible {
outline: none;
}
.c3:focus-visible:after {
border-radius: 8px;
content: '';
position: absolute;
top: -5px;
bottom: -5px;
left: -5px;
right: -5px;
border: 2px solid #4945ff;
}
.c5 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
}
.c40 {
background: #ffffff;
border-radius: 4px;
box-shadow: 0px 1px 4px rgba(33,33,52,0.1);
}
.c43 {
padding-top: 24px;
padding-right: 32px;
padding-bottom: 24px;
padding-left: 32px;
}
.c67 {
background: #eaeaef;
padding-top: 24px;
padding-right: 32px;
padding-bottom: 24px;
padding-left: 32px;
}
.c26 {
display: grid;
grid-template-columns: repeat(12,1fr);
gap: 16px;
}
.c41 {
display: grid;
grid-template-columns: repeat(12,1fr);
gap: 0px;
}
.c27 {
grid-column: span 6;
}
.c42 {
grid-column: span 7;
}
.c66 {
grid-column: span 5;
}
.c59 {
font-weight: 500;
font-size: 1rem;
line-height: 1.25;
color: #4a4a6a;
}
.c57 {
font-weight: 400;
font-size: 0.75rem;
line-height: 1.33;
color: #4945ff;
}
.c60 {
font-weight: 400;
font-size: 0.875rem;
line-height: 1.43;
color: #666687;
}
.c46 {
border-radius: 4px;
}
.c49 {
background: #ffffff;
padding-right: 24px;
padding-left: 24px;
}
.c52 {
-webkit-flex: 1;
-ms-flex: 1;
flex: 1;
}
.c62 {
background: #dcdce4;
border-radius: 50%;
cursor: pointer;
width: 2rem;
height: 2rem;
cursor: pointer;
}
.c64 {
color: #666687;
width: 0.6875rem;
}
.c50 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-box-pack: justify;
-webkit-justify-content: space-between;
-ms-flex-pack: justify;
justify-content: space-between;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c53 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c63 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c47 {
border: 1px solid #ffffff;
overflow: hidden;
}
.c47:hover:not([aria-disabled='true']) {
border: 1px solid #4945ff;
}
.c47:hover:not([aria-disabled='true']) .c58 {
color: #271fe0;
}
.c47:hover:not([aria-disabled='true']) .c56 {
color: #4945ff;
}
.c47:hover:not([aria-disabled='true']) > .c48 {
background: #f0f0ff;
}
.c47:hover:not([aria-disabled='true']) [data-strapi-dropdown='true'] {
background: #d9d8ff;
}
.c47:hover:not([aria-disabled='true']) svg path {
fill: #4945ff;
}
.c54 {
background: transparent;
border: none;
position: relative;
outline: none;
}
.c54[aria-disabled='true'] {
pointer-events: none;
}
.c54[aria-disabled='true'] svg path {
fill: #666687;
}
.c54 svg {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
font-size: 0.625rem;
}
.c54 svg path {
fill: #4945ff;
}
.c54:after {
-webkit-transition-property: all;
transition-property: all;
-webkit-transition-duration: 0.2s;
transition-duration: 0.2s;
border-radius: 8px;
content: '';
position: absolute;
top: -4px;
bottom: -4px;
left: -4px;
right: -4px;
border: 2px solid transparent;
}
.c54:focus-visible {
outline: none;
}
.c54:focus-visible:after {
border-radius: 8px;
content: '';
position: absolute;
top: -5px;
bottom: -5px;
left: -5px;
right: -5px;
border: 2px solid #4945ff;
}
.c61 > * {
margin-left: 0;
margin-right: 0;
}
.c61 > * + * {
margin-left: 12px;
}
.c65 path {
fill: #666687;
}
.c55 {
text-align: left;
}
.c55 svg {
width: 0.875rem;
height: 0.875rem;
}
.c55 svg path {
fill: #8e8ea9;
}
.c51 {
height: 5.5rem;
}
@media (max-width:68.75rem) {
.c27 {
grid-column: span;
}
}
@media (max-width:34.375rem) {
.c27 {
grid-column: span;
}
}
@media (max-width:68.75rem) {
.c42 {
grid-column: span;
}
}
@media (max-width:34.375rem) {
.c42 {
grid-column: span;
}
}
@media (max-width:68.75rem) {
.c66 {
grid-column: span;
}
}
@media (max-width:34.375rem) {
.c66 {
grid-column: span;
}
}
<main
aria-labelledby="main-content-title"
class="c0"
id="main-content"
tabindex="-1"
>
<form
action="#"
novalidate=""
>
<div
style="height: 0px;"
>
<div
class="c1"
data-strapi-header="true"
>
<div
class="c2"
>
<a
aria-current="page"
class="c3 active"
href="/settings/users-permissions/roles"
>
<span
aria-hidden="true"
class="c4 c5"
>
<svg
fill="none"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M24 13.3a.2.2 0 01-.2.2H5.74l8.239 8.239a.2.2 0 010 .282L12.14 23.86a.2.2 0 01-.282 0L.14 12.14a.2.2 0 010-.282L11.86.14a.2.2 0 01.282 0L13.98 1.98a.2.2 0 010 .282L5.74 10.5H23.8c.11 0 .2.09.2.2v2.6z"
fill="#212134"
/>
</svg>
</span>
<span
class="c6 c7 c8"
>
Go back
</span>
</a>
</div>
<div
class="c9"
>
<div
class="c10"
>
<h1
class="c11"
id="main-content-title"
>
Authenticated
</h1>
</div>
<button
aria-disabled="false"
class="c12 c13"
type="submit"
>
<div
aria-hidden="true"
class="c14 c15 c16"
>
<svg
fill="none"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M20.727 2.97a.2.2 0 01.286 0l2.85 2.89a.2.2 0 010 .28L9.554 20.854a.2.2 0 01-.285 0l-9.13-9.243a.2.2 0 010-.281l2.85-2.892a.2.2 0 01.284 0l6.14 6.209L20.726 2.97z"
fill="#212134"
/>
</svg>
</div>
<span
class="c17 c18"
>
Save
</span>
</button>
</div>
<p
class="c19 c20"
>
Default role given to authenticated user.
</p>
</div>
</div>
<div
class="c21"
>
<div
class="c22"
>
<div
class="c23"
>
<div
class="c24"
>
<h2
class="c25"
>
Role details
</h2>
<div
class="c26"
>
<div
class="c27"
>
<div
class=""
>
<div>
<div>
<div
class="c28"
>
<div
class="c29"
>
<label
class="c30"
for="textinput-1"
>
Name
</label>
</div>
<div
class="c31 c32"
>
<input
aria-disabled="false"
aria-invalid="false"
class="c33"
id="textinput-1"
name="name"
value="Authenticated"
/>
</div>
</div>
</div>
</div>
</div>
</div>
<div
class="c27"
>
<div
class=""
>
<div
class="c34"
>
<div>
<div
class="c35"
>
<div
class="c36"
>
<label
class="c37"
for="textarea-1"
>
Description
</label>
</div>
<div
class="c38"
>
<textarea
aria-invalid="false"
class="c39"
id="textarea-1"
name="description"
>
Default role given to authenticated user.
</textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div
class="c40 c41"
>
<div
class="c42"
>
<div
class="c43"
>
<div
class="c24"
>
<div
class="c44"
>
<h2
class="c25"
>
Permissions
</h2>
<p
class="c45"
>
Only actions bound by a route are listed below.
</p>
</div>
<div
aria-disabled="false"
class="c46 c47"
data-strapi-expanded="false"
>
<div
class="c48 c49 c50 c51"
cursor=""
>
<button
aria-controls="accordion-content-accordion-1"
aria-disabled="false"
aria-expanded="false"
aria-labelledby="accordion-label-accordion-1"
class="c48 c52 c53 c54 c55"
data-strapi-accordion-toggle="true"
type="button"
>
<span
class="c56 c57"
>
<span
class="c58 c59"
id="accordion-label-accordion-1"
>
Address
</span>
<p
class="c56 c60"
id="accordion-desc-accordion-1"
>
Define all allowed actions for the api::address plugin.
</p>
</span>
</button>
<div
class="c48 c53 c61"
>
<span
aria-hidden="true"
class="c48 c62 c63"
cursor="pointer"
data-strapi-dropdown="true"
height="2rem"
width="2rem"
>
<svg
class="c64 c65"
fill="none"
height="1em"
viewBox="0 0 14 8"
width="0.6875rem"
xmlns="http://www.w3.org/2000/svg"
>
<path
clip-rule="evenodd"
d="M14 .889a.86.86 0 01-.26.625L7.615 7.736A.834.834 0 017 8a.834.834 0 01-.615-.264L.26 1.514A.861.861 0 010 .889c0-.24.087-.45.26-.625A.834.834 0 01.875 0h12.25c.237 0 .442.088.615.264a.86.86 0 01.26.625z"
fill="#32324D"
fill-rule="evenodd"
/>
</svg>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div
class="c66"
>
<div
class="c67"
style="min-height: 100%;"
>
<div
class="c44"
>
<h3
class="c25"
>
Advanced settings
</h3>
<p
class="c45"
>
Select the application's actions or the plugin's actions and click on the cog icon to display the bound route
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</main>
`);
});
it("can edit a users-permissions role's name and description", async () => {
const { getByLabelText, getByRole, getByTestId, getAllByText } = makeAndRenderApp();
// Check loading screen
const loader = getByTestId('loader');
expect(loader).toBeInTheDocument();
// After loading, check other elements
await waitForElementToBeRemoved(loader);
const saveButton = getByRole('button', { name: /save/i });
expect(saveButton).toBeInTheDocument();
const nameField = getByLabelText(/name/i);
expect(nameField).toBeInTheDocument();
const descriptionField = getByLabelText(/description/i);
expect(descriptionField).toBeInTheDocument();
// Shows error when name is missing
await userEvent.clear(nameField);
expect(nameField).toHaveValue('');
await userEvent.clear(descriptionField);
expect(descriptionField).toHaveValue('');
// Show errors after form submit
await userEvent.click(saveButton);
await waitFor(() => expect(saveButton).not.toBeDisabled());
const errorMessages = await getAllByText(/invalid value/i);
errorMessages.forEach(errorMessage => expect(errorMessage).toBeInTheDocument());
});
it('can toggle the permissions accordions and actions', async () => {
// Create app and wait for loading
const {
getByLabelText,
queryByText,
getByTestId,
getByText,
getAllByRole,
} = makeAndRenderApp();
const loader = getByTestId('loader');
await waitForElementToBeRemoved(loader);
// Open the collapse
const collapse = getByText(/define all allowed actions for the api::address plugin/i);
await userEvent.click(collapse);
expect(getByLabelText(/select all/i)).toBeInTheDocument();
// Display the selected action's bound route
const actionCogButton = getByTestId('action-cog');
await userEvent.click(actionCogButton);
expect(getByText(/bound route to/i)).toBeInTheDocument();
expect(getByText('POST')).toBeInTheDocument();
expect(getByText('/addresses')).toBeInTheDocument();
// Select all actions with the "select all" checkbox
const [selectAllCheckbox, ...actionCheckboxes] = getAllByRole('checkbox');
expect(selectAllCheckbox.checked).toBe(false);
await userEvent.click(selectAllCheckbox);
actionCheckboxes.forEach(actionCheckbox => {
expect(actionCheckbox.checked).toBe(true);
});
// Close the collapse
await userEvent.click(collapse);
expect(queryByText(/select all/i)).not.toBeInTheDocument();
});
});
| packages/plugins/users-permissions/admin/src/pages/Roles/EditPage/tests/index.test.js | 1 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.0003649364225566387,
0.0001763361506164074,
0.00015993556007742882,
0.00017411298176739365,
0.000023002045054454356
] |
{
"id": 1,
"code_window": [
" />\n",
" </MainButtons>\n",
"\n",
" <MoreButton disabled ref={buttonMoreRef} id=\"more\" label=\"more\" icon={<More />} />\n",
" </Flex>\n",
"\n",
" <Button onClick={onTogglePreviewMode} variant=\"tertiary\" size=\"L\" id=\"preview\">\n",
" {formatMessage({\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <MoreButton disabled ref={buttonMoreRef} id=\"more\" label=\"More\" icon={<More />} />\n"
],
"file_path": "packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygNav.js",
"type": "replace",
"edit_start_line_idx": 77
} | # @strapi/generators
This package contains strapi code generators available through the CLI or programmatically.
## API Reference
### `runCLI()`
Start the generator CLI.
### `generate(generatorName, options, plopOptions)`
Execute a generator without interactive mode.
- `generatorName` - one of `api`, `controller`, `service`, `model`, `plugin`, `policy`.
- `options` - options are specific to each generator
- `plopOtions`
- `dir`: base directory that plop will use as base directory for its actions
| packages/generators/generators/README.md | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.00016665323346387595,
0.00016409257659688592,
0.00016153193428181112,
0.00016409257659688592,
0.0000025606495910324156
] |
{
"id": 1,
"code_window": [
" />\n",
" </MainButtons>\n",
"\n",
" <MoreButton disabled ref={buttonMoreRef} id=\"more\" label=\"more\" icon={<More />} />\n",
" </Flex>\n",
"\n",
" <Button onClick={onTogglePreviewMode} variant=\"tertiary\" size=\"L\" id=\"preview\">\n",
" {formatMessage({\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <MoreButton disabled ref={buttonMoreRef} id=\"more\" label=\"More\" icon={<More />} />\n"
],
"file_path": "packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygNav.js",
"type": "replace",
"edit_start_line_idx": 77
} | const generateHeadersFromActions = (actions, propertyName) => {
return actions.map(action => {
const isActionRelatedToCurrentProperty =
Array.isArray(action.applyToProperties) &&
action.applyToProperties.indexOf(propertyName) !== -1 &&
action.isDisplayed;
return { label: action.label, actionId: action.actionId, isActionRelatedToCurrentProperty };
});
};
export default generateHeadersFromActions;
| packages/core/admin/admin/src/pages/SettingsPage/pages/Roles/EditPage/components/ContentTypeCollapse/CollapsePropertyMatrix/utils/generateHeadersFromActions.js | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.00020141087588854134,
0.00018374304636381567,
0.00016607520228717476,
0.00018374304636381567,
0.00001766783680068329
] |
{
"id": 1,
"code_window": [
" />\n",
" </MainButtons>\n",
"\n",
" <MoreButton disabled ref={buttonMoreRef} id=\"more\" label=\"more\" icon={<More />} />\n",
" </Flex>\n",
"\n",
" <Button onClick={onTogglePreviewMode} variant=\"tertiary\" size=\"L\" id=\"preview\">\n",
" {formatMessage({\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <MoreButton disabled ref={buttonMoreRef} id=\"more\" label=\"More\" icon={<More />} />\n"
],
"file_path": "packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygNav.js",
"type": "replace",
"edit_start_line_idx": 77
} | import produce from 'immer';
import reducer from '../reducer';
describe('CONTENT MANAGER | hooks | useFetchContentTypeLayout | reducer', () => {
let state;
beforeEach(() => {
state = {
error: null,
isLoading: true,
layout: {},
layouts: {},
};
});
it('should handle the default case correctly', () => {
expect(reducer(state, { type: 'test' })).toEqual(state);
});
it('should handle the GET_DATA action correctly', () => {
state.isLoading = false;
state.error = true;
const action = { type: 'GET_DATA' };
const expected = produce(state, draft => {
draft.isLoading = true;
draft.error = null;
});
expect(reducer(state, action)).toEqual(expected);
});
it('should handle the GET_DATA_SUCCEEDED action correctly', () => {
const action = {
type: 'GET_DATA_SUCCEEDED',
data: { contentType: { uid: 'test' } },
};
const expected = produce(state, draft => {
draft.isLoading = false;
draft.layout = { contentType: { uid: 'test' } };
draft.layouts = { test: { contentType: { uid: 'test' } } };
});
expect(reducer(state, action)).toEqual(expected);
});
it('should handle the GET_DATA_ERROR action correctly', () => {
const action = {
type: 'GET_DATA_ERROR',
error: true,
};
const expected = produce(state, draft => {
draft.isLoading = false;
draft.error = true;
});
expect(reducer(state, action)).toEqual(expected);
});
});
| packages/core/admin/admin/src/content-manager/hooks/useFetchContentTypeLayout/tests/reducer.test.js | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.00017788144759833813,
0.0001739942963467911,
0.00017133416258729994,
0.0001734341203700751,
0.0000024157411644409876
] |
{
"id": 2,
"code_window": [
"\n",
" <MoreButton\n",
" ref={buttonMoreRef}\n",
" onClick={onTogglePopover}\n",
" id=\"more\"\n",
" label=\"more\"\n",
" icon={<More />}\n",
" />\n",
" {visiblePopover && (\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" label=\"More\"\n"
],
"file_path": "packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygNav.js",
"type": "replace",
"edit_start_line_idx": 137
} | import styled from 'styled-components';
import { Box } from '@strapi/design-system/Box';
import { IconButtonGroup, IconButton } from '@strapi/design-system/IconButton';
import { BaseButton } from '@strapi/design-system/BaseButton';
export const WysiwygWrapper = styled(Box)`
border: 1px solid
${({ theme, error }) => (error ? theme.colors.danger600 : theme.colors.neutral200)};
margin-top: ${({ theme }) => `${theme.spaces[2]}`};
`;
// NAV BUTTONS
export const CustomIconButton = styled(IconButton)`
padding: ${({ theme }) => theme.spaces[2]};
/* Trick to prevent the outline from overflowing because of the general outline-offset */
outline-offset: -2px !important;
svg {
width: ${18 / 16}rem;
height: ${18 / 16}rem;
}
`;
export const MainButtons = styled(IconButtonGroup)`
margin-left: ${({ theme }) => theme.spaces[4]};
`;
export const MoreButton = styled(IconButton)`
margin: ${({ theme }) => `0 ${theme.spaces[2]}`};
padding: ${({ theme }) => theme.spaces[2]};
svg {
width: ${18 / 16}rem;
height: ${18 / 16}rem;
}
`;
// NAV
export const IconButtonGroupMargin = styled(IconButtonGroup)`
margin-right: ${({ theme }) => `${theme.spaces[2]}`};
`;
// EDITOR && PREVIEW
export const EditorAndPreviewWrapper = styled.div`
position: relative;
`;
// FOOTER
export const ExpandButton = styled(BaseButton)`
background-color: transparent;
border: none;
align-items: center;
svg {
margin-left: ${({ theme }) => `${theme.spaces[2]}`};
path {
fill: ${({ theme }) => theme.colors.neutral700};
width: ${12 / 16}rem;
height: ${12 / 16}rem;
}
}
`;
// PREVIEW
const setOpacity = (hex, alpha) =>
`${hex}${Math.floor(alpha * 255)
.toString(16)
.padStart(2, 0)}`;
export const ExpandWrapper = styled.div`
position: absolute;
z-index: 4;
inset: 0;
background: ${({ theme }) => setOpacity(theme.colors.neutral800, 0.2)};
padding: 0 ${({ theme }) => theme.spaces[8]};
`;
export const ExpandContainer = styled(Box)`
display: flex;
max-width: ${1080 / 16}rem;
min-height: ${500 / 16}rem;
margin: 0 auto;
overflow: hidden;
margin-top: 10%;
border: ${({ theme }) => `1px solid ${theme.colors.neutral200}`};
`;
export const PreviewWrapper = styled(Box)`
width: 50%;
border-left: ${({ theme }) => `1px solid ${theme.colors.neutral200}`};
`;
export const WysiwygContainer = styled(Box)`
width: 50%;
`;
export const PreviewHeader = styled(Box)`
border-radius: 0 0 4px 4px;
border-top: 0;
`;
export const PreviewContainer = styled(Box)`
position: relative;
height: 100%;
`;
| packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygStyles.js | 1 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.0024297081399708986,
0.00037779222475364804,
0.0001651095226407051,
0.00017420946096535772,
0.0006488836370408535
] |
{
"id": 2,
"code_window": [
"\n",
" <MoreButton\n",
" ref={buttonMoreRef}\n",
" onClick={onTogglePopover}\n",
" id=\"more\"\n",
" label=\"more\"\n",
" icon={<More />}\n",
" />\n",
" {visiblePopover && (\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" label=\"More\"\n"
],
"file_path": "packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygNav.js",
"type": "replace",
"edit_start_line_idx": 137
} | import React from 'react';
import { RemoveRoundedButton } from '@strapi/helper-plugin';
import Plus from '@strapi/icons/Plus';
import { Box } from '@strapi/design-system/Box';
import { FieldLabel } from '@strapi/design-system/Field';
import { Grid, GridItem } from '@strapi/design-system/Grid';
import { Flex } from '@strapi/design-system/Flex';
import { Stack } from '@strapi/design-system/Stack';
import { TextInput } from '@strapi/design-system/TextInput';
import { TextButton } from '@strapi/design-system/TextButton';
import { Field, FieldArray, useFormikContext } from 'formik';
import { useIntl } from 'react-intl';
import Combobox from './Combobox';
const HeadersInput = () => {
const { formatMessage } = useIntl();
const { values, errors } = useFormikContext();
return (
<Stack size={1}>
<FieldLabel>
{formatMessage({
id: 'Settings.webhooks.form.headers',
defaultMessage: 'Headers',
})}
</FieldLabel>
<Box padding={8} background="neutral100" hasRadius>
<FieldArray
validateOnChange={false}
name="headers"
render={({ push, remove }) => (
<Grid gap={4}>
{values.headers?.map((header, i) => (
// eslint-disable-next-line
<React.Fragment key={i}>
<GridItem col={6}>
<Field
as={Combobox}
name={`headers.${i}.key`}
aria-label={`row ${i + 1} key`}
label={formatMessage({
id: 'Settings.webhooks.key',
defaultMessage: 'Key',
})}
error={
errors.headers?.[i]?.key &&
formatMessage({
id: errors.headers[i]?.key,
defaultMessage: errors.headers[i]?.key,
})
}
/>
</GridItem>
<GridItem col={6}>
<Flex alignItems="flex-end">
<Box style={{ flex: 1 }}>
<Field
as={TextInput}
aria-label={`row ${i + 1} value`}
label={formatMessage({
id: 'Settings.webhooks.value',
defaultMessage: 'Value',
})}
name={`headers.${i}.value`}
error={
errors.headers?.[i]?.value &&
formatMessage({
id: errors.headers[i]?.value,
defaultMessage: errors.headers[i]?.value,
})
}
/>
</Box>
<Flex
paddingLeft={2}
style={{ alignSelf: 'center' }}
paddingTop={errors.headers?.[i]?.value ? 0 : 5}
>
<RemoveRoundedButton
onClick={() => values.headers.length !== 1 && remove(i)}
label={formatMessage(
{
id: 'Settings.webhooks.headers.remove',
defaultMessage: 'Remove header row {number}',
},
{ number: i + 1 }
)}
/>
</Flex>
</Flex>
</GridItem>
</React.Fragment>
))}
<GridItem col={12}>
<TextButton
type="button"
onClick={() => {
push({ key: '', value: '' });
}}
startIcon={<Plus />}
>
{formatMessage({
id: 'Settings.webhooks.create.header',
defaultMessage: 'Create a new header',
})}
</TextButton>
</GridItem>
</Grid>
)}
/>
</Box>
</Stack>
);
};
export default HeadersInput;
| packages/core/admin/admin/src/pages/SettingsPage/pages/Webhooks/EditView/components/HeadersInput/index.js | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.0030732592567801476,
0.0004995413473807275,
0.000165497898706235,
0.0001715341059025377,
0.0008134457748383284
] |
{
"id": 2,
"code_window": [
"\n",
" <MoreButton\n",
" ref={buttonMoreRef}\n",
" onClick={onTogglePopover}\n",
" id=\"more\"\n",
" label=\"more\"\n",
" icon={<More />}\n",
" />\n",
" {visiblePopover && (\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" label=\"More\"\n"
],
"file_path": "packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygNav.js",
"type": "replace",
"edit_start_line_idx": 137
} | 'use strict';
const INVALID_DSN = 'an_invalid_dsn';
const VALID_DSN = 'a_valid_dsn';
const captureException = jest.fn();
// FIXME
/* eslint-disable import/extensions */
jest.mock('@sentry/node', () => {
return {
init(options = {}) {
if (options.dsn !== VALID_DSN) {
throw Error();
}
},
captureException,
withScope(configureScope) {
configureScope();
},
};
});
const sentryServiceLoader = require('../sentry');
const defaultConfig = require('../../config').default;
describe('Sentry service', () => {
beforeEach(() => {
// Reset Strapi state
global.strapi = {
config: {
get: () => defaultConfig,
},
log: {
warn: jest.fn(),
info: jest.fn(),
},
};
});
afterEach(() => {
// Reset the plugin resource state
jest.resetModules();
});
it('disables Sentry when no DSN is provided', () => {
const sentryService = sentryServiceLoader({ strapi });
sentryService.init();
expect(strapi.log.info).toHaveBeenCalledWith(expect.stringMatching(/disabled/i));
const instance = sentryService.getInstance();
expect(instance).toBeNull();
});
it('disables Sentry when an invalid DSN is provided', () => {
global.strapi.config.get = () => ({ dsn: INVALID_DSN });
const sentryService = sentryServiceLoader({ strapi });
sentryService.init();
expect(strapi.log.warn).toHaveBeenCalledWith(expect.stringMatching(/could not set up sentry/i));
const instance = sentryService.getInstance();
expect(instance).toBeNull();
});
it("doesn't send events before init", () => {
const sentryService = sentryServiceLoader({ strapi });
sentryService.sendError(Error());
expect(strapi.log.warn).toHaveBeenCalledWith(expect.stringMatching(/cannot send event/i));
});
it('initializes and sends errors', () => {
global.strapi.config.get = () => ({ dsn: VALID_DSN, sendMetadata: true });
const sentryService = sentryServiceLoader({ strapi });
sentryService.init();
// Saves the instance correctly
const instance = sentryService.getInstance();
expect(instance).not.toBeNull();
// Doesn't allow re-init
sentryService.init();
// Send error
const error = Error('an error');
const configureScope = jest.fn();
sentryService.sendError(error, configureScope);
expect(configureScope).toHaveBeenCalled();
expect(captureException).toHaveBeenCalled();
});
it('does not not send metadata when the option is disabled', () => {
// Init with metadata option disabled
global.strapi.config.get = () => ({ dsn: VALID_DSN, sendMetadata: false });
const sentryService = sentryServiceLoader({ strapi });
sentryService.init();
// Send error
const error = Error('an error');
const configureScope = jest.fn();
sentryService.sendError(error, configureScope);
expect(configureScope).not.toHaveBeenCalled();
});
});
| packages/plugins/sentry/server/services/__tests__/sentry.test.js | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.00017684795602690428,
0.00017327569366898388,
0.00017135523376055062,
0.00017306160589214414,
0.0000016938489579843008
] |
{
"id": 2,
"code_window": [
"\n",
" <MoreButton\n",
" ref={buttonMoreRef}\n",
" onClick={onTogglePopover}\n",
" id=\"more\"\n",
" label=\"more\"\n",
" icon={<More />}\n",
" />\n",
" {visiblePopover && (\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" label=\"More\"\n"
],
"file_path": "packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygNav.js",
"type": "replace",
"edit_start_line_idx": 137
} | module.exports = {
routes: [
{
method: 'GET',
path: '/{{pluralize id}}',
handler: '{{id}}.find',
config: {
policies: [],
},
},
{
method: 'GET',
path: '/{{pluralize id}}/:id',
handler: '{{id}}.findOne',
config: {
policies: [],
},
},
{
method: 'POST',
path: '/{{pluralize id}}',
handler: '{{id}}.create',
config: {
policies: [],
},
},
{
method: 'PUT',
path: '/{{pluralize id}}/:id',
handler: '{{id}}.update',
config: {
policies: [],
},
},
{
method: 'DELETE',
path: '/{{pluralize id}}/:id',
handler: '{{id}}.delete',
config: {
policies: [],
},
},
],
};
| packages/generators/generators/lib/templates/collection-type-routes.js.hbs | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.0001733159297145903,
0.00017170311184599996,
0.00016887433594092727,
0.00017153880617115647,
0.0000016181370483536739
] |
{
"id": 3,
"code_window": [
" name=\"Image\"\n",
" icon={<Image />}\n",
" />\n",
" <CustomIconButton\n",
" onClick={() => onActionClick('Link', editorRef, onTogglePopover)}\n",
" id=\"Link\"\n",
" label=\"Link\"\n",
" name=\"Link\"\n",
" // eslint-disable-next-line jsx-a11y/anchor-is-valid\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <CustomLinkIconButton\n"
],
"file_path": "packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygNav.js",
"type": "replace",
"edit_start_line_idx": 181
} | import styled from 'styled-components';
import { Box } from '@strapi/design-system/Box';
import { IconButtonGroup, IconButton } from '@strapi/design-system/IconButton';
import { BaseButton } from '@strapi/design-system/BaseButton';
export const WysiwygWrapper = styled(Box)`
border: 1px solid
${({ theme, error }) => (error ? theme.colors.danger600 : theme.colors.neutral200)};
margin-top: ${({ theme }) => `${theme.spaces[2]}`};
`;
// NAV BUTTONS
export const CustomIconButton = styled(IconButton)`
padding: ${({ theme }) => theme.spaces[2]};
/* Trick to prevent the outline from overflowing because of the general outline-offset */
outline-offset: -2px !important;
svg {
width: ${18 / 16}rem;
height: ${18 / 16}rem;
}
`;
export const MainButtons = styled(IconButtonGroup)`
margin-left: ${({ theme }) => theme.spaces[4]};
`;
export const MoreButton = styled(IconButton)`
margin: ${({ theme }) => `0 ${theme.spaces[2]}`};
padding: ${({ theme }) => theme.spaces[2]};
svg {
width: ${18 / 16}rem;
height: ${18 / 16}rem;
}
`;
// NAV
export const IconButtonGroupMargin = styled(IconButtonGroup)`
margin-right: ${({ theme }) => `${theme.spaces[2]}`};
`;
// EDITOR && PREVIEW
export const EditorAndPreviewWrapper = styled.div`
position: relative;
`;
// FOOTER
export const ExpandButton = styled(BaseButton)`
background-color: transparent;
border: none;
align-items: center;
svg {
margin-left: ${({ theme }) => `${theme.spaces[2]}`};
path {
fill: ${({ theme }) => theme.colors.neutral700};
width: ${12 / 16}rem;
height: ${12 / 16}rem;
}
}
`;
// PREVIEW
const setOpacity = (hex, alpha) =>
`${hex}${Math.floor(alpha * 255)
.toString(16)
.padStart(2, 0)}`;
export const ExpandWrapper = styled.div`
position: absolute;
z-index: 4;
inset: 0;
background: ${({ theme }) => setOpacity(theme.colors.neutral800, 0.2)};
padding: 0 ${({ theme }) => theme.spaces[8]};
`;
export const ExpandContainer = styled(Box)`
display: flex;
max-width: ${1080 / 16}rem;
min-height: ${500 / 16}rem;
margin: 0 auto;
overflow: hidden;
margin-top: 10%;
border: ${({ theme }) => `1px solid ${theme.colors.neutral200}`};
`;
export const PreviewWrapper = styled(Box)`
width: 50%;
border-left: ${({ theme }) => `1px solid ${theme.colors.neutral200}`};
`;
export const WysiwygContainer = styled(Box)`
width: 50%;
`;
export const PreviewHeader = styled(Box)`
border-radius: 0 0 4px 4px;
border-top: 0;
`;
export const PreviewContainer = styled(Box)`
position: relative;
height: 100%;
`;
| packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygStyles.js | 1 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.0036192878615111113,
0.0004853536665905267,
0.0001656568783801049,
0.00017349499103147537,
0.0009910417720675468
] |
{
"id": 3,
"code_window": [
" name=\"Image\"\n",
" icon={<Image />}\n",
" />\n",
" <CustomIconButton\n",
" onClick={() => onActionClick('Link', editorRef, onTogglePopover)}\n",
" id=\"Link\"\n",
" label=\"Link\"\n",
" name=\"Link\"\n",
" // eslint-disable-next-line jsx-a11y/anchor-is-valid\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <CustomLinkIconButton\n"
],
"file_path": "packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygNav.js",
"type": "replace",
"edit_start_line_idx": 181
} | export const SET_LAYOUT = 'ContentManager/EditViewLayoutManager/SET_LAYOUT';
export const RESET_PROPS = 'ContentManager/EditViewLayoutManager/RESET_PROPS';
| packages/core/admin/admin/src/content-manager/pages/EditViewLayoutManager/constants.js | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.00016356761625502259,
0.00016356761625502259,
0.00016356761625502259,
0.00016356761625502259,
0
] |
{
"id": 3,
"code_window": [
" name=\"Image\"\n",
" icon={<Image />}\n",
" />\n",
" <CustomIconButton\n",
" onClick={() => onActionClick('Link', editorRef, onTogglePopover)}\n",
" id=\"Link\"\n",
" label=\"Link\"\n",
" name=\"Link\"\n",
" // eslint-disable-next-line jsx-a11y/anchor-is-valid\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <CustomLinkIconButton\n"
],
"file_path": "packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygNav.js",
"type": "replace",
"edit_start_line_idx": 181
} | {
"components.Row.generatedDate": "Letztes Mal generiert",
"components.Row.open": "Öffnen",
"components.Row.regenerate": "Neu generieren",
"containers.HomePage.Block.title": "Versionen",
"containers.HomePage.Button.open": "Dokumentation öffnen",
"containers.HomePage.Button.update": "Aktualisieren",
"containers.HomePage.PluginHeader.description": "Einstellungen des Dokumentation-Plugins ändern",
"containers.HomePage.PluginHeader.title": "Dokumentation - Einstellungen",
"containers.HomePage.PopUpWarning.confirm": "Ich verstehe",
"containers.HomePage.PopUpWarning.message": "Sind Sie sich sicher, dass Sie diese Version löschen wollen?",
"containers.HomePage.copied": "Token in der Zwischenablage kopiert",
"containers.HomePage.form.jwtToken": "Jwt Token abrufen",
"containers.HomePage.form.jwtToken.description": "Kopieren Sie diesen Token und nutzen Sie es unter Swagger, um Anfragen zu stellen",
"containers.HomePage.form.password": "Passwort",
"containers.HomePage.form.password.inputDescription": "Setzen Sie ein Passwort, um die Dokumentation privat zu machen",
"containers.HomePage.form.restrictedAccess": "Zugriff beschränken",
"containers.HomePage.form.restrictedAccess.inputDescription": "Den Endpoint der Dokumentation privat machen. Dieser ist standardmäßig öffentlich.",
"containers.HomePage.form.showGeneratedFiles": "Generierte Dateien anzeigen",
"containers.HomePage.form.showGeneratedFiles.inputDescription": "Nützlich, wenn Sie die generierte Dokumentation überschreiben möchten. \nDas Plugin wird nach Modell und Plugin geteilte Dateien erzeugen. \nDurch die Aktivierung dieser Option wird es einfacher sein, Ihre Dokumentation anzupassen.",
"error.deleteDoc.versionMissing": "Die Version, die Sie zu löschen versuchen, existiert nicht.",
"error.noVersion": "Eine Version wird benötigt",
"error.regenerateDoc": "Ein Fehler ist während dem Neu-Erstellen der Dokumentation aufgetreten.",
"error.regenerateDoc.versionMissing": "Die Version, die Sie zu generieren versuchen, existiert nicht",
"notification.delete.success": "Dokument wurde erfolgreich gelöscht",
"notification.generate.success": "Dokument wurde erfolgreich generiert",
"notification.update.success": "Einstellungen wurden erfolgreich aktualisiert",
"plugin.name": "Dokumentation"
}
| packages/plugins/documentation/admin/src/translations/de.json | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.00017811091674957424,
0.0001734740799292922,
0.00017004985420498997,
0.00017226149793714285,
0.000003400780997253605
] |
{
"id": 3,
"code_window": [
" name=\"Image\"\n",
" icon={<Image />}\n",
" />\n",
" <CustomIconButton\n",
" onClick={() => onActionClick('Link', editorRef, onTogglePopover)}\n",
" id=\"Link\"\n",
" label=\"Link\"\n",
" name=\"Link\"\n",
" // eslint-disable-next-line jsx-a11y/anchor-is-valid\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <CustomLinkIconButton\n"
],
"file_path": "packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygNav.js",
"type": "replace",
"edit_start_line_idx": 181
} | import styled, { keyframes } from 'styled-components';
const loading = keyframes`
from {
left: -100px;
width: 30%;
}
50% {
width: 30%;
}
70% {
width: 70%;
}
80% {
left: 50%;
}
95% {
left: 120%;
}
to {
left: 100%;
}
`;
const LoadingIndicator = styled.div`
position: relative;
width: 44%;
height: 4px;
overflow: hidden;
background-color: #515764;
border-radius: 2px;
&:before {
content: '';
display: block;
position: absolute;
left: -100px;
width: 100px;
height: 4px;
background-color: #b3b5b9;
animation: ${loading} 2s linear infinite;
}
`;
export default LoadingIndicator;
| packages/core/upload/admin/src/components/LoadingIndicator/index.js | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.00017788416880648583,
0.00017223083705175668,
0.00016455454169772565,
0.00017329378169961274,
0.000004419436208991101
] |
{
"id": 4,
"code_window": [
" height: ${18 / 16}rem;\n",
" }\n",
"`;\n",
"\n",
"export const MainButtons = styled(IconButtonGroup)`\n",
" margin-left: ${({ theme }) => theme.spaces[4]};\n",
"`;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"export const CustomLinkIconButton = styled(CustomIconButton)`\n",
" svg {\n",
" width: ${8 / 16}rem;\n",
" height: ${8 / 16}rem;\n",
" }\n",
"`;\n",
"\n"
],
"file_path": "packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygStyles.js",
"type": "add",
"edit_start_line_idx": 23
} | import React, { useRef } from 'react';
import PropTypes from 'prop-types';
import { useIntl } from 'react-intl';
import { Box } from '@strapi/design-system/Box';
import { Button } from '@strapi/design-system/Button';
import { IconButtonGroup } from '@strapi/design-system/IconButton';
import { Option, Select } from '@strapi/design-system/Select';
import { Popover } from '@strapi/design-system/Popover';
import { Flex } from '@strapi/design-system/Flex';
import Bold from '@strapi/icons/Bold';
import Italic from '@strapi/icons/Italic';
import Underline from '@strapi/icons/Underline';
import Strikethrough from '@strapi/icons/StrikeThrough';
import BulletList from '@strapi/icons/BulletList';
import NumberList from '@strapi/icons/NumberList';
import Code from '@strapi/icons/Code';
import Image from '@strapi/icons/Picture';
import Link from '@strapi/icons/Link';
import Quote from '@strapi/icons/Quote';
import More from '@strapi/icons/More';
import { MainButtons, CustomIconButton, MoreButton, IconButtonGroupMargin } from './WysiwygStyles';
const WysiwygNav = ({
editorRef,
isPreviewMode,
onActionClick,
onToggleMediaLib,
onTogglePopover,
onTogglePreviewMode,
noPreviewMode,
visiblePopover,
}) => {
const { formatMessage } = useIntl();
const selectPlaceholder = formatMessage({
id: 'components.Wysiwyg.selectOptions.title',
defaultMessage: 'Add a title',
});
const buttonMoreRef = useRef();
if (isPreviewMode) {
return (
<Box padding={2} background="neutral100">
<Flex justifyContent="space-between">
<Flex>
<Select
disabled
id="selectTitle"
placeholder={selectPlaceholder}
size="S"
aria-label={selectPlaceholder}
>
<Option value="h1">h1</Option>
<Option value="h2">h2</Option>
<Option value="h3">h3</Option>
<Option value="h4">h4</Option>
<Option value="h5">h5</Option>
<Option value="h6">h6</Option>
</Select>
<MainButtons>
<CustomIconButton disabled id="Bold" label="Bold" name="Bold" icon={<Bold />} />
<CustomIconButton
disabled
id="Italic"
label="Italic"
name="Italic"
icon={<Italic />}
/>
<CustomIconButton
disabled
id="Underline"
label="Underline"
name="Underline"
icon={<Underline />}
/>
</MainButtons>
<MoreButton disabled ref={buttonMoreRef} id="more" label="more" icon={<More />} />
</Flex>
<Button onClick={onTogglePreviewMode} variant="tertiary" size="L" id="preview">
{formatMessage({
id: 'components.Wysiwyg.ToggleMode.markdown-mode',
defaultMessage: 'Markdown mode',
})}
</Button>
</Flex>
</Box>
);
}
return (
<Box padding={2} background="neutral100">
<Flex justifyContent="space-between">
<Flex>
<Select
id="selectTitle"
placeholder={selectPlaceholder}
size="S"
onChange={value => onActionClick(value, editorRef)}
>
<Option value="h1">h1</Option>
<Option value="h2">h2</Option>
<Option value="h3">h3</Option>
<Option value="h4">h4</Option>
<Option value="h5">h5</Option>
<Option value="h6">h6</Option>
</Select>
<MainButtons>
<CustomIconButton
onClick={() => onActionClick('Bold', editorRef)}
id="Bold"
label="Bold"
name="Bold"
icon={<Bold />}
/>
<CustomIconButton
onClick={() => onActionClick('Italic', editorRef)}
id="Italic"
label="Italic"
name="Italic"
icon={<Italic />}
/>
<CustomIconButton
onClick={() => onActionClick('Underline', editorRef)}
id="Underline"
label="Underline"
name="Underline"
icon={<Underline />}
/>
</MainButtons>
<MoreButton
ref={buttonMoreRef}
onClick={onTogglePopover}
id="more"
label="more"
icon={<More />}
/>
{visiblePopover && (
<Popover centered source={buttonMoreRef} spacing={4} id="popover">
<Flex>
<IconButtonGroupMargin>
<CustomIconButton
onClick={() => onActionClick('Strikethrough', editorRef, onTogglePopover)}
id="Strikethrough"
label="Strikethrough"
name="Strikethrough"
icon={<Strikethrough />}
/>
<CustomIconButton
onClick={() => onActionClick('BulletList', editorRef, onTogglePopover)}
id="BulletList"
label="BulletList"
name="BulletList"
icon={<BulletList />}
/>
<CustomIconButton
onClick={() => onActionClick('NumberList', editorRef, onTogglePopover)}
id="NumberList"
label="NumberList"
name="NumberList"
icon={<NumberList />}
/>
</IconButtonGroupMargin>
<IconButtonGroup>
<CustomIconButton
onClick={() => onActionClick('Code', editorRef, onTogglePopover)}
id="Code"
label="Code"
name="Code"
icon={<Code />}
/>
<CustomIconButton
onClick={onToggleMediaLib}
id="Image"
label="Image"
name="Image"
icon={<Image />}
/>
<CustomIconButton
onClick={() => onActionClick('Link', editorRef, onTogglePopover)}
id="Link"
label="Link"
name="Link"
// eslint-disable-next-line jsx-a11y/anchor-is-valid
icon={<Link />}
/>
<CustomIconButton
onClick={() => onActionClick('Quote', editorRef, onTogglePopover)}
id="Quote"
label="Quote"
name="Quote"
icon={<Quote />}
/>
</IconButtonGroup>
</Flex>
</Popover>
)}
</Flex>
{!noPreviewMode && onTogglePreviewMode && (
<Button onClick={onTogglePreviewMode} variant="tertiary" size="L" id="preview">
{formatMessage({
id: 'components.Wysiwyg.ToggleMode.preview-mode',
defaultMessage: 'Preview mode',
})}
</Button>
)}
</Flex>
</Box>
);
};
WysiwygNav.defaultProps = {
isPreviewMode: false,
onActionClick: () => {},
onToggleMediaLib: () => {},
onTogglePopover: () => {},
onTogglePreviewMode: () => {},
noPreviewMode: false,
visiblePopover: false,
};
WysiwygNav.propTypes = {
editorRef: PropTypes.shape({ current: PropTypes.any }).isRequired,
isPreviewMode: PropTypes.bool,
onActionClick: PropTypes.func,
onToggleMediaLib: PropTypes.func,
onTogglePopover: PropTypes.func,
onTogglePreviewMode: PropTypes.func,
visiblePopover: PropTypes.bool,
noPreviewMode: PropTypes.bool,
};
export default WysiwygNav;
| packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygNav.js | 1 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.9969979524612427,
0.13294145464897156,
0.0001647429307922721,
0.000174434288055636,
0.3241126537322998
] |
{
"id": 4,
"code_window": [
" height: ${18 / 16}rem;\n",
" }\n",
"`;\n",
"\n",
"export const MainButtons = styled(IconButtonGroup)`\n",
" margin-left: ${({ theme }) => theme.spaces[4]};\n",
"`;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"export const CustomLinkIconButton = styled(CustomIconButton)`\n",
" svg {\n",
" width: ${8 / 16}rem;\n",
" height: ${8 / 16}rem;\n",
" }\n",
"`;\n",
"\n"
],
"file_path": "packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygStyles.js",
"type": "add",
"edit_start_line_idx": 23
} | 'use strict';
const { createTestBuilder } = require('../../../../../test/helpers/builder');
const { createStrapiInstance } = require('../../../../../test/helpers/strapi');
const { createContentAPIRequest } = require('../../../../../test/helpers/request');
let strapi;
let rq;
const component = {
name: 'somecomponent',
attributes: {
name: {
type: 'string',
},
},
};
const ct = {
displayName: 'withcomponent',
singularName: 'withcomponent',
pluralName: 'withcomponents',
attributes: {
field: {
type: 'component',
component: 'default.somecomponent',
repeatable: true,
required: false,
},
},
};
describe('Non repeatable and Not required component', () => {
const builder = createTestBuilder();
beforeAll(async () => {
await builder
.addComponent(component)
.addContentType(ct)
.build();
strapi = await createStrapiInstance();
rq = await createContentAPIRequest({ strapi });
rq.setURLPrefix('/api/withcomponents');
});
afterAll(async () => {
await strapi.destroy();
await builder.cleanup();
});
describe('POST new entry', () => {
test('Creating entry with JSON works', async () => {
const res = await rq.post('/', {
body: {
data: {
field: [
{
name: 'someString',
},
],
},
},
qs: {
populate: ['field'],
},
});
expect(res.statusCode).toBe(200);
expect(Array.isArray(res.body.data.attributes.field)).toBe(true);
expect(res.body.data.attributes.field).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: expect.anything(),
name: 'someString',
}),
])
);
});
test.each(['someString', 128219, false, {}, null])(
'Throws if the field is not an object %p',
async value => {
const res = await rq.post('/', {
body: {
data: {
field: value,
},
},
});
expect(res.statusCode).toBe(400);
}
);
test('Can send an empty array', async () => {
const res = await rq.post('/', {
body: {
data: {
field: [],
},
},
qs: {
populate: ['field'],
},
});
expect(res.statusCode).toBe(200);
expect(res.body.data.attributes.field).toEqual([]);
});
test('Can send input without the component field', async () => {
const res = await rq.post('/', {
body: {
data: {},
},
qs: {
populate: ['field'],
},
});
expect(res.statusCode).toBe(200);
expect(res.body.data.attributes.field).toEqual([]);
});
});
describe('GET entries', () => {
test('Data is orderd in the order sent', async () => {
const res = await rq.post('/', {
body: {
data: {
field: [
{
name: 'firstString',
},
{
name: 'someString',
},
],
},
},
qs: {
populate: ['field'],
},
});
const getRes = await rq.get(`/${res.body.data.id}`, {
qs: {
populate: ['field'],
},
});
expect(getRes.statusCode).toBe(200);
expect(Array.isArray(getRes.body.data.attributes.field)).toBe(true);
expect(getRes.body.data.attributes.field[0]).toMatchObject({
name: 'firstString',
});
expect(getRes.body.data.attributes.field[1]).toMatchObject({
name: 'someString',
});
});
test('Should return entries with their nested components', async () => {
const res = await rq.get('/', {
qs: {
populate: ['field'],
},
});
expect(res.statusCode).toBe(200);
expect(Array.isArray(res.body.data)).toBe(true);
res.body.data.forEach(entry => {
expect(Array.isArray(entry.attributes.field)).toBe(true);
if (entry.attributes.field.length === 0) return;
expect(entry.attributes.field).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: expect.any(String),
}),
])
);
});
});
});
describe('PUT entry', () => {
test.each(['someString', 128219, false, {}, null])(
'Throws when sending invalid updated field %p',
async value => {
const res = await rq.post('/', {
body: {
data: {
field: [
{
name: 'someString',
},
],
},
},
qs: {
populate: ['field'],
},
});
const updateRes = await rq.put(`/${res.body.data.id}`, {
body: {
data: {
field: value,
},
},
qs: {
populate: ['field'],
},
});
expect(updateRes.statusCode).toBe(400);
// shouldn't have been updated
const getRes = await rq.get(`/${res.body.data.id}`, {
qs: {
populate: ['field'],
},
});
expect(getRes.statusCode).toBe(200);
expect(getRes.body.data).toMatchObject({
id: res.body.data.id,
attributes: { field: res.body.data.attributes.field },
});
}
);
test('Updates order at each request', async () => {
const res = await rq.post('/', {
body: {
data: {
field: [
{
name: 'someString',
},
{
name: 'otherString',
},
],
},
},
qs: {
populate: ['field'],
},
});
expect(res.body.data.attributes.field[0]).toMatchObject({
name: 'someString',
});
expect(res.body.data.attributes.field[1]).toMatchObject({
name: 'otherString',
});
const updateRes = await rq.put(`/${res.body.data.id}`, {
body: {
data: {
field: [
{
name: 'otherString',
},
{
name: 'someString',
},
],
},
},
qs: {
populate: ['field'],
},
});
expect(updateRes.statusCode).toBe(200);
expect(Array.isArray(updateRes.body.data.attributes.field)).toBe(true);
expect(updateRes.body.data.attributes.field[0]).toMatchObject({
name: 'otherString',
});
expect(updateRes.body.data.attributes.field[1]).toMatchObject({
name: 'someString',
});
const getRes = await rq.get(`/${res.body.data.id}`, {
qs: {
populate: ['field'],
},
});
expect(getRes.statusCode).toBe(200);
expect(Array.isArray(getRes.body.data.attributes.field)).toBe(true);
expect(getRes.body.data.attributes.field[0]).toMatchObject({
name: 'otherString',
});
expect(getRes.body.data.attributes.field[1]).toMatchObject({
name: 'someString',
});
});
test('Keeps the previous value if component not sent', async () => {
const res = await rq.post('/', {
body: {
data: {
field: [
{
name: 'someString',
},
{
name: 'otherString',
},
],
},
},
qs: {
populate: ['field'],
},
});
const updateRes = await rq.put(`/${res.body.data.id}`, {
body: {
data: {},
},
qs: {
populate: ['field'],
},
});
expect(updateRes.statusCode).toBe(200);
expect(updateRes.body.data).toMatchObject({
id: res.body.data.id,
attributes: { field: res.body.data.attributes.field },
});
const getRes = await rq.get(`/${res.body.data.id}`, {
qs: {
populate: ['field'],
},
});
expect(getRes.statusCode).toBe(200);
expect(getRes.body.data).toMatchObject({
id: res.body.data.id,
attributes: { field: res.body.data.attributes.field },
});
});
test('Removes previous components if empty array sent', async () => {
const res = await rq.post('/', {
body: {
data: {
field: [
{
name: 'someString',
},
],
},
},
qs: {
populate: ['field'],
},
});
const updateRes = await rq.put(`/${res.body.data.id}`, {
body: {
data: {
field: [],
},
},
qs: {
populate: ['field'],
},
});
const expectResult = {
id: res.body.data.id,
attributes: { field: [] },
};
expect(updateRes.statusCode).toBe(200);
expect(updateRes.body.data).toMatchObject(expectResult);
const getRes = await rq.get(`/${res.body.data.id}`, {
qs: {
populate: ['field'],
},
});
expect(getRes.statusCode).toBe(200);
expect(getRes.body.data).toMatchObject(expectResult);
});
test('Replaces the previous components if sent without id', async () => {
const res = await rq.post('/', {
body: {
data: {
field: [
{
name: 'someString',
},
],
},
},
qs: {
populate: ['field'],
},
});
const updateRes = await rq.put(`/${res.body.data.id}`, {
body: {
data: {
field: [
{
name: 'new String',
},
],
},
},
qs: {
populate: ['field'],
},
});
expect(updateRes.statusCode).toBe(200);
const oldIds = res.body.data.attributes.field.map(val => val.id);
updateRes.body.data.attributes.field.forEach(val => {
expect(oldIds.includes(val.id)).toBe(false);
});
expect(updateRes.body.data).toMatchObject({
id: res.body.data.id,
attributes: {
field: [
{
name: 'new String',
},
],
},
});
const getRes = await rq.get(`/${res.body.data.id}`, {
qs: {
populate: ['field'],
},
});
expect(getRes.statusCode).toBe(200);
expect(getRes.body.data).toMatchObject({
id: res.body.data.id,
attributes: {
field: [
{
name: 'new String',
},
],
},
});
});
test('Throws on invalid id in component', async () => {
const res = await rq.post('/', {
body: {
data: {
field: [
{
name: 'someString',
},
],
},
},
});
const updateRes = await rq.put(`/${res.body.data.id}`, {
body: {
data: {
field: [
{
id: 'invalid_id',
name: 'new String',
},
],
},
},
});
expect(updateRes.statusCode).toBe(400);
});
test('Updates component with ids, create new ones and removes old ones', async () => {
const res = await rq.post('/', {
body: {
data: {
field: [
{
name: 'one',
},
{
name: 'two',
},
{
name: 'three',
},
],
},
},
qs: {
populate: ['field'],
},
});
const updateRes = await rq.put(`/${res.body.data.id}`, {
body: {
data: {
field: [
{
id: res.body.data.attributes.field[0].id, // send old id to update the previous component
name: 'newOne',
},
{
name: 'newTwo',
},
{
id: res.body.data.attributes.field[2].id,
name: 'three',
},
{
name: 'four',
},
],
},
},
qs: {
populate: ['field'],
},
});
const expectedResult = {
id: res.body.data.id,
attributes: {
field: [
{
id: res.body.data.attributes.field[0].id,
name: 'newOne',
},
{
name: 'newTwo',
},
{
id: res.body.data.attributes.field[2].id,
name: 'three',
},
{
name: 'four',
},
],
},
};
expect(updateRes.statusCode).toBe(200);
expect(updateRes.body.data).toMatchObject(expectedResult);
const getRes = await rq.get(`/${res.body.data.id}`, {
qs: {
populate: ['field'],
},
});
expect(getRes.statusCode).toBe(200);
expect(getRes.body.data).toMatchObject(expectedResult);
});
});
describe('DELETE entry', () => {
test('Returns entry with components', async () => {
const res = await rq.post('/', {
body: {
data: {
field: [
{
name: 'someString',
},
{
name: 'someOtherString',
},
{
name: 'otherSomeString',
},
],
},
},
qs: {
populate: ['field'],
},
});
const deleteRes = await rq.delete(`/${res.body.data.id}`, {
qs: {
populate: ['field'],
},
});
expect(deleteRes.statusCode).toBe(200);
expect(deleteRes.body.data).toMatchObject(res.body.data);
const getRes = await rq.get(`/${res.body.data.id}`, {
qs: {
populate: ['field'],
},
});
expect(getRes.statusCode).toBe(404);
});
});
});
| packages/core/strapi/tests/components/repeatable-not-required.test.e2e.js | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.000176619112608023,
0.00017160861170850694,
0.0001653263025218621,
0.0001720664877211675,
0.0000025748809093784075
] |
{
"id": 4,
"code_window": [
" height: ${18 / 16}rem;\n",
" }\n",
"`;\n",
"\n",
"export const MainButtons = styled(IconButtonGroup)`\n",
" margin-left: ${({ theme }) => theme.spaces[4]};\n",
"`;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"export const CustomLinkIconButton = styled(CustomIconButton)`\n",
" svg {\n",
" width: ${8 / 16}rem;\n",
" height: ${8 / 16}rem;\n",
" }\n",
"`;\n",
"\n"
],
"file_path": "packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygStyles.js",
"type": "add",
"edit_start_line_idx": 23
} | 'use strict';
/**
* @description Determines the format of the data response
*
* @param {boolean} isListOfEntities - Checks for a multiple entities
* @param {object} attributes - The attributes found on a contentType
* @returns object | array of attributes
*/
module.exports = (isListOfEntities, attributes) => {
if (isListOfEntities) {
return {
type: 'array',
items: {
type: 'object',
properties: {
id: { type: 'string' },
attributes: { type: 'object', properties: attributes },
},
},
};
}
return {
type: 'object',
properties: {
id: { type: 'string' },
attributes: { type: 'object', properties: attributes },
},
};
};
| packages/plugins/documentation/server/utils/get-schema-data.js | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.00017421194934286177,
0.00017193009261973202,
0.00017061473045032471,
0.00017144688172265887,
0.000001413188783772057
] |
{
"id": 4,
"code_window": [
" height: ${18 / 16}rem;\n",
" }\n",
"`;\n",
"\n",
"export const MainButtons = styled(IconButtonGroup)`\n",
" margin-left: ${({ theme }) => theme.spaces[4]};\n",
"`;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"export const CustomLinkIconButton = styled(CustomIconButton)`\n",
" svg {\n",
" width: ${8 / 16}rem;\n",
" height: ${8 / 16}rem;\n",
" }\n",
"`;\n",
"\n"
],
"file_path": "packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygStyles.js",
"type": "add",
"edit_start_line_idx": 23
} | 'use strict';
module.exports = {
type: 'admin',
routes: [
{
method: 'GET',
path: '/settings',
handler: 'admin-api.getSettings',
config: {
policies: [
'admin::isAuthenticatedAdmin',
{
name: 'admin::hasPermissions',
config: {
actions: ['plugin::upload.settings.read'],
},
},
],
},
},
{
method: 'PUT',
path: '/settings',
handler: 'admin-api.updateSettings',
config: {
policies: [
'admin::isAuthenticatedAdmin',
{
name: 'admin::hasPermissions',
config: {
actions: ['plugin::upload.settings.read'],
},
},
],
},
},
{
method: 'POST',
path: '/',
handler: 'admin-api.upload',
config: {
policies: ['admin::isAuthenticatedAdmin'],
},
},
{
method: 'GET',
path: '/files',
handler: 'admin-api.find',
config: {
policies: [
'admin::isAuthenticatedAdmin',
{
name: 'admin::hasPermissions',
config: {
actions: ['plugin::upload.read'],
},
},
],
},
},
{
method: 'GET',
path: '/files/:id',
handler: 'admin-api.findOne',
config: {
policies: [
'admin::isAuthenticatedAdmin',
{
name: 'admin::hasPermissions',
config: {
actions: ['plugin::upload.read'],
},
},
],
},
},
{
method: 'DELETE',
path: '/files/:id',
handler: 'admin-api.destroy',
config: {
policies: [
'admin::isAuthenticatedAdmin',
{
name: 'admin::hasPermissions',
config: {
actions: ['plugin::upload.assets.update'],
},
},
],
},
},
],
};
| packages/core/upload/server/routes/admin.js | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.0001744348555803299,
0.00016916431195568293,
0.00016272661741822958,
0.00016881237388588488,
0.0000030631310892204056
] |
{
"id": 5,
"code_window": [
" background: #d9d8ff;\n",
" }\n",
"\n",
" .c40:hover:not([aria-disabled='true']) svg path {\n",
" fill: #4945ff;\n",
" }\n",
"\n",
" .c47 {\n",
" background: transparent;\n",
" border: none;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/plugins/users-permissions/admin/src/pages/Roles/CreatePage/tests/index.test.js",
"type": "replace",
"edit_start_line_idx": 772
} | import React from 'react';
import { render, waitFor, waitForElementToBeRemoved } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ThemeProvider, lightTheme } from '@strapi/design-system';
import { Router, Switch, Route } from 'react-router-dom';
import { IntlProvider } from 'react-intl';
import { createMemoryHistory } from 'history';
import pluginId from '../../../../pluginId';
import RolesEditPage from '..';
import server from './server';
jest.mock('@strapi/helper-plugin', () => {
// Make sure the references of the mock functions stay the same, otherwise we get an endless loop
const mockToggleNotification = jest.fn();
const mockUseNotification = jest.fn(() => {
return mockToggleNotification;
});
return {
...jest.requireActual('@strapi/helper-plugin'),
useNotification: mockUseNotification,
useOverlayBlocker: jest.fn(() => ({ lockApp: jest.fn(), unlockApp: jest.fn() })),
};
});
function makeAndRenderApp() {
const history = createMemoryHistory();
const app = (
<IntlProvider locale="en" messages={{}} textComponent="span">
<ThemeProvider theme={lightTheme}>
<Router history={history}>
<Switch>
<Route path={`/settings/${pluginId}/roles/:id`} component={RolesEditPage} />
</Switch>
</Router>
</ThemeProvider>
</IntlProvider>
);
const renderResult = render(app);
history.push(`/settings/${pluginId}/roles/1`);
return renderResult;
}
describe('Admin | containers | RoleEditPage', () => {
beforeAll(() => server.listen());
beforeEach(() => jest.clearAllMocks());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
it('renders users-permissions edit role and matches snapshot', async () => {
const { container, getByTestId, getByRole } = makeAndRenderApp();
await waitForElementToBeRemoved(() => getByTestId('loader'));
await waitFor(() => expect(getByRole('heading', { name: /permissions/i })).toBeInTheDocument());
expect(container.firstChild).toMatchInlineSnapshot(`
.c1 {
background: #f6f6f9;
padding-top: 24px;
padding-right: 56px;
padding-bottom: 56px;
padding-left: 56px;
}
.c2 {
padding-bottom: 12px;
}
.c21 {
padding-right: 56px;
padding-left: 56px;
}
.c9 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-box-pack: justify;
-webkit-justify-content: space-between;
-ms-flex-pack: justify;
justify-content: space-between;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c10 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c11 {
font-weight: 600;
font-size: 2rem;
line-height: 1.25;
color: #32324d;
}
.c19 {
font-weight: 400;
font-size: 0.875rem;
line-height: 1.43;
color: #666687;
}
.c20 {
font-size: 1rem;
line-height: 1.5;
}
.c0 {
outline: none;
}
.c18 {
font-weight: 500;
font-size: 0.75rem;
line-height: 1.33;
color: #32324d;
}
.c15 {
padding-right: 8px;
}
.c12 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
cursor: pointer;
padding: 8px;
border-radius: 4px;
background: #ffffff;
border: 1px solid #dcdce4;
position: relative;
outline: none;
}
.c12 svg {
height: 12px;
width: 12px;
}
.c12 svg > g,
.c12 svg path {
fill: #ffffff;
}
.c12[aria-disabled='true'] {
pointer-events: none;
}
.c12:after {
-webkit-transition-property: all;
transition-property: all;
-webkit-transition-duration: 0.2s;
transition-duration: 0.2s;
border-radius: 8px;
content: '';
position: absolute;
top: -4px;
bottom: -4px;
left: -4px;
right: -4px;
border: 2px solid transparent;
}
.c12:focus-visible {
outline: none;
}
.c12:focus-visible:after {
border-radius: 8px;
content: '';
position: absolute;
top: -5px;
bottom: -5px;
left: -5px;
right: -5px;
border: 2px solid #4945ff;
}
.c16 {
height: 100%;
}
.c13 {
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
padding: 8px 16px;
background: #4945ff;
border: none;
border: 1px solid #4945ff;
background: #4945ff;
}
.c13 .c14 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c13 .c17 {
color: #ffffff;
}
.c13[aria-disabled='true'] {
border: 1px solid #dcdce4;
background: #eaeaef;
}
.c13[aria-disabled='true'] .c17 {
color: #666687;
}
.c13[aria-disabled='true'] svg > g,
.c13[aria-disabled='true'] svg path {
fill: #666687;
}
.c13[aria-disabled='true']:active {
border: 1px solid #dcdce4;
background: #eaeaef;
}
.c13[aria-disabled='true']:active .c17 {
color: #666687;
}
.c13[aria-disabled='true']:active svg > g,
.c13[aria-disabled='true']:active svg path {
fill: #666687;
}
.c13:hover {
border: 1px solid #7b79ff;
background: #7b79ff;
}
.c13:active {
border: 1px solid #4945ff;
background: #4945ff;
}
.c22 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
}
.c22 > * {
margin-top: 0;
margin-bottom: 0;
}
.c22 > * + * {
margin-top: 32px;
}
.c24 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
}
.c24 > * {
margin-top: 0;
margin-bottom: 0;
}
.c24 > * + * {
margin-top: 16px;
}
.c44 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
}
.c44 > * {
margin-top: 0;
margin-bottom: 0;
}
.c44 > * + * {
margin-top: 8px;
}
.c23 {
background: #ffffff;
padding-top: 24px;
padding-right: 32px;
padding-bottom: 24px;
padding-left: 32px;
border-radius: 4px;
box-shadow: 0px 1px 4px rgba(33,33,52,0.1);
}
.c30 {
font-weight: 500;
font-size: 0.75rem;
line-height: 1.33;
color: #32324d;
}
.c29 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c31 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-box-pack: justify;
-webkit-justify-content: space-between;
-ms-flex-pack: justify;
justify-content: space-between;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c33 {
border: none;
border-radius: 4px;
padding-left: 16px;
padding-right: 16px;
color: #32324d;
font-weight: 400;
font-size: 0.875rem;
display: block;
width: 100%;
}
.c33::-webkit-input-placeholder {
color: #8e8ea9;
opacity: 1;
}
.c33::-moz-placeholder {
color: #8e8ea9;
opacity: 1;
}
.c33:-ms-input-placeholder {
color: #8e8ea9;
opacity: 1;
}
.c33::placeholder {
color: #8e8ea9;
opacity: 1;
}
.c33[aria-disabled='true'] {
background: inherit;
color: inherit;
}
.c33:focus {
outline: none;
box-shadow: none;
}
.c32 {
border: 1px solid #dcdce4;
border-radius: 4px;
background: #ffffff;
height: 2.5rem;
outline: none;
box-shadow: 0;
-webkit-transition-property: border-color,box-shadow,fill;
transition-property: border-color,box-shadow,fill;
-webkit-transition-duration: 0.2s;
transition-duration: 0.2s;
}
.c32:focus-within {
border: 1px solid #4945ff;
box-shadow: #4945ff 0px 0px 0px 2px;
}
.c28 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
}
.c28 > * {
margin-top: 0;
margin-bottom: 0;
}
.c28 > * + * {
margin-top: 4px;
}
.c37 {
font-weight: 500;
font-size: 0.75rem;
line-height: 1.33;
color: #32324d;
}
.c36 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c38 {
border: 1px solid #dcdce4;
border-radius: 4px;
padding-left: 16px;
padding-right: 16px;
padding-top: 12px;
padding-bottom: 12px;
background: #ffffff;
outline: none;
box-shadow: 0;
-webkit-transition-property: border-color,box-shadow,fill;
transition-property: border-color,box-shadow,fill;
-webkit-transition-duration: 0.2s;
transition-duration: 0.2s;
}
.c38:focus-within {
border: 1px solid #4945ff;
box-shadow: #4945ff 0px 0px 0px 2px;
}
.c39 {
display: block;
width: 100%;
font-weight: 400;
font-size: 0.875rem;
border: none;
color: #32324d;
resize: none;
}
.c39::-webkit-input-placeholder {
color: #8e8ea9;
opacity: 1;
}
.c39::-moz-placeholder {
color: #8e8ea9;
opacity: 1;
}
.c39:-ms-input-placeholder {
color: #8e8ea9;
opacity: 1;
}
.c39::placeholder {
color: #8e8ea9;
opacity: 1;
}
.c39:focus-within {
outline: none;
}
.c35 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
}
.c35 > * {
margin-top: 0;
margin-bottom: 0;
}
.c35 > * + * {
margin-top: 4px;
}
.c34 textarea {
height: 5rem;
line-height: 1.25rem;
}
.c34 textarea::-webkit-input-placeholder {
font-weight: 400;
font-size: 0.875rem;
line-height: 1.43;
color: #8e8ea9;
opacity: 1;
}
.c34 textarea::-moz-placeholder {
font-weight: 400;
font-size: 0.875rem;
line-height: 1.43;
color: #8e8ea9;
opacity: 1;
}
.c34 textarea:-ms-input-placeholder {
font-weight: 400;
font-size: 0.875rem;
line-height: 1.43;
color: #8e8ea9;
opacity: 1;
}
.c34 textarea::placeholder {
font-weight: 400;
font-size: 0.875rem;
line-height: 1.43;
color: #8e8ea9;
opacity: 1;
}
.c25 {
font-weight: 500;
font-size: 1rem;
line-height: 1.25;
color: #32324d;
}
.c45 {
font-weight: 400;
font-size: 0.875rem;
line-height: 1.43;
color: #666687;
}
.c6 {
font-weight: 400;
font-size: 0.875rem;
line-height: 1.43;
color: #4945ff;
}
.c7 {
font-weight: 600;
line-height: 1.14;
}
.c8 {
font-weight: 600;
font-size: 0.6875rem;
line-height: 1.45;
text-transform: uppercase;
}
.c4 {
padding-right: 8px;
}
.c3 {
display: -webkit-inline-box;
display: -webkit-inline-flex;
display: -ms-inline-flexbox;
display: inline-flex;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
text-transform: uppercase;
-webkit-text-decoration: none;
text-decoration: none;
position: relative;
outline: none;
}
.c3 svg path {
fill: #4945ff;
}
.c3 svg {
font-size: 0.625rem;
}
.c3:after {
-webkit-transition-property: all;
transition-property: all;
-webkit-transition-duration: 0.2s;
transition-duration: 0.2s;
border-radius: 8px;
content: '';
position: absolute;
top: -4px;
bottom: -4px;
left: -4px;
right: -4px;
border: 2px solid transparent;
}
.c3:focus-visible {
outline: none;
}
.c3:focus-visible:after {
border-radius: 8px;
content: '';
position: absolute;
top: -5px;
bottom: -5px;
left: -5px;
right: -5px;
border: 2px solid #4945ff;
}
.c5 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
}
.c40 {
background: #ffffff;
border-radius: 4px;
box-shadow: 0px 1px 4px rgba(33,33,52,0.1);
}
.c43 {
padding-top: 24px;
padding-right: 32px;
padding-bottom: 24px;
padding-left: 32px;
}
.c67 {
background: #eaeaef;
padding-top: 24px;
padding-right: 32px;
padding-bottom: 24px;
padding-left: 32px;
}
.c26 {
display: grid;
grid-template-columns: repeat(12,1fr);
gap: 16px;
}
.c41 {
display: grid;
grid-template-columns: repeat(12,1fr);
gap: 0px;
}
.c27 {
grid-column: span 6;
}
.c42 {
grid-column: span 7;
}
.c66 {
grid-column: span 5;
}
.c59 {
font-weight: 500;
font-size: 1rem;
line-height: 1.25;
color: #4a4a6a;
}
.c57 {
font-weight: 400;
font-size: 0.75rem;
line-height: 1.33;
color: #4945ff;
}
.c60 {
font-weight: 400;
font-size: 0.875rem;
line-height: 1.43;
color: #666687;
}
.c46 {
border-radius: 4px;
}
.c49 {
background: #ffffff;
padding-right: 24px;
padding-left: 24px;
}
.c52 {
-webkit-flex: 1;
-ms-flex: 1;
flex: 1;
}
.c62 {
background: #dcdce4;
border-radius: 50%;
cursor: pointer;
width: 2rem;
height: 2rem;
cursor: pointer;
}
.c64 {
color: #666687;
width: 0.6875rem;
}
.c50 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-box-pack: justify;
-webkit-justify-content: space-between;
-ms-flex-pack: justify;
justify-content: space-between;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c53 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c63 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.c47 {
border: 1px solid #ffffff;
overflow: hidden;
}
.c47:hover:not([aria-disabled='true']) {
border: 1px solid #4945ff;
}
.c47:hover:not([aria-disabled='true']) .c58 {
color: #271fe0;
}
.c47:hover:not([aria-disabled='true']) .c56 {
color: #4945ff;
}
.c47:hover:not([aria-disabled='true']) > .c48 {
background: #f0f0ff;
}
.c47:hover:not([aria-disabled='true']) [data-strapi-dropdown='true'] {
background: #d9d8ff;
}
.c47:hover:not([aria-disabled='true']) svg path {
fill: #4945ff;
}
.c54 {
background: transparent;
border: none;
position: relative;
outline: none;
}
.c54[aria-disabled='true'] {
pointer-events: none;
}
.c54[aria-disabled='true'] svg path {
fill: #666687;
}
.c54 svg {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
font-size: 0.625rem;
}
.c54 svg path {
fill: #4945ff;
}
.c54:after {
-webkit-transition-property: all;
transition-property: all;
-webkit-transition-duration: 0.2s;
transition-duration: 0.2s;
border-radius: 8px;
content: '';
position: absolute;
top: -4px;
bottom: -4px;
left: -4px;
right: -4px;
border: 2px solid transparent;
}
.c54:focus-visible {
outline: none;
}
.c54:focus-visible:after {
border-radius: 8px;
content: '';
position: absolute;
top: -5px;
bottom: -5px;
left: -5px;
right: -5px;
border: 2px solid #4945ff;
}
.c61 > * {
margin-left: 0;
margin-right: 0;
}
.c61 > * + * {
margin-left: 12px;
}
.c65 path {
fill: #666687;
}
.c55 {
text-align: left;
}
.c55 svg {
width: 0.875rem;
height: 0.875rem;
}
.c55 svg path {
fill: #8e8ea9;
}
.c51 {
height: 5.5rem;
}
@media (max-width:68.75rem) {
.c27 {
grid-column: span;
}
}
@media (max-width:34.375rem) {
.c27 {
grid-column: span;
}
}
@media (max-width:68.75rem) {
.c42 {
grid-column: span;
}
}
@media (max-width:34.375rem) {
.c42 {
grid-column: span;
}
}
@media (max-width:68.75rem) {
.c66 {
grid-column: span;
}
}
@media (max-width:34.375rem) {
.c66 {
grid-column: span;
}
}
<main
aria-labelledby="main-content-title"
class="c0"
id="main-content"
tabindex="-1"
>
<form
action="#"
novalidate=""
>
<div
style="height: 0px;"
>
<div
class="c1"
data-strapi-header="true"
>
<div
class="c2"
>
<a
aria-current="page"
class="c3 active"
href="/settings/users-permissions/roles"
>
<span
aria-hidden="true"
class="c4 c5"
>
<svg
fill="none"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M24 13.3a.2.2 0 01-.2.2H5.74l8.239 8.239a.2.2 0 010 .282L12.14 23.86a.2.2 0 01-.282 0L.14 12.14a.2.2 0 010-.282L11.86.14a.2.2 0 01.282 0L13.98 1.98a.2.2 0 010 .282L5.74 10.5H23.8c.11 0 .2.09.2.2v2.6z"
fill="#212134"
/>
</svg>
</span>
<span
class="c6 c7 c8"
>
Go back
</span>
</a>
</div>
<div
class="c9"
>
<div
class="c10"
>
<h1
class="c11"
id="main-content-title"
>
Authenticated
</h1>
</div>
<button
aria-disabled="false"
class="c12 c13"
type="submit"
>
<div
aria-hidden="true"
class="c14 c15 c16"
>
<svg
fill="none"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M20.727 2.97a.2.2 0 01.286 0l2.85 2.89a.2.2 0 010 .28L9.554 20.854a.2.2 0 01-.285 0l-9.13-9.243a.2.2 0 010-.281l2.85-2.892a.2.2 0 01.284 0l6.14 6.209L20.726 2.97z"
fill="#212134"
/>
</svg>
</div>
<span
class="c17 c18"
>
Save
</span>
</button>
</div>
<p
class="c19 c20"
>
Default role given to authenticated user.
</p>
</div>
</div>
<div
class="c21"
>
<div
class="c22"
>
<div
class="c23"
>
<div
class="c24"
>
<h2
class="c25"
>
Role details
</h2>
<div
class="c26"
>
<div
class="c27"
>
<div
class=""
>
<div>
<div>
<div
class="c28"
>
<div
class="c29"
>
<label
class="c30"
for="textinput-1"
>
Name
</label>
</div>
<div
class="c31 c32"
>
<input
aria-disabled="false"
aria-invalid="false"
class="c33"
id="textinput-1"
name="name"
value="Authenticated"
/>
</div>
</div>
</div>
</div>
</div>
</div>
<div
class="c27"
>
<div
class=""
>
<div
class="c34"
>
<div>
<div
class="c35"
>
<div
class="c36"
>
<label
class="c37"
for="textarea-1"
>
Description
</label>
</div>
<div
class="c38"
>
<textarea
aria-invalid="false"
class="c39"
id="textarea-1"
name="description"
>
Default role given to authenticated user.
</textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div
class="c40 c41"
>
<div
class="c42"
>
<div
class="c43"
>
<div
class="c24"
>
<div
class="c44"
>
<h2
class="c25"
>
Permissions
</h2>
<p
class="c45"
>
Only actions bound by a route are listed below.
</p>
</div>
<div
aria-disabled="false"
class="c46 c47"
data-strapi-expanded="false"
>
<div
class="c48 c49 c50 c51"
cursor=""
>
<button
aria-controls="accordion-content-accordion-1"
aria-disabled="false"
aria-expanded="false"
aria-labelledby="accordion-label-accordion-1"
class="c48 c52 c53 c54 c55"
data-strapi-accordion-toggle="true"
type="button"
>
<span
class="c56 c57"
>
<span
class="c58 c59"
id="accordion-label-accordion-1"
>
Address
</span>
<p
class="c56 c60"
id="accordion-desc-accordion-1"
>
Define all allowed actions for the api::address plugin.
</p>
</span>
</button>
<div
class="c48 c53 c61"
>
<span
aria-hidden="true"
class="c48 c62 c63"
cursor="pointer"
data-strapi-dropdown="true"
height="2rem"
width="2rem"
>
<svg
class="c64 c65"
fill="none"
height="1em"
viewBox="0 0 14 8"
width="0.6875rem"
xmlns="http://www.w3.org/2000/svg"
>
<path
clip-rule="evenodd"
d="M14 .889a.86.86 0 01-.26.625L7.615 7.736A.834.834 0 017 8a.834.834 0 01-.615-.264L.26 1.514A.861.861 0 010 .889c0-.24.087-.45.26-.625A.834.834 0 01.875 0h12.25c.237 0 .442.088.615.264a.86.86 0 01.26.625z"
fill="#32324D"
fill-rule="evenodd"
/>
</svg>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div
class="c66"
>
<div
class="c67"
style="min-height: 100%;"
>
<div
class="c44"
>
<h3
class="c25"
>
Advanced settings
</h3>
<p
class="c45"
>
Select the application's actions or the plugin's actions and click on the cog icon to display the bound route
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</main>
`);
});
it("can edit a users-permissions role's name and description", async () => {
const { getByLabelText, getByRole, getByTestId, getAllByText } = makeAndRenderApp();
// Check loading screen
const loader = getByTestId('loader');
expect(loader).toBeInTheDocument();
// After loading, check other elements
await waitForElementToBeRemoved(loader);
const saveButton = getByRole('button', { name: /save/i });
expect(saveButton).toBeInTheDocument();
const nameField = getByLabelText(/name/i);
expect(nameField).toBeInTheDocument();
const descriptionField = getByLabelText(/description/i);
expect(descriptionField).toBeInTheDocument();
// Shows error when name is missing
await userEvent.clear(nameField);
expect(nameField).toHaveValue('');
await userEvent.clear(descriptionField);
expect(descriptionField).toHaveValue('');
// Show errors after form submit
await userEvent.click(saveButton);
await waitFor(() => expect(saveButton).not.toBeDisabled());
const errorMessages = await getAllByText(/invalid value/i);
errorMessages.forEach(errorMessage => expect(errorMessage).toBeInTheDocument());
});
it('can toggle the permissions accordions and actions', async () => {
// Create app and wait for loading
const {
getByLabelText,
queryByText,
getByTestId,
getByText,
getAllByRole,
} = makeAndRenderApp();
const loader = getByTestId('loader');
await waitForElementToBeRemoved(loader);
// Open the collapse
const collapse = getByText(/define all allowed actions for the api::address plugin/i);
await userEvent.click(collapse);
expect(getByLabelText(/select all/i)).toBeInTheDocument();
// Display the selected action's bound route
const actionCogButton = getByTestId('action-cog');
await userEvent.click(actionCogButton);
expect(getByText(/bound route to/i)).toBeInTheDocument();
expect(getByText('POST')).toBeInTheDocument();
expect(getByText('/addresses')).toBeInTheDocument();
// Select all actions with the "select all" checkbox
const [selectAllCheckbox, ...actionCheckboxes] = getAllByRole('checkbox');
expect(selectAllCheckbox.checked).toBe(false);
await userEvent.click(selectAllCheckbox);
actionCheckboxes.forEach(actionCheckbox => {
expect(actionCheckbox.checked).toBe(true);
});
// Close the collapse
await userEvent.click(collapse);
expect(queryByText(/select all/i)).not.toBeInTheDocument();
});
});
| packages/plugins/users-permissions/admin/src/pages/Roles/EditPage/tests/index.test.js | 1 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.843632698059082,
0.012335884384810925,
0.00016367057105526328,
0.00017526530427858233,
0.09146826714277267
] |
{
"id": 5,
"code_window": [
" background: #d9d8ff;\n",
" }\n",
"\n",
" .c40:hover:not([aria-disabled='true']) svg path {\n",
" fill: #4945ff;\n",
" }\n",
"\n",
" .c47 {\n",
" background: transparent;\n",
" border: none;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/plugins/users-permissions/admin/src/pages/Roles/CreatePage/tests/index.test.js",
"type": "replace",
"edit_start_line_idx": 772
} | import axios from 'axios';
import { auth } from '@strapi/helper-plugin';
const instance = axios.create({
baseURL: process.env.STRAPI_ADMIN_BACKEND_URL,
});
instance.interceptors.request.use(
async config => {
config.headers = {
Authorization: `Bearer ${auth.getToken()}`,
Accept: 'application/json',
'Content-Type': 'application/json',
};
return config;
},
error => {
Promise.reject(error);
}
);
instance.interceptors.response.use(
response => response,
error => {
// whatever you want to do with the error
if (error?.response?.status === 401) {
auth.clearAppStorage();
window.location.reload();
}
throw error;
}
);
export default instance;
| packages/core/admin/admin/src/core/utils/axiosInstance.js | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.00017607331392355263,
0.00017231350648216903,
0.0001679399429121986,
0.00017262037727050483,
0.0000031537138056592084
] |
{
"id": 5,
"code_window": [
" background: #d9d8ff;\n",
" }\n",
"\n",
" .c40:hover:not([aria-disabled='true']) svg path {\n",
" fill: #4945ff;\n",
" }\n",
"\n",
" .c47 {\n",
" background: transparent;\n",
" border: none;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/plugins/users-permissions/admin/src/pages/Roles/CreatePage/tests/index.test.js",
"type": "replace",
"edit_start_line_idx": 772
} | import reducer from '../reducer';
describe('HELPER_PLUGIN | hooks | useRBAC | reducer', () => {
describe('DEFAULT_ACTION', () => {
it('should return the initialState', () => {
const initialState = {
ok: true,
};
expect(reducer(initialState, { type: '' })).toEqual(initialState);
});
});
describe('GET_DATA_SUCCEEDED', () => {
it('should set the data correctly', () => {
const initialState = {
isLoading: true,
allowedActions: {},
};
const action = {
type: 'GET_DATA_SUCCEEDED',
data: {
canRead: false,
},
};
const expected = {
allowedActions: {
canRead: false,
},
isLoading: false,
};
expect(reducer(initialState, action)).toEqual(expected);
});
});
});
| packages/core/helper-plugin/lib/src/hooks/useRBAC/tests/reducer.test.js | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.00017484734416939318,
0.00017374849994666874,
0.00017178647976834327,
0.0001741801097523421,
0.0000011809386251115939
] |
{
"id": 5,
"code_window": [
" background: #d9d8ff;\n",
" }\n",
"\n",
" .c40:hover:not([aria-disabled='true']) svg path {\n",
" fill: #4945ff;\n",
" }\n",
"\n",
" .c47 {\n",
" background: transparent;\n",
" border: none;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/plugins/users-permissions/admin/src/pages/Roles/CreatePage/tests/index.test.js",
"type": "replace",
"edit_start_line_idx": 772
} | const removeConditionKeyFromData = obj => {
if (!obj) {
return null;
}
return Object.keys(obj).reduce((acc, current) => {
if (current !== 'conditions') {
acc[current] = obj[current];
}
return acc;
}, {});
};
export default removeConditionKeyFromData;
| packages/core/admin/admin/src/pages/SettingsPage/pages/Roles/EditPage/components/utils/removeConditionKeyFromData.js | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.00017180154100060463,
0.00017043540719896555,
0.0001690692879492417,
0.00017043540719896555,
0.0000013661265256814659
] |
{
"id": 6,
"code_window": [
" .c44 {\n",
" height: 5.5rem;\n",
" }\n",
"\n",
" @media (max-width:68.75rem) {\n",
" .c20 {\n",
" grid-column: span;\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .c44:hover svg path {\n",
" fill: #4945ff;\n",
" }\n",
"\n"
],
"file_path": "packages/plugins/users-permissions/admin/src/pages/Roles/CreatePage/tests/index.test.js",
"type": "add",
"edit_start_line_idx": 863
} | import styled from 'styled-components';
import { Box } from '@strapi/design-system/Box';
import { IconButtonGroup, IconButton } from '@strapi/design-system/IconButton';
import { BaseButton } from '@strapi/design-system/BaseButton';
export const WysiwygWrapper = styled(Box)`
border: 1px solid
${({ theme, error }) => (error ? theme.colors.danger600 : theme.colors.neutral200)};
margin-top: ${({ theme }) => `${theme.spaces[2]}`};
`;
// NAV BUTTONS
export const CustomIconButton = styled(IconButton)`
padding: ${({ theme }) => theme.spaces[2]};
/* Trick to prevent the outline from overflowing because of the general outline-offset */
outline-offset: -2px !important;
svg {
width: ${18 / 16}rem;
height: ${18 / 16}rem;
}
`;
export const MainButtons = styled(IconButtonGroup)`
margin-left: ${({ theme }) => theme.spaces[4]};
`;
export const MoreButton = styled(IconButton)`
margin: ${({ theme }) => `0 ${theme.spaces[2]}`};
padding: ${({ theme }) => theme.spaces[2]};
svg {
width: ${18 / 16}rem;
height: ${18 / 16}rem;
}
`;
// NAV
export const IconButtonGroupMargin = styled(IconButtonGroup)`
margin-right: ${({ theme }) => `${theme.spaces[2]}`};
`;
// EDITOR && PREVIEW
export const EditorAndPreviewWrapper = styled.div`
position: relative;
`;
// FOOTER
export const ExpandButton = styled(BaseButton)`
background-color: transparent;
border: none;
align-items: center;
svg {
margin-left: ${({ theme }) => `${theme.spaces[2]}`};
path {
fill: ${({ theme }) => theme.colors.neutral700};
width: ${12 / 16}rem;
height: ${12 / 16}rem;
}
}
`;
// PREVIEW
const setOpacity = (hex, alpha) =>
`${hex}${Math.floor(alpha * 255)
.toString(16)
.padStart(2, 0)}`;
export const ExpandWrapper = styled.div`
position: absolute;
z-index: 4;
inset: 0;
background: ${({ theme }) => setOpacity(theme.colors.neutral800, 0.2)};
padding: 0 ${({ theme }) => theme.spaces[8]};
`;
export const ExpandContainer = styled(Box)`
display: flex;
max-width: ${1080 / 16}rem;
min-height: ${500 / 16}rem;
margin: 0 auto;
overflow: hidden;
margin-top: 10%;
border: ${({ theme }) => `1px solid ${theme.colors.neutral200}`};
`;
export const PreviewWrapper = styled(Box)`
width: 50%;
border-left: ${({ theme }) => `1px solid ${theme.colors.neutral200}`};
`;
export const WysiwygContainer = styled(Box)`
width: 50%;
`;
export const PreviewHeader = styled(Box)`
border-radius: 0 0 4px 4px;
border-top: 0;
`;
export const PreviewContainer = styled(Box)`
position: relative;
height: 100%;
`;
| packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygStyles.js | 1 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.00017950298206415027,
0.00017598643898963928,
0.00016658572712913156,
0.0001773611584212631,
0.000003835868028545519
] |
{
"id": 6,
"code_window": [
" .c44 {\n",
" height: 5.5rem;\n",
" }\n",
"\n",
" @media (max-width:68.75rem) {\n",
" .c20 {\n",
" grid-column: span;\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .c44:hover svg path {\n",
" fill: #4945ff;\n",
" }\n",
"\n"
],
"file_path": "packages/plugins/users-permissions/admin/src/pages/Roles/CreatePage/tests/index.test.js",
"type": "add",
"edit_start_line_idx": 863
} | 'use strict';
// Helpers.
const { createStrapiInstance } = require('../../../../test/helpers/strapi');
const { createContentAPIRequest } = require('../../../../test/helpers/request');
const { createTestBuilder } = require('../../../../test/helpers/builder');
const modelsUtils = require('../../../../test/helpers/models');
const form = require('../../../../test/helpers/generators');
const cleanDate = entry => {
delete entry.updatedAt;
delete entry.createdAt;
};
const builder = createTestBuilder();
let data;
let rq;
let strapi;
describe('Create Strapi API End to End', () => {
beforeAll(async () => {
await builder
.addContentTypes([form.article, form.tag, form.category, form.reference, form.product], {
batch: true,
})
.build();
strapi = await createStrapiInstance();
rq = await createContentAPIRequest({ strapi });
});
afterAll(async () => {
await strapi.destroy();
await builder.cleanup();
});
describe('Test manyToMany relation (article - tag) with Content Manager', () => {
beforeAll(async () => {
data = {
articles: [],
tags: [],
};
});
test('Create tag1', async () => {
const { body } = await rq({
url: '/tags',
method: 'POST',
body: {
data: {
name: 'tag1',
},
},
});
data.tags.push(body.data);
expect(body.data.id).toBeDefined();
expect(body.data.attributes.name).toBe('tag1');
});
test('Create tag2', async () => {
const { body } = await rq({
url: '/tags',
method: 'POST',
body: {
data: {
name: 'tag2',
},
},
});
data.tags.push(body.data);
expect(body.data.id).toBeDefined();
expect(body.data.attributes.name).toBe('tag2');
});
test('Create tag3', async () => {
const { body } = await rq({
url: '/tags',
method: 'POST',
body: {
data: {
name: 'tag3',
},
},
});
data.tags.push(body.data);
expect(body.data.id).toBeDefined();
expect(body.data.attributes.name).toBe('tag3');
});
test('Create article1 without relation', async () => {
const entry = {
title: 'Article 1',
content: 'My super content 1',
};
const { body } = await rq({
url: '/articles',
method: 'POST',
body: {
data: entry,
},
});
data.articles.push(body.data);
expect(body.data.id).toBeDefined();
expect(body.data.attributes.title).toBe(entry.title);
expect(body.data.attributes.content).toBe(entry.content);
});
test('Create article2 with tag1', async () => {
const entry = {
title: 'Article 2',
content: 'Content 2',
tags: [data.tags[0].id],
};
const { body } = await rq({
url: '/articles',
method: 'POST',
body: {
data: entry,
},
qs: {
populate: ['tags'],
},
});
data.articles.push(body.data);
expect(body.data.id).toBeDefined();
expect(body.data.attributes.title).toBe(entry.title);
expect(body.data.attributes.content).toBe(entry.content);
expect(Array.isArray(body.data.attributes.tags.data)).toBeTruthy();
expect(body.data.attributes.tags.data.length).toBe(1);
expect(body.data.attributes.tags.data[0].id).toBe(data.tags[0].id);
});
test('Update article1 add tag2', async () => {
const { id, attributes } = data.articles[0];
const entry = Object.assign({}, attributes, {
tags: [data.tags[1].id],
});
cleanDate(entry);
const { body } = await rq({
url: `/articles/${id}`,
method: 'PUT',
body: {
data: entry,
},
qs: {
populate: ['tags'],
},
});
data.articles[0] = body.data;
expect(body.data.id).toBeDefined();
expect(body.data.attributes.title).toBe(entry.title);
expect(body.data.attributes.content).toBe(entry.content);
expect(Array.isArray(body.data.attributes.tags.data)).toBeTruthy();
expect(body.data.attributes.tags.data.length).toBe(1);
expect(body.data.attributes.tags.data[0].id).toBe(data.tags[1].id);
});
test('Update article1 add tag1 and tag3', async () => {
const { id, attributes } = data.articles[0];
const entry = Object.assign({}, attributes);
entry.tags = data.tags.map(t => t.id);
cleanDate(entry);
const { body } = await rq({
url: `/articles/${id}`,
method: 'PUT',
body: {
data: entry,
},
qs: {
populate: ['tags'],
},
});
data.articles[0] = body.data;
expect(body.data.id).toBeDefined();
expect(body.data.attributes.title).toBe(entry.title);
expect(body.data.attributes.content).toBe(entry.content);
expect(Array.isArray(body.data.attributes.tags.data)).toBeTruthy();
expect(body.data.attributes.tags.data.length).toBe(3);
});
test('Update article1 remove one tag', async () => {
const { id, attributes } = data.articles[0];
const entry = Object.assign({}, attributes);
entry.tags = entry.tags.data.slice(1).map(t => t.id);
cleanDate(entry);
const { body } = await rq({
url: `/articles/${id}`,
method: 'PUT',
body: {
data: entry,
},
qs: {
populate: ['tags'],
},
});
data.articles[0] = body.data;
expect(body.data.id).toBeDefined();
expect(body.data.attributes.title).toBe(entry.title);
expect(body.data.attributes.content).toBe(entry.content);
expect(Array.isArray(body.data.attributes.tags.data)).toBeTruthy();
expect(body.data.attributes.tags.data.length).toBe(2);
});
test('Update article1 remove all tag', async () => {
const { id, attributes } = data.articles[0];
const entry = Object.assign({}, attributes, {
tags: [],
});
cleanDate(entry);
const { body } = await rq({
url: `/articles/${id}`,
method: 'PUT',
body: {
data: entry,
},
qs: {
populate: ['tags'],
},
});
data.articles[0] = body.data;
expect(body.data.id).toBeDefined();
expect(body.data.attributes.title).toBe(entry.title);
expect(body.data.attributes.content).toBe(entry.content);
expect(Array.isArray(body.data.attributes.tags.data)).toBeTruthy();
expect(body.data.attributes.tags.data.length).toBe(0);
});
});
describe('Test oneToMany - manyToOne relation (article - category) with Content Manager', () => {
beforeAll(() => {
data = {
articles: [],
categories: [],
};
});
afterAll(async () => {
await modelsUtils.cleanupModels([form.article.uid, form.category.uid], { strapi });
});
test('Create cat1', async () => {
const { body } = await rq({
url: '/categories',
method: 'POST',
body: {
data: {
name: 'cat1',
},
},
qs: {
populate: ['articles'],
},
});
data.categories.push(body.data);
expect(body.data.id).toBeDefined();
expect(body.data.attributes.name).toBe('cat1');
});
test('Create cat2', async () => {
const { body } = await rq({
url: '/categories',
method: 'POST',
body: {
data: {
name: 'cat2',
},
},
qs: {
populate: ['articles'],
},
});
data.categories.push(body.data);
expect(body.data.id).toBeDefined();
expect(body.data.attributes.name).toBe('cat2');
});
test('Create article1 with cat1', async () => {
const entry = {
title: 'Article 1',
content: 'Content 1',
category: data.categories[0].id,
};
const { body } = await rq({
url: '/articles',
method: 'POST',
body: {
data: entry,
},
qs: {
populate: ['category'],
},
});
data.articles.push(body.data);
expect(body.data.id).toBeDefined();
expect(body.data.attributes.title).toBe(entry.title);
expect(body.data.attributes.content).toBe(entry.content);
expect(body.data.attributes.category.data.attributes.name).toBe(
data.categories[0].attributes.name
);
});
test('Update article1 with cat2', async () => {
const { id, attributes } = data.articles[0];
const entry = Object.assign({}, attributes, {
category: data.categories[1].id,
});
cleanDate(entry);
const { body } = await rq({
url: `/articles/${id}`,
method: 'PUT',
body: {
data: entry,
},
qs: {
populate: ['category'],
},
});
data.articles[0] = body.data;
expect(body.data.id).toBeDefined();
expect(body.data.attributes.title).toBe(entry.title);
expect(body.data.attributes.content).toBe(entry.content);
expect(body.data.attributes.category.data.attributes.name).toBe(
data.categories[1].attributes.name
);
});
test('Create article2', async () => {
const entry = {
title: 'Article 2',
content: 'Content 2',
};
const { body } = await rq({
url: '/articles',
method: 'POST',
body: {
data: entry,
},
});
data.articles.push(body.data);
expect(body.data.id).toBeDefined();
expect(body.data.attributes.title).toBe(entry.title);
expect(body.data.attributes.content).toBe(entry.content);
});
test('Update article2 with cat2', async () => {
const { id, attributes } = data.articles[1];
const entry = Object.assign({}, attributes, {
category: data.categories[1].id,
});
cleanDate(entry);
const { body } = await rq({
url: `/articles/${id}`,
method: 'PUT',
body: {
data: entry,
},
qs: {
populate: ['category'],
},
});
data.articles[1] = body.data;
expect(body.data.id).toBeDefined();
expect(body.data.attributes.title).toBe(entry.title);
expect(body.data.attributes.content).toBe(entry.content);
expect(body.data.attributes.category.data.attributes.name).toBe(
data.categories[1].attributes.name
);
});
test('Update cat1 with article1', async () => {
const { id, attributes } = data.categories[0];
const entry = Object.assign({}, attributes);
entry.articles = data.categories[0].attributes.articles.data
.map(a => a.id)
.concat(data.articles[0].id);
cleanDate(entry);
const { body } = await rq({
url: `/categories/${id}`,
method: 'PUT',
body: {
data: entry,
},
qs: {
populate: ['articles'],
},
});
data.categories[0] = body.data;
expect(body.data.id).toBeDefined();
expect(Array.isArray(body.data.attributes.articles.data)).toBeTruthy();
expect(body.data.attributes.articles.data.length).toBe(1);
expect(body.data.attributes.name).toBe(entry.name);
});
test('Create cat3 with article1', async () => {
const entry = {
name: 'cat3',
articles: [data.articles[0].id],
};
const { body } = await rq({
url: '/categories',
method: 'POST',
body: {
data: entry,
},
qs: {
populate: ['articles'],
},
});
data.categories.push(body.data);
expect(body.data.id).toBeDefined();
expect(Array.isArray(body.data.attributes.articles.data)).toBeTruthy();
expect(body.data.attributes.articles.data.length).toBe(1);
expect(body.data.attributes.name).toBe(entry.name);
});
test('Get article1 with cat3', async () => {
const { body } = await rq({
url: `/articles/${data.articles[0].id}`,
method: 'GET',
qs: {
populate: ['category'],
},
});
expect(body.data.id).toBeDefined();
expect(body.data.attributes.category.data.id).toBe(data.categories[2].id);
});
test('Get article2 with cat2', async () => {
const { body } = await rq({
url: `/articles/${data.articles[1].id}`,
method: 'GET',
qs: {
populate: ['category'],
},
});
expect(body.data.id).toBeDefined();
expect(body.data.attributes.category.data.id).toBe(data.categories[1].id);
});
test('Get cat1 without relations', async () => {
const { body } = await rq({
url: `/categories/${data.categories[0].id}`,
method: 'GET',
qs: {
populate: ['articles'],
},
});
expect(body.data.id).toBeDefined();
expect(body.data.attributes.articles.data.length).toBe(0);
});
test('Get cat2 with article2', async () => {
const { body } = await rq({
url: `/categories/${data.categories[1].id}`,
method: 'GET',
qs: {
populate: ['articles'],
},
});
expect(body.data.id).toBeDefined();
expect(body.data.attributes.articles.data.length).toBe(1);
expect(body.data.attributes.articles.data[0].id).toBe(data.articles[1].id);
});
test('Get cat3 with article1', async () => {
const { body } = await rq({
url: `/categories/${data.categories[2].id}`,
method: 'GET',
qs: {
populate: ['articles'],
},
});
expect(body.data.id).toBeDefined();
expect(body.data.attributes.articles.data.length).toBe(1);
expect(body.data.attributes.articles.data[0].id).toBe(data.articles[0].id);
});
});
describe('Test oneToOne relation (article - reference) with Content Manager', () => {
beforeAll(() => {
data = {
articles: [],
references: [],
};
});
afterAll(async () => {
await modelsUtils.cleanupModels([form.article.uid, form.reference.uid], { strapi });
});
test('Create ref1', async () => {
const { body } = await rq({
url: '/references',
method: 'POST',
body: {
data: {
name: 'ref1',
},
},
});
data.references.push(body.data);
expect(body.data.id).toBeDefined();
expect(body.data.attributes.name).toBe('ref1');
});
test('Create article1', async () => {
const entry = {
title: 'Article 1',
content: 'Content 1',
};
const { body } = await rq({
url: '/articles',
method: 'POST',
body: {
data: entry,
},
});
data.articles.push(body.data);
expect(body.data.id).toBeDefined();
expect(body.data.attributes.title).toBe(entry.title);
expect(body.data.attributes.content).toBe(entry.content);
});
test('Update article1 with ref1', async () => {
const { id, attributes } = data.articles[0];
const entry = Object.assign({}, attributes, {
reference: data.references[0].id,
});
cleanDate(entry);
const { body } = await rq({
url: `/articles/${id}`,
method: 'PUT',
body: {
data: entry,
},
qs: {
populate: ['reference'],
},
});
data.articles[0] = body.data;
expect(body.data.id).toBeDefined();
expect(body.data.attributes.title).toBe(entry.title);
expect(body.data.attributes.content).toBe(entry.content);
expect(body.data.attributes.reference.data.id).toBe(entry.reference);
});
test('Create article2 with ref1', async () => {
const entry = {
title: 'Article 2',
content: 'Content 2',
reference: data.references[0].id,
};
const { body } = await rq({
url: '/articles',
method: 'POST',
body: {
data: entry,
},
qs: {
populate: ['reference'],
},
});
data.articles.push(body.data);
expect(body.data.id).toBeDefined();
expect(body.data.attributes.title).toBe(entry.title);
expect(body.data.attributes.content).toBe(entry.content);
expect(body.data.attributes.reference.data.id).toBe(entry.reference);
});
});
describe('Test oneWay relation (reference - tag) with Content Manager', () => {
beforeAll(() => {
data = {
tags: [],
references: [],
};
});
afterAll(async () => {
await modelsUtils.cleanupModels([form.reference.uid, form.tag.uid], { strapi });
});
test('Attach Tag to a Reference', async () => {
const {
body: { data: createdTag },
} = await rq({
url: '/tags',
method: 'POST',
body: {
data: {
name: 'tag111',
},
},
});
data.tags.push(createdTag);
const {
body: { data: createdReference },
} = await rq({
url: '/references',
method: 'POST',
body: {
data: {
name: 'cat111',
tag: createdTag.id,
},
},
qs: {
populate: ['tag'],
},
});
data.references.push(createdReference);
expect(createdReference.attributes.tag.data.id).toBe(createdTag.id);
});
test('Detach Tag from a Reference', async () => {
const {
body: { data: createdTag },
} = await rq({
url: '/tags',
method: 'POST',
body: {
data: {
name: 'tag111',
},
},
});
data.tags.push(createdTag);
const {
body: { data: createdReference },
} = await rq({
url: '/references',
method: 'POST',
body: {
data: {
name: 'cat111',
tag: createdTag.id,
},
},
qs: {
populate: ['tag'],
},
});
data.references.push(createdReference);
expect(createdReference.attributes.tag.data.id).toBe(createdTag.id);
const {
body: { data: updatedReference },
} = await rq({
url: `/references/${createdReference.id}`,
method: 'PUT',
body: {
data: {
tag: null,
},
},
qs: {
populate: ['tag'],
},
});
expect(updatedReference.attributes.tag.data).toBe(null);
});
test('Delete Tag so the relation in the Reference side should be removed', async () => {
const {
body: { data: createdTag },
} = await rq({
url: '/tags',
method: 'POST',
body: {
data: {
name: 'tag111',
},
},
});
data.tags.push(createdTag);
const {
body: { data: createdReference },
} = await rq({
url: '/references',
method: 'POST',
body: {
data: {
name: 'cat111',
tag: createdTag.id,
},
},
qs: {
populate: ['tag'],
},
});
data.references.push(createdReference);
await rq({
url: `/tags/${createdTag.id}`,
method: 'DELETE',
});
const {
body: { data: foundReference },
} = await rq({
url: `/references/${createdReference.id}`,
method: 'GET',
qs: {
populate: ['tag'],
},
});
expect(foundReference.attributes.tag.data).toBe(null);
});
});
});
| packages/core/strapi/tests/endpoint.test.e2e.js | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.00017912700423039496,
0.00017426404519937932,
0.00016597310604993254,
0.00017473366460762918,
0.0000027864950880029937
] |
{
"id": 6,
"code_window": [
" .c44 {\n",
" height: 5.5rem;\n",
" }\n",
"\n",
" @media (max-width:68.75rem) {\n",
" .c20 {\n",
" grid-column: span;\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .c44:hover svg path {\n",
" fill: #4945ff;\n",
" }\n",
"\n"
],
"file_path": "packages/plugins/users-permissions/admin/src/pages/Roles/CreatePage/tests/index.test.js",
"type": "add",
"edit_start_line_idx": 863
} | # @strapi/generators
This package contains strapi code generators available through the CLI or programmatically.
## API Reference
### `runCLI()`
Start the generator CLI.
### `generate(generatorName, options, plopOptions)`
Execute a generator without interactive mode.
- `generatorName` - one of `api`, `controller`, `service`, `model`, `plugin`, `policy`.
- `options` - options are specific to each generator
- `plopOtions`
- `dir`: base directory that plop will use as base directory for its actions
| packages/generators/generators/README.md | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.00017434722394682467,
0.00016957886691670865,
0.00016481050988659263,
0.00016957886691670865,
0.000004768357030116022
] |
{
"id": 6,
"code_window": [
" .c44 {\n",
" height: 5.5rem;\n",
" }\n",
"\n",
" @media (max-width:68.75rem) {\n",
" .c20 {\n",
" grid-column: span;\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .c44:hover svg path {\n",
" fill: #4945ff;\n",
" }\n",
"\n"
],
"file_path": "packages/plugins/users-permissions/admin/src/pages/Roles/CreatePage/tests/index.test.js",
"type": "add",
"edit_start_line_idx": 863
} | export const GET_DATA = 'ContentManager/App/GET_DATA';
export const RESET_PROPS = 'ContentManager/App/RESET_PROPS';
export const SET_CONTENT_TYPE_LINKS = 'ContentManager/App/SET_CONTENT_TYPE_LINKS';
| packages/core/admin/admin/src/content-manager/pages/App/constants.js | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.00018416752573102713,
0.00018416752573102713,
0.00018416752573102713,
0.00018416752573102713,
0
] |
{
"id": 7,
"code_window": [
" background: #d9d8ff;\n",
" }\n",
"\n",
" .c47:hover:not([aria-disabled='true']) svg path {\n",
" fill: #4945ff;\n",
" }\n",
"\n",
" .c54 {\n",
" background: transparent;\n",
" border: none;\n",
" position: relative;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/plugins/users-permissions/admin/src/pages/Roles/EditPage/tests/index.test.js",
"type": "replace",
"edit_start_line_idx": 855
} | import styled from 'styled-components';
import { Box } from '@strapi/design-system/Box';
import { IconButtonGroup, IconButton } from '@strapi/design-system/IconButton';
import { BaseButton } from '@strapi/design-system/BaseButton';
export const WysiwygWrapper = styled(Box)`
border: 1px solid
${({ theme, error }) => (error ? theme.colors.danger600 : theme.colors.neutral200)};
margin-top: ${({ theme }) => `${theme.spaces[2]}`};
`;
// NAV BUTTONS
export const CustomIconButton = styled(IconButton)`
padding: ${({ theme }) => theme.spaces[2]};
/* Trick to prevent the outline from overflowing because of the general outline-offset */
outline-offset: -2px !important;
svg {
width: ${18 / 16}rem;
height: ${18 / 16}rem;
}
`;
export const MainButtons = styled(IconButtonGroup)`
margin-left: ${({ theme }) => theme.spaces[4]};
`;
export const MoreButton = styled(IconButton)`
margin: ${({ theme }) => `0 ${theme.spaces[2]}`};
padding: ${({ theme }) => theme.spaces[2]};
svg {
width: ${18 / 16}rem;
height: ${18 / 16}rem;
}
`;
// NAV
export const IconButtonGroupMargin = styled(IconButtonGroup)`
margin-right: ${({ theme }) => `${theme.spaces[2]}`};
`;
// EDITOR && PREVIEW
export const EditorAndPreviewWrapper = styled.div`
position: relative;
`;
// FOOTER
export const ExpandButton = styled(BaseButton)`
background-color: transparent;
border: none;
align-items: center;
svg {
margin-left: ${({ theme }) => `${theme.spaces[2]}`};
path {
fill: ${({ theme }) => theme.colors.neutral700};
width: ${12 / 16}rem;
height: ${12 / 16}rem;
}
}
`;
// PREVIEW
const setOpacity = (hex, alpha) =>
`${hex}${Math.floor(alpha * 255)
.toString(16)
.padStart(2, 0)}`;
export const ExpandWrapper = styled.div`
position: absolute;
z-index: 4;
inset: 0;
background: ${({ theme }) => setOpacity(theme.colors.neutral800, 0.2)};
padding: 0 ${({ theme }) => theme.spaces[8]};
`;
export const ExpandContainer = styled(Box)`
display: flex;
max-width: ${1080 / 16}rem;
min-height: ${500 / 16}rem;
margin: 0 auto;
overflow: hidden;
margin-top: 10%;
border: ${({ theme }) => `1px solid ${theme.colors.neutral200}`};
`;
export const PreviewWrapper = styled(Box)`
width: 50%;
border-left: ${({ theme }) => `1px solid ${theme.colors.neutral200}`};
`;
export const WysiwygContainer = styled(Box)`
width: 50%;
`;
export const PreviewHeader = styled(Box)`
border-radius: 0 0 4px 4px;
border-top: 0;
`;
export const PreviewContainer = styled(Box)`
position: relative;
height: 100%;
`;
| packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygStyles.js | 1 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.009372260421514511,
0.0014088883763179183,
0.0001715545222396031,
0.00025993402232415974,
0.002619291190057993
] |
{
"id": 7,
"code_window": [
" background: #d9d8ff;\n",
" }\n",
"\n",
" .c47:hover:not([aria-disabled='true']) svg path {\n",
" fill: #4945ff;\n",
" }\n",
"\n",
" .c54 {\n",
" background: transparent;\n",
" border: none;\n",
" position: relative;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/plugins/users-permissions/admin/src/pages/Roles/EditPage/tests/index.test.js",
"type": "replace",
"edit_start_line_idx": 855
} | 'use strict';
const pluralize = require('pluralize');
const generateApi = require('./plops/api');
const generateController = require('./plops/controller');
const generateContentType = require('./plops/content-type');
const generatePlugin = require('./plops/plugin');
const generatePolicy = require('./plops/policy');
const generateMiddleware = require('./plops/middleware');
const generateService = require('./plops/service');
module.exports = plop => {
// Plop config
plop.setWelcomeMessage('Strapi Generators');
plop.addHelper('pluralize', text => pluralize(text));
// Generators
generateApi(plop);
generateController(plop);
generateContentType(plop);
generatePlugin(plop);
generatePolicy(plop);
generateMiddleware(plop);
generateService(plop);
};
| packages/generators/generators/lib/plopfile.js | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.00017655799456406385,
0.0001762731553753838,
0.00017571709759067744,
0.0001765443739714101,
3.9323154510384484e-7
] |
{
"id": 7,
"code_window": [
" background: #d9d8ff;\n",
" }\n",
"\n",
" .c47:hover:not([aria-disabled='true']) svg path {\n",
" fill: #4945ff;\n",
" }\n",
"\n",
" .c54 {\n",
" background: transparent;\n",
" border: none;\n",
" position: relative;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/plugins/users-permissions/admin/src/pages/Roles/EditPage/tests/index.test.js",
"type": "replace",
"edit_start_line_idx": 855
} | /*
*
*
* BackHeader
*
*/
import React from 'react';
import { get } from 'lodash';
import { useRouteMatch } from 'react-router-dom';
import PropTypes from 'prop-types';
import useTracking from '../../../hooks/useTracking';
import StyledBackHeader from './StyledBackHeader';
const BackHeader = props => {
const { trackUsage } = useTracking();
const pluginsParams = useRouteMatch('/plugins/:pluginId');
const settingsParams = useRouteMatch('/settings/:settingType');
const pluginId = get(pluginsParams, ['params', 'pluginId'], null);
const settingType = get(settingsParams, ['params', 'settingType'], null);
const location = pluginId || settingType;
const handleClick = e => {
if (location) {
trackUsage('didGoBack', { location });
}
props.onClick(e);
};
return <StyledBackHeader {...props} onClick={handleClick} />;
};
BackHeader.defaultProps = {
onClick: () => {},
};
BackHeader.propTypes = {
onClick: PropTypes.func,
};
export default BackHeader;
| packages/core/helper-plugin/lib/src/old/components/BackHeader/index.js | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.0007697127875871956,
0.00029316172003746033,
0.0001705229951767251,
0.00017492420738562942,
0.0002382826351094991
] |
{
"id": 7,
"code_window": [
" background: #d9d8ff;\n",
" }\n",
"\n",
" .c47:hover:not([aria-disabled='true']) svg path {\n",
" fill: #4945ff;\n",
" }\n",
"\n",
" .c54 {\n",
" background: transparent;\n",
" border: none;\n",
" position: relative;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/plugins/users-permissions/admin/src/pages/Roles/EditPage/tests/index.test.js",
"type": "replace",
"edit_start_line_idx": 855
} | 'use strict';
const { getNonLocalizedAttributes } = require('../content-types');
const ctService = require('../../services/content-types')();
describe('i18n - Controller - content-types', () => {
describe('getNonLocalizedAttributes', () => {
beforeEach(() => {
const getModel = () => {};
global.strapi = {
getModel,
plugins: { i18n: { services: { 'content-types': ctService } } },
admin: { services: { constants: { READ_ACTION: 'read', CREATE_ACTION: 'create' } } },
};
});
test('model not localized', async () => {
const badRequest = jest.fn();
const ctx = {
state: { user: {} },
request: {
body: {
model: 'api::country.country',
id: 1,
locale: 'fr',
},
},
badRequest,
};
await getNonLocalizedAttributes(ctx);
expect(badRequest).toHaveBeenCalledWith('model.not.localized');
});
test('entity not found', async () => {
const notFound = jest.fn();
const findOne = jest.fn(() => Promise.resolve(undefined));
const getModel = jest.fn(() => ({ pluginOptions: { i18n: { localized: true } } }));
global.strapi.query = () => ({ findOne });
global.strapi.getModel = getModel;
const ctx = {
state: { user: {} },
request: {
body: {
model: 'api::country.country',
id: 1,
locale: 'fr',
},
},
notFound,
};
await getNonLocalizedAttributes(ctx);
expect(notFound).toHaveBeenCalledWith();
});
test('returns nonLocalizedFields', async () => {
const model = {
pluginOptions: { i18n: { localized: true } },
attributes: {
name: { type: 'string' },
averagePrice: { type: 'integer' },
description: { type: 'string', pluginOptions: { i18n: { localized: true } } },
},
};
const entity = {
id: 1,
name: "Papailhau's Pizza",
description: 'Best pizza restaurant of the town',
locale: 'en',
publishedAt: '2021-03-30T09:34:54.042Z',
localizations: [{ id: 2, locale: 'it', publishedAt: null }],
};
const permissions = [
{ properties: { fields: ['name', 'averagePrice'], locales: ['it'] } },
{ properties: { fields: ['name', 'description'], locales: ['fr'] } },
{ properties: { fields: ['name'], locales: ['fr'] } },
];
const findOne = jest.fn(() => Promise.resolve(entity));
const findMany = jest.fn(() => Promise.resolve(permissions));
const getModel = jest.fn(() => model);
global.strapi.query = () => ({ findOne });
global.strapi.getModel = getModel;
global.strapi.admin.services.permission = { findMany };
const ctx = {
state: { user: { roles: [{ id: 1 }, { id: 2 }] } },
request: {
body: {
model: 'api::country.country',
id: 1,
locale: 'fr',
},
},
};
await getNonLocalizedAttributes(ctx);
expect(findMany).toHaveBeenCalledWith({
where: {
action: ['read', 'create'],
subject: 'api::country.country',
role: {
id: [1, 2],
},
},
});
expect(ctx.body).toEqual({
nonLocalizedFields: { name: "Papailhau's Pizza" },
localizations: [
{ id: 2, locale: 'it', publishedAt: null },
{ id: 1, locale: 'en', publishedAt: '2021-03-30T09:34:54.042Z' },
],
});
});
});
});
| packages/plugins/i18n/server/controllers/__tests__/content-types.test.js | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.000179103430127725,
0.00017327792011201382,
0.00016758737911004573,
0.00017367152031511068,
0.0000026767131657834398
] |
{
"id": 8,
"code_window": [
" height: 5.5rem;\n",
" }\n",
"\n",
" @media (max-width:68.75rem) {\n",
" .c27 {\n",
" grid-column: span;\n",
" }\n",
" }\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .c51:hover svg path {\n",
" fill: #4945ff;\n",
" }\n",
"\n"
],
"file_path": "packages/plugins/users-permissions/admin/src/pages/Roles/EditPage/tests/index.test.js",
"type": "add",
"edit_start_line_idx": 946
} | import styled from 'styled-components';
import { Box } from '@strapi/design-system/Box';
import { IconButtonGroup, IconButton } from '@strapi/design-system/IconButton';
import { BaseButton } from '@strapi/design-system/BaseButton';
export const WysiwygWrapper = styled(Box)`
border: 1px solid
${({ theme, error }) => (error ? theme.colors.danger600 : theme.colors.neutral200)};
margin-top: ${({ theme }) => `${theme.spaces[2]}`};
`;
// NAV BUTTONS
export const CustomIconButton = styled(IconButton)`
padding: ${({ theme }) => theme.spaces[2]};
/* Trick to prevent the outline from overflowing because of the general outline-offset */
outline-offset: -2px !important;
svg {
width: ${18 / 16}rem;
height: ${18 / 16}rem;
}
`;
export const MainButtons = styled(IconButtonGroup)`
margin-left: ${({ theme }) => theme.spaces[4]};
`;
export const MoreButton = styled(IconButton)`
margin: ${({ theme }) => `0 ${theme.spaces[2]}`};
padding: ${({ theme }) => theme.spaces[2]};
svg {
width: ${18 / 16}rem;
height: ${18 / 16}rem;
}
`;
// NAV
export const IconButtonGroupMargin = styled(IconButtonGroup)`
margin-right: ${({ theme }) => `${theme.spaces[2]}`};
`;
// EDITOR && PREVIEW
export const EditorAndPreviewWrapper = styled.div`
position: relative;
`;
// FOOTER
export const ExpandButton = styled(BaseButton)`
background-color: transparent;
border: none;
align-items: center;
svg {
margin-left: ${({ theme }) => `${theme.spaces[2]}`};
path {
fill: ${({ theme }) => theme.colors.neutral700};
width: ${12 / 16}rem;
height: ${12 / 16}rem;
}
}
`;
// PREVIEW
const setOpacity = (hex, alpha) =>
`${hex}${Math.floor(alpha * 255)
.toString(16)
.padStart(2, 0)}`;
export const ExpandWrapper = styled.div`
position: absolute;
z-index: 4;
inset: 0;
background: ${({ theme }) => setOpacity(theme.colors.neutral800, 0.2)};
padding: 0 ${({ theme }) => theme.spaces[8]};
`;
export const ExpandContainer = styled(Box)`
display: flex;
max-width: ${1080 / 16}rem;
min-height: ${500 / 16}rem;
margin: 0 auto;
overflow: hidden;
margin-top: 10%;
border: ${({ theme }) => `1px solid ${theme.colors.neutral200}`};
`;
export const PreviewWrapper = styled(Box)`
width: 50%;
border-left: ${({ theme }) => `1px solid ${theme.colors.neutral200}`};
`;
export const WysiwygContainer = styled(Box)`
width: 50%;
`;
export const PreviewHeader = styled(Box)`
border-radius: 0 0 4px 4px;
border-top: 0;
`;
export const PreviewContainer = styled(Box)`
position: relative;
height: 100%;
`;
| packages/core/admin/admin/src/content-manager/components/Wysiwyg/WysiwygStyles.js | 1 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.00017768176621757448,
0.00017365971871186048,
0.00016618988593108952,
0.0001752631360432133,
0.0000037858853829675354
] |
{
"id": 8,
"code_window": [
" height: 5.5rem;\n",
" }\n",
"\n",
" @media (max-width:68.75rem) {\n",
" .c27 {\n",
" grid-column: span;\n",
" }\n",
" }\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .c51:hover svg path {\n",
" fill: #4945ff;\n",
" }\n",
"\n"
],
"file_path": "packages/plugins/users-permissions/admin/src/pages/Roles/EditPage/tests/index.test.js",
"type": "add",
"edit_start_line_idx": 946
} | const displayedFilters = [
{
name: 'firstname',
metadatas: { label: 'Firstname' },
fieldSchema: { type: 'string' },
},
{
name: 'lastname',
metadatas: { label: 'Lastname' },
fieldSchema: { type: 'string' },
},
{
name: 'email',
metadatas: { label: 'Email' },
fieldSchema: { type: 'email' },
},
{
name: 'username',
metadatas: { label: 'Username' },
fieldSchema: { type: 'string' },
},
{
name: 'isActive',
metadatas: { label: 'Active user' },
fieldSchema: { type: 'boolean' },
},
];
export default displayedFilters;
| packages/core/admin/admin/src/pages/SettingsPage/pages/Users/ListPage/utils/displayedFilters.js | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.00017855728219728917,
0.000173625725437887,
0.00016707951726857573,
0.00017524039139971137,
0.000004822870323550887
] |
{
"id": 8,
"code_window": [
" height: 5.5rem;\n",
" }\n",
"\n",
" @media (max-width:68.75rem) {\n",
" .c27 {\n",
" grid-column: span;\n",
" }\n",
" }\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .c51:hover svg path {\n",
" fill: #4945ff;\n",
" }\n",
"\n"
],
"file_path": "packages/plugins/users-permissions/admin/src/pages/Roles/EditPage/tests/index.test.js",
"type": "add",
"edit_start_line_idx": 946
} | module.exports = [
'strapi::errors',
'strapi::security',
'strapi::cors',
'strapi::poweredBy',
'strapi::logger',
'strapi::query',
'strapi::body',
'strapi::favicon',
'strapi::public',
];
| packages/generators/app/lib/resources/files/config/middlewares.js | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.00018101376190315932,
0.0001771776587702334,
0.00017334154108539224,
0.0001771776587702334,
0.000003836110408883542
] |
{
"id": 8,
"code_window": [
" height: 5.5rem;\n",
" }\n",
"\n",
" @media (max-width:68.75rem) {\n",
" .c27 {\n",
" grid-column: span;\n",
" }\n",
" }\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .c51:hover svg path {\n",
" fill: #4945ff;\n",
" }\n",
"\n"
],
"file_path": "packages/plugins/users-permissions/admin/src/pages/Roles/EditPage/tests/index.test.js",
"type": "add",
"edit_start_line_idx": 946
} | 'use strict';
const sendmailFactory = require('sendmail');
const { removeUndefined } = require('@strapi/utils');
module.exports = {
init(providerOptions = {}, settings = {}) {
const sendmail = sendmailFactory({
silent: true,
...providerOptions,
});
return {
send(options) {
return new Promise((resolve, reject) => {
const { from, to, cc, bcc, replyTo, subject, text, html, ...rest } = options;
let msg = {
from: from || settings.defaultFrom,
to,
cc,
bcc,
replyTo: replyTo || settings.defaultReplyTo,
subject,
text,
html,
...rest,
};
sendmail(removeUndefined(msg), err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
},
};
},
};
| packages/providers/email-sendmail/lib/index.js | 0 | https://github.com/strapi/strapi/commit/a10953ffb95e8a644143d7769520107dcad73fbd | [
0.0001808722736313939,
0.0001746027119224891,
0.00017032181494869292,
0.00017256004502996802,
0.000003792818233705475
] |
{
"id": 0,
"code_window": [
"name: primary tests\n",
"\n",
"on:\n",
" push:\n"
],
"labels": [
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"name: \"tests 1\"\n"
],
"file_path": ".github/workflows/tests_primary.yml",
"type": "replace",
"edit_start_line_idx": 0
} | name: secondary tests
on:
push:
branches:
- master
- release-*
pull_request:
types: [ labeled ]
branches:
- master
- release-*
env:
# Force terminal colors. @see https://www.npmjs.com/package/colors
FORCE_COLOR: 1
FLAKINESS_CONNECTION_STRING: ${{ secrets.FLAKINESS_CONNECTION_STRING }}
jobs:
test_linux:
name: ${{ matrix.os }} (${{ matrix.browser }})
strategy:
fail-fast: false
matrix:
browser: [chromium, firefox, webkit]
os: [ubuntu-18.04]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
- run: npm run build
- run: node lib/cli/cli install-deps ${{ matrix.browser }} chromium
# XVFB-RUN merges both STDOUT and STDERR, whereas we need only STDERR
# Wrap `npm run` in a subshell to redirect STDERR to file.
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash -c "npm run test -- --project=${{ matrix.browser }}"
- run: node tests/config/checkCoverage.js ${{ matrix.browser }}
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: always()
with:
name: ${{ matrix.browser }}-${{ matrix.os }}-test-results
path: test-results
test_mac:
name: ${{ matrix.os }} (${{ matrix.browser }})
strategy:
fail-fast: false
matrix:
os: [macos-10.15, macos-11.0]
browser: [chromium, firefox, webkit]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
DEBUG: extract-zip
- run: npm run build
- run: node lib/cli/cli install-deps ${{ matrix.browser }} chromium
- run: npm run test -- --project=${{ matrix.browser }}
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: ${{ matrix.browser }}-${{ matrix.os }}-test-results
path: test-results
test_win:
name: "Windows"
strategy:
fail-fast: false
matrix:
browser: [chromium, firefox, webkit]
runs-on: windows-latest
steps:
- name: Install Media Pack
shell: powershell
run: Install-WindowsFeature Server-Media-Foundation
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
DEBUG: extract-zip
- run: npm run build
- run: node lib/cli/cli install-deps
- run: npm run test -- --project=${{ matrix.browser }}
shell: bash
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
shell: bash
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: ${{ matrix.browser }}-win-test-results
path: test-results
test-package-installations:
runs-on: ubuntu-20.04
strategy:
fail-fast: false
matrix:
node_version:
- "^12.0.0"
- "^14.1.0" # pre 14.1, zip extraction was broken (https://github.com/microsoft/playwright/issues/1988)
timeout-minutes: 20
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node_version }}
- run: npm ci
env:
DEBUG: extract-zip
- run: npm run build
- run: node lib/cli/cli install-deps
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash packages/installation-tests/installation-tests.sh
headful_linux:
name: "Headful Linux"
strategy:
fail-fast: false
matrix:
browser: [chromium, firefox, webkit]
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
- run: npm run build
- run: node lib/cli/cli install-deps ${{ matrix.browser }} chromium
# XVFB-RUN merges both STDOUT and STDERR, whereas we need only STDERR
# Wrap `npm run` in a subshell to redirect STDERR to file.
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash -c "npm run test -- --project=${{ matrix.browser }} --headed"
if: ${{ always() }}
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: headful-${{ matrix.browser }}-linux-test-results
path: test-results
transport_linux:
name: "Transport"
strategy:
fail-fast: false
matrix:
mode: [driver, service]
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
- run: npm run build
- run: node lib/cli/cli install-deps chromium
# XVFB-RUN merges both STDOUT and STDERR, whereas we need only STDERR
# Wrap `npm run` in a subshell to redirect STDERR to file.
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash -c "npm run ctest -- --mode=${{ matrix.mode }}"
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: mode-${{ matrix.mode }}-linux-test-results
path: test-results
video_linux:
name: "Video Linux"
strategy:
fail-fast: false
matrix:
browser: [chromium, firefox, webkit]
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
- run: npm run build
- run: node lib/cli/cli install-deps ${{ matrix.browser }} chromium
# XVFB-RUN merges both STDOUT and STDERR, whereas we need only STDERR
# Wrap `npm run` in a subshell to redirect STDERR to file.
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash -c "npm run test -- --project=${{ matrix.browser }} --video"
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: video-${{ matrix.browser }}-linux-test-results
path: test-results
test_android:
name: Android Emulator (shard ${{ matrix.shard }})
strategy:
fail-fast: false
matrix:
shard: [1, 2]
runs-on: macos-10.15
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 14
- run: npm ci
- run: npm run build
- run: node lib/cli/cli install-deps
- name: Create Android Emulator
run: utils/avd_recreate.sh
- name: Start Android Emulator
run: utils/avd_start.sh
- name: Run tests
run: npm run atest -- --shard=${{ matrix.shard }}/2
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: android-test-results
path: test-results
chrome_stable_linux:
name: "Chrome Stable (Linux)"
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- name: Install Chrome Stable
run: sudo apt install google-chrome-stable
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
- run: node lib/cli/cli install-deps chromium
# This only created problems, should we move ffmpeg back into npm?
- run: node lib/cli/cli install ffmpeg
# XVFB-RUN merges both STDOUT and STDERR, whereas we need only STDERR
# Wrap `npm run` in a subshell to redirect STDERR to file.
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash -c "npm run ctest -- --channel=chrome"
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: chrome-stable-linux-test-results
path: test-results
chrome_stable_win:
name: "Chrome Stable (Win)"
runs-on: windows-latest
steps:
- name: Install Media Pack
shell: powershell
run: Install-WindowsFeature Server-Media-Foundation
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
# This only created problems, should we move ffmpeg back into npm?
- run: node lib/cli/cli install ffmpeg
- run: npm run ctest -- --channel=chrome
shell: bash
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
shell: bash
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: chrome-stable-win-test-results
path: test-results
chrome_stable_mac:
name: "Chrome Stable (Mac)"
runs-on: macos-10.15
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
# This only created problems, should we move ffmpeg back into npm?
- run: node lib/cli/cli install ffmpeg
- run: npm run ctest -- --channel=chrome
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: chrome-stable-mac-test-results
path: test-results
firefox_stable_linux:
name: "Firefox Stable (Linux)"
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
- run: node lib/cli/cli install-deps firefox
- run: node lib/cli/cli install ffmpeg firefox-stable chromium
# XVFB-RUN merges both STDOUT and STDERR, whereas we need only STDERR
# Wrap `npm run` in a subshell to redirect STDERR to file.
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash -c "npm run ftest -- --channel=firefox-stable"
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: firefox-stable-linux-test-results
path: test-results
firefox_stable_win:
name: "Firefox Stable (Win)"
runs-on: windows-latest
steps:
- name: Install Media Pack
shell: powershell
run: Install-WindowsFeature Server-Media-Foundation
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
- run: node lib/cli/cli install ffmpeg firefox-stable chromium
- run: npm run ftest -- --channel=firefox-stable
shell: bash
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
shell: bash
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: firefox-stable-win-test-results
path: test-results
firefox_stable_mac:
name: "Firefox Stable (Mac)"
runs-on: macos-10.15
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
- run: node lib/cli/cli install ffmpeg firefox-stable chromium
- run: npm run ftest -- --channel=firefox-stable
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: firefox-stable-mac-test-results
path: test-results
edge_stable_win:
name: "Edge Stable (Win)"
runs-on: windows-latest
steps:
- name: Install Media Pack
shell: powershell
run: Install-WindowsFeature Server-Media-Foundation
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
# This only created problems, should we move ffmpeg back into npm?
- run: node lib/cli/cli install ffmpeg
- run: npm run ctest -- --channel=msedge
shell: bash
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: edge-stable-win-test-results
path: test-results
test_electron:
name: "Electron Linux"
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
- run: npm run build
- run: node lib/cli/cli install-deps chromium
# XVFB-RUN merges both STDOUT and STDERR, whereas we need only STDERR
# Wrap `npm run` in a subshell to redirect STDERR to file.
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash -c "npm run etest"
- run: node tests/config/checkCoverage.js electron
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: electron-linux-test-results
path: test-results
chrome_beta_linux:
name: "Chrome Beta (Linux)"
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- run: ./utils/install-chrome-beta/reinstall_linux.sh
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
- run: node lib/cli/cli install-deps chromium
- run: node lib/cli/cli install ffmpeg
# XVFB-RUN merges both STDOUT and STDERR, whereas we need only STDERR
# Wrap `npm run` in a subshell to redirect STDERR to file.
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash -c "npm run ctest -- --channel=chrome-beta"
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: chrome-beta-linux-test-results
path: test-results
chrome_beta_win:
name: "Chrome Beta (Win)"
runs-on: windows-latest
steps:
- name: Install Media Pack
shell: powershell
run: Install-WindowsFeature Server-Media-Foundation
- name: Install Chrome Beta
shell: powershell
run: choco install -y googlechromebeta --pre --force
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
- run: node lib/cli/cli install ffmpeg
- run: npm run ctest -- --channel=chrome-beta
shell: bash
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
shell: bash
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: chrome-beta-win-test-results
path: test-results
chrome_beta_mac:
name: "Chrome Beta (Mac)"
runs-on: macos-10.15
steps:
- uses: actions/checkout@v2
- run: ./utils/install-chrome-beta/reinstall_mac.sh
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
- run: node lib/cli/cli install ffmpeg
- run: npm run ctest -- --channel=chrome-beta
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: chrome-beta-mac-test-results
path: test-results
| .github/workflows/tests_secondary.yml | 1 | https://github.com/microsoft/playwright/commit/a04c54ac28325e9dd420a6e570bdf7d5af5980ff | [
0.0005357521586120129,
0.00018783925042953342,
0.0001658311957726255,
0.00016918664914555848,
0.00007025099330348894
] |
{
"id": 0,
"code_window": [
"name: primary tests\n",
"\n",
"on:\n",
" push:\n"
],
"labels": [
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"name: \"tests 1\"\n"
],
"file_path": ".github/workflows/tests_primary.yml",
"type": "replace",
"edit_start_line_idx": 0
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as http from 'http';
import fs from 'fs';
import path from 'path';
export type ServerRouteHandler = (request: http.IncomingMessage, response: http.ServerResponse) => boolean;
export class HttpServer {
private _server: http.Server | undefined;
private _urlPrefix: string;
private _routes: { prefix?: string, exact?: string, handler: ServerRouteHandler }[] = [];
constructor() {
this._urlPrefix = '';
}
routePrefix(prefix: string, handler: ServerRouteHandler) {
this._routes.push({ prefix, handler });
}
routePath(path: string, handler: ServerRouteHandler) {
this._routes.push({ exact: path, handler });
}
async start(port?: number): Promise<string> {
this._server = http.createServer(this._onRequest.bind(this));
this._server.listen(port);
await new Promise(cb => this._server!.once('listening', cb));
const address = this._server.address();
this._urlPrefix = typeof address === 'string' ? address : `http://127.0.0.1:${address.port}`;
return this._urlPrefix;
}
async stop() {
await new Promise(cb => this._server!.close(cb));
}
urlPrefix() {
return this._urlPrefix;
}
serveFile(response: http.ServerResponse, absoluteFilePath: string, headers?: { [name: string]: string }): boolean {
try {
const content = fs.readFileSync(absoluteFilePath);
response.statusCode = 200;
const contentType = extensionToMime[path.extname(absoluteFilePath).substring(1)] || 'application/octet-stream';
response.setHeader('Content-Type', contentType);
response.setHeader('Content-Length', content.byteLength);
for (const [name, value] of Object.entries(headers || {}))
response.setHeader(name, value);
response.end(content);
return true;
} catch (e) {
return false;
}
}
private _onRequest(request: http.IncomingMessage, response: http.ServerResponse) {
request.on('error', () => response.end());
try {
if (!request.url) {
response.end();
return;
}
const url = new URL('http://localhost' + request.url);
for (const route of this._routes) {
if (route.exact && url.pathname === route.exact && route.handler(request, response))
return;
if (route.prefix && url.pathname.startsWith(route.prefix) && route.handler(request, response))
return;
}
response.statusCode = 404;
response.end();
} catch (e) {
response.end();
}
}
}
const extensionToMime: { [key: string]: string } = {
'css': 'text/css',
'html': 'text/html',
'jpeg': 'image/jpeg',
'jpg': 'image/jpeg',
'js': 'application/javascript',
'png': 'image/png',
'ttf': 'font/ttf',
'svg': 'image/svg+xml',
'webp': 'image/webp',
'woff': 'font/woff',
'woff2': 'font/woff2',
};
| src/utils/httpServer.ts | 0 | https://github.com/microsoft/playwright/commit/a04c54ac28325e9dd420a6e570bdf7d5af5980ff | [
0.00026357785100117326,
0.00018714609905146062,
0.00016689130279701203,
0.00017437133647035807,
0.000030204568247427233
] |
{
"id": 0,
"code_window": [
"name: primary tests\n",
"\n",
"on:\n",
" push:\n"
],
"labels": [
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"name: \"tests 1\"\n"
],
"file_path": ".github/workflows/tests_primary.yml",
"type": "replace",
"edit_start_line_idx": 0
} | /**
* Copyright 2018 Google Inc. All rights reserved.
* Modifications copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { browserTest as it, expect } from './config/browserTest';
it('should work', async ({browser, httpsServer}) => {
let error = null;
const context = await browser.newContext({ ignoreHTTPSErrors: true });
const page = await context.newPage();
const response = await page.goto(httpsServer.EMPTY_PAGE).catch(e => error = e);
expect(error).toBe(null);
expect(response.ok()).toBe(true);
await context.close();
});
it('should isolate contexts', async ({browser, httpsServer}) => {
{
let error = null;
const context = await browser.newContext({ ignoreHTTPSErrors: true });
const page = await context.newPage();
const response = await page.goto(httpsServer.EMPTY_PAGE).catch(e => error = e);
expect(error).toBe(null);
expect(response.ok()).toBe(true);
await context.close();
}
{
let error = null;
const context = await browser.newContext();
const page = await context.newPage();
await page.goto(httpsServer.EMPTY_PAGE).catch(e => error = e);
expect(error).not.toBe(null);
await context.close();
}
});
it('should work with mixed content', async ({browser, server, httpsServer}) => {
httpsServer.setRoute('/mixedcontent.html', (req, res) => {
res.end(`<iframe src=${server.EMPTY_PAGE}></iframe>`);
});
const context = await browser.newContext({ ignoreHTTPSErrors: true });
const page = await context.newPage();
await page.goto(httpsServer.PREFIX + '/mixedcontent.html', {waitUntil: 'domcontentloaded'});
expect(page.frames().length).toBe(2);
// Make sure blocked iframe has functional execution context
// @see https://github.com/GoogleChrome/puppeteer/issues/2709
expect(await page.frames()[0].evaluate('1 + 2')).toBe(3);
expect(await page.frames()[1].evaluate('2 + 3')).toBe(5);
await context.close();
});
it('should work with WebSocket', async ({browser, httpsServer}) => {
const context = await browser.newContext({ ignoreHTTPSErrors: true });
const page = await context.newPage();
const value = await page.evaluate(endpoint => {
let cb;
const result = new Promise(f => cb = f);
const ws = new WebSocket(endpoint);
ws.addEventListener('message', data => { ws.close(); cb(data.data); });
ws.addEventListener('error', error => cb('Error'));
return result;
}, httpsServer.PREFIX.replace(/https/, 'wss') + '/ws');
expect(value).toBe('incoming');
await context.close();
});
it('should fail with WebSocket if not ignored', async ({browser, httpsServer}) => {
const context = await browser.newContext();
const page = await context.newPage();
const value = await page.evaluate(endpoint => {
let cb;
const result = new Promise(f => cb = f);
const ws = new WebSocket(endpoint);
ws.addEventListener('message', data => { ws.close(); cb(data.data); });
ws.addEventListener('error', error => cb('Error'));
return result;
}, httpsServer.PREFIX.replace(/https/, 'wss') + '/ws');
expect(value).toBe('Error');
await context.close();
});
| tests/ignorehttpserrors.spec.ts | 0 | https://github.com/microsoft/playwright/commit/a04c54ac28325e9dd420a6e570bdf7d5af5980ff | [
0.00017621356528252363,
0.0001705134054645896,
0.00016563745157327503,
0.00016927742399275303,
0.000003265788109274581
] |
{
"id": 0,
"code_window": [
"name: primary tests\n",
"\n",
"on:\n",
" push:\n"
],
"labels": [
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"name: \"tests 1\"\n"
],
"file_path": ".github/workflows/tests_primary.yml",
"type": "replace",
"edit_start_line_idx": 0
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as frames from './frames';
import * as types from './types';
import { assert } from '../utils/utils';
import { SdkObject } from './instrumentation';
export function filterCookies(cookies: types.NetworkCookie[], urls: string[]): types.NetworkCookie[] {
const parsedURLs = urls.map(s => new URL(s));
// Chromiums's cookies are missing sameSite when it is 'None'
return cookies.filter(c => {
// Firefox and WebKit can return cookies with empty values.
if (!c.value)
return false;
if (!parsedURLs.length)
return true;
for (const parsedURL of parsedURLs) {
let domain = c.domain;
if (!domain.startsWith('.'))
domain = '.' + domain;
if (!('.' + parsedURL.hostname).endsWith(domain))
continue;
if (!parsedURL.pathname.startsWith(c.path))
continue;
if (parsedURL.protocol !== 'https:' && c.secure)
continue;
return true;
}
return false;
});
}
export function rewriteCookies(cookies: types.SetNetworkCookieParam[]): types.SetNetworkCookieParam[] {
return cookies.map(c => {
assert(c.name, 'Cookie should have a name');
assert(c.value, 'Cookie should have a value');
assert(c.url || (c.domain && c.path), 'Cookie should have a url or a domain/path pair');
assert(!(c.url && c.domain), 'Cookie should have either url or domain');
assert(!(c.url && c.path), 'Cookie should have either url or domain');
const copy = {...c};
if (copy.url) {
assert(copy.url !== 'about:blank', `Blank page can not have cookie "${c.name}"`);
assert(!copy.url.startsWith('data:'), `Data URL page can not have cookie "${c.name}"`);
const url = new URL(copy.url);
copy.domain = url.hostname;
copy.path = url.pathname.substring(0, url.pathname.lastIndexOf('/') + 1);
copy.secure = url.protocol === 'https:';
}
return copy;
});
}
export function parsedURL(url: string): URL | null {
try {
return new URL(url);
} catch (e) {
return null;
}
}
export function stripFragmentFromUrl(url: string): string {
if (!url.includes('#'))
return url;
return url.substring(0, url.indexOf('#'));
}
export class Request extends SdkObject {
readonly _routeDelegate: RouteDelegate | null;
private _response: Response | null = null;
private _redirectedFrom: Request | null;
private _redirectedTo: Request | null = null;
readonly _documentId?: string;
readonly _isFavicon: boolean;
_failureText: string | null = null;
private _url: string;
private _resourceType: string;
private _method: string;
private _postData: Buffer | null;
private _headers: types.HeadersArray;
private _headersMap = new Map<string, string>();
private _frame: frames.Frame;
private _waitForResponsePromise: Promise<Response | null>;
private _waitForResponsePromiseCallback: (value: Response | null) => void = () => {};
_responseEndTiming = -1;
constructor(routeDelegate: RouteDelegate | null, frame: frames.Frame, redirectedFrom: Request | null, documentId: string | undefined,
url: string, resourceType: string, method: string, postData: Buffer | null, headers: types.HeadersArray) {
super(frame, 'request');
assert(!url.startsWith('data:'), 'Data urls should not fire requests');
assert(!(routeDelegate && redirectedFrom), 'Should not be able to intercept redirects');
this._routeDelegate = routeDelegate;
this._frame = frame;
this._redirectedFrom = redirectedFrom;
if (redirectedFrom)
redirectedFrom._redirectedTo = this;
this._documentId = documentId;
this._url = stripFragmentFromUrl(url);
this._resourceType = resourceType;
this._method = method;
this._postData = postData;
this._headers = headers;
for (const { name, value } of this._headers)
this._headersMap.set(name.toLowerCase(), value);
this._waitForResponsePromise = new Promise(f => this._waitForResponsePromiseCallback = f);
this._isFavicon = url.endsWith('/favicon.ico');
}
_setFailureText(failureText: string) {
this._failureText = failureText;
this._waitForResponsePromiseCallback(null);
}
url(): string {
return this._url;
}
resourceType(): string {
return this._resourceType;
}
method(): string {
return this._method;
}
postDataBuffer(): Buffer | null {
return this._postData;
}
headers(): types.HeadersArray {
return this._headers;
}
headerValue(name: string): string | undefined {
return this._headersMap.get(name);
}
response(): Promise<Response | null> {
return this._waitForResponsePromise;
}
_existingResponse(): Response | null {
return this._response;
}
_setResponse(response: Response) {
this._response = response;
this._waitForResponsePromiseCallback(response);
}
_finalRequest(): Request {
return this._redirectedTo ? this._redirectedTo._finalRequest() : this;
}
frame(): frames.Frame {
return this._frame;
}
isNavigationRequest(): boolean {
return !!this._documentId;
}
redirectedFrom(): Request | null {
return this._redirectedFrom;
}
failure(): { errorText: string } | null {
if (this._failureText === null)
return null;
return {
errorText: this._failureText
};
}
_route(): Route | null {
if (!this._routeDelegate)
return null;
return new Route(this, this._routeDelegate);
}
updateWithRawHeaders(headers: types.HeadersArray) {
this._headers = headers;
this._headersMap.clear();
for (const { name, value } of this._headers)
this._headersMap.set(name.toLowerCase(), value);
if (!this._headersMap.has('host')) {
const host = new URL(this._url).host;
this._headers.push({ name: 'host', value: host });
this._headersMap.set('host', host);
}
}
}
export class Route extends SdkObject {
private readonly _request: Request;
private readonly _delegate: RouteDelegate;
private _handled = false;
constructor(request: Request, delegate: RouteDelegate) {
super(request.frame(), 'route');
this._request = request;
this._delegate = delegate;
}
request(): Request {
return this._request;
}
async abort(errorCode: string = 'failed') {
assert(!this._handled, 'Route is already handled!');
this._handled = true;
await this._delegate.abort(errorCode);
}
async fulfill(response: { status?: number, headers?: types.HeadersArray, body?: string, isBase64?: boolean }) {
assert(!this._handled, 'Route is already handled!');
this._handled = true;
await this._delegate.fulfill({
status: response.status === undefined ? 200 : response.status,
headers: response.headers || [],
body: response.body || '',
isBase64: response.isBase64 || false,
});
}
async continue(overrides: types.NormalizedContinueOverrides = {}) {
assert(!this._handled, 'Route is already handled!');
if (overrides.url) {
const newUrl = new URL(overrides.url);
const oldUrl = new URL(this._request.url());
if (oldUrl.protocol !== newUrl.protocol)
throw new Error('New URL must have same protocol as overridden URL');
}
await this._delegate.continue(overrides);
}
}
export type RouteHandler = (route: Route, request: Request) => void;
type GetResponseBodyCallback = () => Promise<Buffer>;
export type ResourceTiming = {
startTime: number;
domainLookupStart: number;
domainLookupEnd: number;
connectStart: number;
secureConnectionStart: number;
connectEnd: number;
requestStart: number;
responseStart: number;
};
export class Response extends SdkObject {
private _request: Request;
private _contentPromise: Promise<Buffer> | null = null;
_finishedPromise: Promise<{ error?: string }>;
private _finishedPromiseCallback: (arg: { error?: string }) => void = () => {};
private _status: number;
private _statusText: string;
private _url: string;
private _headers: types.HeadersArray;
private _headersMap = new Map<string, string>();
private _getResponseBodyCallback: GetResponseBodyCallback;
private _timing: ResourceTiming;
constructor(request: Request, status: number, statusText: string, headers: types.HeadersArray, timing: ResourceTiming, getResponseBodyCallback: GetResponseBodyCallback) {
super(request.frame(), 'response');
this._request = request;
this._timing = timing;
this._status = status;
this._statusText = statusText;
this._url = request.url();
this._headers = headers;
for (const { name, value } of this._headers)
this._headersMap.set(name.toLowerCase(), value);
this._getResponseBodyCallback = getResponseBodyCallback;
this._finishedPromise = new Promise(f => {
this._finishedPromiseCallback = f;
});
this._request._setResponse(this);
}
_requestFinished(responseEndTiming: number, error?: string) {
this._request._responseEndTiming = Math.max(responseEndTiming, this._timing.responseStart);
this._finishedPromiseCallback({ error });
}
url(): string {
return this._url;
}
status(): number {
return this._status;
}
statusText(): string {
return this._statusText;
}
headers(): types.HeadersArray {
return this._headers;
}
headerValue(name: string): string | undefined {
return this._headersMap.get(name);
}
finished(): Promise<Error | null> {
return this._finishedPromise.then(({ error }) => error ? new Error(error) : null);
}
timing(): ResourceTiming {
return this._timing;
}
body(): Promise<Buffer> {
if (!this._contentPromise) {
this._contentPromise = this._finishedPromise.then(async ({ error }) => {
if (error)
throw new Error(error);
return this._getResponseBodyCallback();
});
}
return this._contentPromise;
}
request(): Request {
return this._request;
}
frame(): frames.Frame {
return this._request.frame();
}
}
export class WebSocket extends SdkObject {
private _url: string;
static Events = {
Close: 'close',
SocketError: 'socketerror',
FrameReceived: 'framereceived',
FrameSent: 'framesent',
};
constructor(parent: SdkObject, url: string) {
super(parent, 'ws');
this._url = url;
}
url(): string {
return this._url;
}
frameSent(opcode: number, data: string) {
this.emit(WebSocket.Events.FrameSent, { opcode, data });
}
frameReceived(opcode: number, data: string) {
this.emit(WebSocket.Events.FrameReceived, { opcode, data });
}
error(errorMessage: string) {
this.emit(WebSocket.Events.SocketError, errorMessage);
}
closed() {
this.emit(WebSocket.Events.Close);
}
}
export interface RouteDelegate {
abort(errorCode: string): Promise<void>;
fulfill(response: types.NormalizedFulfillResponse): Promise<void>;
continue(overrides: types.NormalizedContinueOverrides): Promise<void>;
}
// List taken from https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml with extra 306 and 418 codes.
export const STATUS_TEXTS: { [status: string]: string } = {
'100': 'Continue',
'101': 'Switching Protocols',
'102': 'Processing',
'103': 'Early Hints',
'200': 'OK',
'201': 'Created',
'202': 'Accepted',
'203': 'Non-Authoritative Information',
'204': 'No Content',
'205': 'Reset Content',
'206': 'Partial Content',
'207': 'Multi-Status',
'208': 'Already Reported',
'226': 'IM Used',
'300': 'Multiple Choices',
'301': 'Moved Permanently',
'302': 'Found',
'303': 'See Other',
'304': 'Not Modified',
'305': 'Use Proxy',
'306': 'Switch Proxy',
'307': 'Temporary Redirect',
'308': 'Permanent Redirect',
'400': 'Bad Request',
'401': 'Unauthorized',
'402': 'Payment Required',
'403': 'Forbidden',
'404': 'Not Found',
'405': 'Method Not Allowed',
'406': 'Not Acceptable',
'407': 'Proxy Authentication Required',
'408': 'Request Timeout',
'409': 'Conflict',
'410': 'Gone',
'411': 'Length Required',
'412': 'Precondition Failed',
'413': 'Payload Too Large',
'414': 'URI Too Long',
'415': 'Unsupported Media Type',
'416': 'Range Not Satisfiable',
'417': 'Expectation Failed',
'418': 'I\'m a teapot',
'421': 'Misdirected Request',
'422': 'Unprocessable Entity',
'423': 'Locked',
'424': 'Failed Dependency',
'425': 'Too Early',
'426': 'Upgrade Required',
'428': 'Precondition Required',
'429': 'Too Many Requests',
'431': 'Request Header Fields Too Large',
'451': 'Unavailable For Legal Reasons',
'500': 'Internal Server Error',
'501': 'Not Implemented',
'502': 'Bad Gateway',
'503': 'Service Unavailable',
'504': 'Gateway Timeout',
'505': 'HTTP Version Not Supported',
'506': 'Variant Also Negotiates',
'507': 'Insufficient Storage',
'508': 'Loop Detected',
'510': 'Not Extended',
'511': 'Network Authentication Required',
};
export function singleHeader(name: string, value: string): types.HeadersArray {
return [{ name, value }];
}
export function mergeHeaders(headers: (types.HeadersArray | undefined | null)[]): types.HeadersArray {
const lowerCaseToValue = new Map<string, string>();
const lowerCaseToOriginalCase = new Map<string, string>();
for (const h of headers) {
if (!h)
continue;
for (const { name, value } of h) {
const lower = name.toLowerCase();
lowerCaseToOriginalCase.set(lower, name);
lowerCaseToValue.set(lower, value);
}
}
const result: types.HeadersArray = [];
for (const [lower, value] of lowerCaseToValue)
result.push({ name: lowerCaseToOriginalCase.get(lower)!, value });
return result;
}
| src/server/network.ts | 0 | https://github.com/microsoft/playwright/commit/a04c54ac28325e9dd420a6e570bdf7d5af5980ff | [
0.0002931611961685121,
0.00018012603686656803,
0.0001646702439757064,
0.00017030588060151786,
0.000028166536139906384
] |
{
"id": 1,
"code_window": [
" branches:\n",
" - master\n",
" - release-*\n",
" pull_request:\n",
" branches:\n",
" - master\n",
" - release-*\n",
"\n",
"env:\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" paths-ignore:\n",
" - 'browser_patches/**'\n"
],
"file_path": ".github/workflows/tests_primary.yml",
"type": "add",
"edit_start_line_idx": 8
} | name: primary tests
on:
push:
branches:
- master
- release-*
pull_request:
branches:
- master
- release-*
env:
# Force terminal colors. @see https://www.npmjs.com/package/colors
FORCE_COLOR: 1
FLAKINESS_CONNECTION_STRING: ${{ secrets.FLAKINESS_CONNECTION_STRING }}
jobs:
test_linux:
name: ${{ matrix.os }} (${{ matrix.browser }})
strategy:
fail-fast: false
matrix:
browser: [chromium, firefox, webkit]
os: [ubuntu-20.04]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
- run: npm run build
- run: node lib/cli/cli install-deps ${{ matrix.browser }} chromium
# XVFB-RUN merges both STDOUT and STDERR, whereas we need only STDERR
# Wrap `npm run` in a subshell to redirect STDERR to file.
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash -c "npm run test -- --project=${{ matrix.browser }}"
- run: node tests/config/checkCoverage.js ${{ matrix.browser }}
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: always()
with:
name: ${{ matrix.browser }}-${{ matrix.os }}-test-results
path: test-results
| .github/workflows/tests_primary.yml | 1 | https://github.com/microsoft/playwright/commit/a04c54ac28325e9dd420a6e570bdf7d5af5980ff | [
0.04008501023054123,
0.00819261372089386,
0.00017279779422096908,
0.00017747824313119054,
0.01594635285437107
] |
{
"id": 1,
"code_window": [
" branches:\n",
" - master\n",
" - release-*\n",
" pull_request:\n",
" branches:\n",
" - master\n",
" - release-*\n",
"\n",
"env:\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" paths-ignore:\n",
" - 'browser_patches/**'\n"
],
"file_path": ".github/workflows/tests_primary.yml",
"type": "add",
"edit_start_line_idx": 8
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export default async function testESM({ chromium, firefox, webkit, selectors, devices, errors, playwright, errorsFile }, browsers) {
if (playwright.chromium !== chromium)
process.exit(1);
if (playwright.firefox !== firefox)
process.exit(1);
if (playwright.webkit !== webkit)
process.exit(1);
if (playwright.errors !== errors)
process.exit(1);
if (errors.TimeoutError !== errorsFile.TimeoutError)
process.exit(1);
try {
for (const browserType of browsers) {
const browser = await browserType.launch();
const context = await browser.newContext();
const page = await context.newPage();
await page.evaluate(() => navigator.userAgent);
await browser.close();
}
console.log(`esm SUCCESS`);
} catch (err) {
console.error(err);
process.exit(1);
}
}
| packages/installation-tests/esm.mjs | 0 | https://github.com/microsoft/playwright/commit/a04c54ac28325e9dd420a6e570bdf7d5af5980ff | [
0.00017700385069474578,
0.00017510491306893528,
0.00017274606216233224,
0.00017620633298065513,
0.0000018076552805723622
] |
{
"id": 1,
"code_window": [
" branches:\n",
" - master\n",
" - release-*\n",
" pull_request:\n",
" branches:\n",
" - master\n",
" - release-*\n",
"\n",
"env:\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" paths-ignore:\n",
" - 'browser_patches/**'\n"
],
"file_path": ".github/workflows/tests_primary.yml",
"type": "add",
"edit_start_line_idx": 8
} | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
const Ci = Components.interfaces;
const Cr = Components.results;
const Cu = Components.utils;
const {Helper} = ChromeUtils.import('chrome://juggler/content/Helper.js');
const {SimpleChannel} = ChromeUtils.import('chrome://juggler/content/SimpleChannel.js');
const {EventEmitter} = ChromeUtils.import('resource://gre/modules/EventEmitter.jsm');
const {Runtime} = ChromeUtils.import('chrome://juggler/content/content/Runtime.js');
const helper = new Helper();
class FrameTree {
constructor(rootDocShell) {
EventEmitter.decorate(this);
this._browsingContextGroup = rootDocShell.browsingContext.group;
if (!this._browsingContextGroup.__jugglerFrameTrees)
this._browsingContextGroup.__jugglerFrameTrees = new Set();
this._browsingContextGroup.__jugglerFrameTrees.add(this);
this._scriptsToEvaluateOnNewDocument = new Map();
this._isolatedWorlds = new Map();
this._webSocketEventService = Cc[
"@mozilla.org/websocketevent/service;1"
].getService(Ci.nsIWebSocketEventService);
this._bindings = new Map();
this._runtime = new Runtime(false /* isWorker */);
this._workers = new Map();
this._docShellToFrame = new Map();
this._frameIdToFrame = new Map();
this._pageReady = false;
this._mainFrame = this._createFrame(rootDocShell);
const webProgress = rootDocShell.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebProgress);
this.QueryInterface = ChromeUtils.generateQI([
Ci.nsIWebProgressListener,
Ci.nsIWebProgressListener2,
Ci.nsISupportsWeakReference,
]);
this._wdm = Cc["@mozilla.org/dom/workers/workerdebuggermanager;1"].createInstance(Ci.nsIWorkerDebuggerManager);
this._wdmListener = {
QueryInterface: ChromeUtils.generateQI([Ci.nsIWorkerDebuggerManagerListener]),
onRegister: this._onWorkerCreated.bind(this),
onUnregister: this._onWorkerDestroyed.bind(this),
};
this._wdm.addListener(this._wdmListener);
for (const workerDebugger of this._wdm.getWorkerDebuggerEnumerator())
this._onWorkerCreated(workerDebugger);
const flags = Ci.nsIWebProgress.NOTIFY_STATE_DOCUMENT |
Ci.nsIWebProgress.NOTIFY_LOCATION;
this._eventListeners = [
helper.addObserver(this._onDOMWindowCreated.bind(this), 'content-document-global-created'),
helper.addObserver(this._onDOMWindowCreated.bind(this), 'juggler-dom-window-reused'),
helper.addObserver(subject => this._onDocShellCreated(subject.QueryInterface(Ci.nsIDocShell)), 'webnavigation-create'),
helper.addObserver(subject => this._onDocShellDestroyed(subject.QueryInterface(Ci.nsIDocShell)), 'webnavigation-destroy'),
helper.addProgressListener(webProgress, this, flags),
];
}
workers() {
return [...this._workers.values()];
}
runtime() {
return this._runtime;
}
addScriptToEvaluateOnNewDocument(script, worldName) {
const scriptId = helper.generateId();
if (worldName) {
this._isolatedWorlds.set(scriptId, {script, worldName});
for (const frame of this.frames())
frame.createIsolatedWorld(worldName);
} else {
this._scriptsToEvaluateOnNewDocument.set(scriptId, script);
}
return {scriptId};
}
removeScriptToEvaluateOnNewDocument(scriptId) {
if (this._isolatedWorlds.has(scriptId))
this._isolatedWorlds.delete(scriptId);
else
this._scriptsToEvaluateOnNewDocument.delete(scriptId);
}
_frameForWorker(workerDebugger) {
if (workerDebugger.type !== Ci.nsIWorkerDebugger.TYPE_DEDICATED)
return null;
if (!workerDebugger.window)
return null;
const docShell = workerDebugger.window.docShell;
return this._docShellToFrame.get(docShell) || null;
}
_onDOMWindowCreated(window) {
const frame = this._docShellToFrame.get(window.docShell) || null;
if (!frame)
return;
frame._onGlobalObjectCleared();
}
_onWorkerCreated(workerDebugger) {
// Note: we do not interoperate with firefox devtools.
if (workerDebugger.isInitialized)
return;
const frame = this._frameForWorker(workerDebugger);
if (!frame)
return;
const worker = new Worker(frame, workerDebugger);
this._workers.set(workerDebugger, worker);
this.emit(FrameTree.Events.WorkerCreated, worker);
}
_onWorkerDestroyed(workerDebugger) {
const worker = this._workers.get(workerDebugger);
if (!worker)
return;
worker.dispose();
this._workers.delete(workerDebugger);
this.emit(FrameTree.Events.WorkerDestroyed, worker);
}
allFramesInBrowsingContextGroup(group) {
const frames = [];
for (const frameTree of (group.__jugglerFrameTrees || []))
frames.push(...frameTree.frames());
return frames;
}
isPageReady() {
return this._pageReady;
}
forcePageReady() {
if (this._pageReady)
return false;
this._pageReady = true;
this.emit(FrameTree.Events.PageReady);
return true;
}
addBinding(worldName, name, script) {
this._bindings.set(worldName + ':' + name, {worldName, name, script});
for (const frame of this.frames())
frame._addBinding(worldName, name, script);
}
frameForDocShell(docShell) {
return this._docShellToFrame.get(docShell) || null;
}
frame(frameId) {
return this._frameIdToFrame.get(frameId) || null;
}
frames() {
let result = [];
collect(this._mainFrame);
return result;
function collect(frame) {
result.push(frame);
for (const subframe of frame._children)
collect(subframe);
}
}
mainFrame() {
return this._mainFrame;
}
dispose() {
this._browsingContextGroup.__jugglerFrameTrees.delete(this);
this._wdm.removeListener(this._wdmListener);
this._runtime.dispose();
helper.removeListeners(this._eventListeners);
}
onStateChange(progress, request, flag, status) {
if (!(request instanceof Ci.nsIChannel))
return;
const channel = request.QueryInterface(Ci.nsIChannel);
const docShell = progress.DOMWindow.docShell;
const frame = this._docShellToFrame.get(docShell);
if (!frame) {
dump(`ERROR: got a state changed event for un-tracked docshell!\n`);
return;
}
if (!channel.isDocument) {
// Somehow, we can get worker requests here,
// while we are only interested in frame documents.
return;
}
const isStart = flag & Ci.nsIWebProgressListener.STATE_START;
const isTransferring = flag & Ci.nsIWebProgressListener.STATE_TRANSFERRING;
const isStop = flag & Ci.nsIWebProgressListener.STATE_STOP;
const isDocument = flag & Ci.nsIWebProgressListener.STATE_IS_DOCUMENT;
if (isStart) {
// Starting a new navigation.
frame._pendingNavigationId = channelId(channel);
frame._pendingNavigationURL = channel.URI.spec;
this.emit(FrameTree.Events.NavigationStarted, frame);
} else if (isTransferring || (isStop && frame._pendingNavigationId && !status)) {
// Navigation is committed.
for (const subframe of frame._children)
this._detachFrame(subframe);
const navigationId = frame._pendingNavigationId;
frame._pendingNavigationId = null;
frame._pendingNavigationURL = null;
frame._lastCommittedNavigationId = navigationId;
frame._url = channel.URI.spec;
this.emit(FrameTree.Events.NavigationCommitted, frame);
if (frame === this._mainFrame)
this.forcePageReady();
} else if (isStop && frame._pendingNavigationId && status) {
// Navigation is aborted.
const navigationId = frame._pendingNavigationId;
frame._pendingNavigationId = null;
frame._pendingNavigationURL = null;
// Always report download navigation as failure to match other browsers.
const errorText = helper.getNetworkErrorStatusText(status);
this.emit(FrameTree.Events.NavigationAborted, frame, navigationId, errorText);
if (frame === this._mainFrame && status !== Cr.NS_BINDING_ABORTED)
this.forcePageReady();
}
if (isStop && isDocument)
this.emit(FrameTree.Events.Load, frame);
}
onLocationChange(progress, request, location, flags) {
const docShell = progress.DOMWindow.docShell;
const frame = this._docShellToFrame.get(docShell);
const sameDocumentNavigation = !!(flags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT);
if (frame && sameDocumentNavigation) {
frame._url = location.spec;
this.emit(FrameTree.Events.SameDocumentNavigation, frame);
}
}
_onDocShellCreated(docShell) {
// Bug 1142752: sometimes, the docshell appears to be immediately
// destroyed, bailout early to prevent random exceptions.
if (docShell.isBeingDestroyed())
return;
// If this docShell doesn't belong to our frame tree - do nothing.
let root = docShell;
while (root.parent)
root = root.parent;
if (root === this._mainFrame._docShell)
this._createFrame(docShell);
}
_createFrame(docShell) {
const parentFrame = this._docShellToFrame.get(docShell.parent) || null;
const frame = new Frame(this, this._runtime, docShell, parentFrame);
this._docShellToFrame.set(docShell, frame);
this._frameIdToFrame.set(frame.id(), frame);
this.emit(FrameTree.Events.FrameAttached, frame);
// Create execution context **after** reporting frame.
// This is our protocol contract.
if (frame.domWindow())
frame._onGlobalObjectCleared();
return frame;
}
_onDocShellDestroyed(docShell) {
const frame = this._docShellToFrame.get(docShell);
if (frame)
this._detachFrame(frame);
}
_detachFrame(frame) {
// Detach all children first
for (const subframe of frame._children)
this._detachFrame(subframe);
this._docShellToFrame.delete(frame._docShell);
this._frameIdToFrame.delete(frame.id());
if (frame._parentFrame)
frame._parentFrame._children.delete(frame);
frame._parentFrame = null;
frame.dispose();
this.emit(FrameTree.Events.FrameDetached, frame);
}
}
FrameTree.Events = {
FrameAttached: 'frameattached',
FrameDetached: 'framedetached',
WorkerCreated: 'workercreated',
WorkerDestroyed: 'workerdestroyed',
WebSocketCreated: 'websocketcreated',
WebSocketOpened: 'websocketopened',
WebSocketClosed: 'websocketclosed',
WebSocketFrameReceived: 'websocketframereceived',
WebSocketFrameSent: 'websocketframesent',
NavigationStarted: 'navigationstarted',
NavigationCommitted: 'navigationcommitted',
NavigationAborted: 'navigationaborted',
SameDocumentNavigation: 'samedocumentnavigation',
PageReady: 'pageready',
Load: 'load',
};
class Frame {
constructor(frameTree, runtime, docShell, parentFrame) {
this._frameTree = frameTree;
this._runtime = runtime;
this._docShell = docShell;
this._children = new Set();
this._frameId = helper.browsingContextToFrameId(this._docShell.browsingContext);
this._parentFrame = null;
this._url = '';
if (docShell.domWindow && docShell.domWindow.location)
this._url = docShell.domWindow.location.href;
if (parentFrame) {
this._parentFrame = parentFrame;
parentFrame._children.add(this);
}
this._lastCommittedNavigationId = null;
this._pendingNavigationId = null;
this._pendingNavigationURL = null;
this._textInputProcessor = null;
this._executionContext = null;
this._isolatedWorlds = new Map();
this._initialNavigationDone = false;
this._webSocketListenerInnerWindowId = 0;
// WebSocketListener calls frameReceived event before webSocketOpened.
// To avoid this, serialize event reporting.
this._webSocketInfos = new Map();
const dispatchWebSocketFrameReceived = (webSocketSerialID, frame) => this._frameTree.emit(FrameTree.Events.WebSocketFrameReceived, {
frameId: this._frameId,
wsid: webSocketSerialID + '',
opcode: frame.opCode,
data: frame.opCode !== 1 ? btoa(frame.payload) : frame.payload,
});
this._webSocketListener = {
QueryInterface: ChromeUtils.generateQI([Ci.nsIWebSocketEventListener, ]),
webSocketCreated: (webSocketSerialID, uri, protocols) => {
this._frameTree.emit(FrameTree.Events.WebSocketCreated, {
frameId: this._frameId,
wsid: webSocketSerialID + '',
requestURL: uri,
});
this._webSocketInfos.set(webSocketSerialID, {
opened: false,
pendingIncomingFrames: [],
});
},
webSocketOpened: (webSocketSerialID, effectiveURI, protocols, extensions, httpChannelId) => {
this._frameTree.emit(FrameTree.Events.WebSocketOpened, {
frameId: this._frameId,
requestId: httpChannelId + '',
wsid: webSocketSerialID + '',
effectiveURL: effectiveURI,
});
const info = this._webSocketInfos.get(webSocketSerialID);
info.opened = true;
for (const frame of info.pendingIncomingFrames)
dispatchWebSocketFrameReceived(webSocketSerialID, frame);
},
webSocketMessageAvailable: (webSocketSerialID, data, messageType) => {
// We don't use this event.
},
webSocketClosed: (webSocketSerialID, wasClean, code, reason) => {
this._webSocketInfos.delete(webSocketSerialID);
let error = '';
if (!wasClean) {
const keys = Object.keys(Ci.nsIWebSocketChannel);
for (const key of keys) {
if (Ci.nsIWebSocketChannel[key] === code)
error = key;
}
}
this._frameTree.emit(FrameTree.Events.WebSocketClosed, {
frameId: this._frameId,
wsid: webSocketSerialID + '',
error,
});
},
frameReceived: (webSocketSerialID, frame) => {
// Report only text and binary frames.
if (frame.opCode !== 1 && frame.opCode !== 2)
return;
const info = this._webSocketInfos.get(webSocketSerialID);
if (info.opened)
dispatchWebSocketFrameReceived(webSocketSerialID, frame);
else
info.pendingIncomingFrames.push(frame);
},
frameSent: (webSocketSerialID, frame) => {
// Report only text and binary frames.
if (frame.opCode !== 1 && frame.opCode !== 2)
return;
this._frameTree.emit(FrameTree.Events.WebSocketFrameSent, {
frameId: this._frameId,
wsid: webSocketSerialID + '',
opcode: frame.opCode,
data: frame.opCode !== 1 ? btoa(frame.payload) : frame.payload,
});
},
};
}
createIsolatedWorld(name) {
const principal = [this.domWindow()]; // extended principal
const sandbox = Cu.Sandbox(principal, {
sandboxPrototype: this.domWindow(),
wantComponents: false,
wantExportHelpers: false,
wantXrays: true,
});
const world = this._runtime.createExecutionContext(this.domWindow(), sandbox, {
frameId: this.id(),
name,
});
this._isolatedWorlds.set(world.id(), world);
return world;
}
unsafeObject(objectId) {
const contexts = [this.executionContext(), ...this._isolatedWorlds.values()];
for (const context of contexts) {
const result = context.unsafeObject(objectId);
if (result)
return result.object;
}
throw new Error('Cannot find object with id = ' + objectId);
}
dispose() {
for (const world of this._isolatedWorlds.values())
this._runtime.destroyExecutionContext(world);
this._isolatedWorlds.clear();
if (this._executionContext)
this._runtime.destroyExecutionContext(this._executionContext);
this._executionContext = null;
}
_getOrCreateIsolatedContext(worldName) {
for (let context of this._isolatedWorlds.values()) {
if (context.auxData().name === worldName)
return context;
}
return this.createIsolatedWorld(worldName);
}
_addBinding(worldName, name, script) {
const executionContext = worldName ? this._getOrCreateIsolatedContext(worldName) : this._executionContext;
if (executionContext)
executionContext.addBinding(name, script);
}
_evaluateScriptSafely(executionContext, script) {
try {
let result = executionContext.evaluateScript(script);
if (result && result.objectId)
executionContext.disposeObject(result.objectId);
} catch (e) {
dump(`ERROR: ${e.message}\n${e.stack}\n`);
}
}
_onGlobalObjectCleared() {
const webSocketService = this._frameTree._webSocketEventService;
if (this._webSocketListenerInnerWindowId)
webSocketService.removeListener(this._webSocketListenerInnerWindowId, this._webSocketListener);
this._webSocketListenerInnerWindowId = this.domWindow().windowGlobalChild.innerWindowId;
webSocketService.addListener(this._webSocketListenerInnerWindowId, this._webSocketListener);
if (this._executionContext)
this._runtime.destroyExecutionContext(this._executionContext);
for (const world of this._isolatedWorlds.values())
this._runtime.destroyExecutionContext(world);
this._isolatedWorlds.clear();
this._executionContext = this._runtime.createExecutionContext(this.domWindow(), this.domWindow(), {
frameId: this._frameId,
name: '',
});
for (const {script, worldName} of this._frameTree._isolatedWorlds.values())
this.createIsolatedWorld(worldName);
// Add bindings before evaluating scripts.
for (const [id, {worldName, name, script}] of this._frameTree._bindings)
this._addBinding(worldName, name, script);
for (const script of this._frameTree._scriptsToEvaluateOnNewDocument.values())
this._evaluateScriptSafely(this._executionContext, script);
for (const {script, worldName} of this._frameTree._isolatedWorlds.values()) {
const context = worldName ? this._getOrCreateIsolatedContext(worldName) : this.executionContext();
this._evaluateScriptSafely(context, script);
}
}
executionContext() {
return this._executionContext;
}
textInputProcessor() {
if (!this._textInputProcessor) {
this._textInputProcessor = Cc["@mozilla.org/text-input-processor;1"].createInstance(Ci.nsITextInputProcessor);
this._textInputProcessor.beginInputTransactionForTests(this._docShell.DOMWindow);
}
return this._textInputProcessor;
}
pendingNavigationId() {
return this._pendingNavigationId;
}
pendingNavigationURL() {
return this._pendingNavigationURL;
}
lastCommittedNavigationId() {
return this._lastCommittedNavigationId;
}
docShell() {
return this._docShell;
}
domWindow() {
return this._docShell.domWindow;
}
name() {
const frameElement = this._docShell.domWindow.frameElement;
let name = '';
if (frameElement)
name = frameElement.getAttribute('name') || frameElement.getAttribute('id') || '';
return name;
}
parentFrame() {
return this._parentFrame;
}
id() {
return this._frameId;
}
url() {
return this._url;
}
}
class Worker {
constructor(frame, workerDebugger) {
this._frame = frame;
this._workerId = helper.generateId();
this._workerDebugger = workerDebugger;
workerDebugger.initialize('chrome://juggler/content/content/WorkerMain.js');
this._channel = new SimpleChannel(`content::worker[${this._workerId}]`);
this._channel.setTransport({
sendMessage: obj => workerDebugger.postMessage(JSON.stringify(obj)),
dispose: () => {},
});
this._workerDebuggerListener = {
QueryInterface: ChromeUtils.generateQI([Ci.nsIWorkerDebuggerListener]),
onMessage: msg => void this._channel._onMessage(JSON.parse(msg)),
onClose: () => void this._channel.dispose(),
onError: (filename, lineno, message) => {
dump(`Error in worker: ${message} @${filename}:${lineno}\n`);
},
};
workerDebugger.addListener(this._workerDebuggerListener);
}
channel() {
return this._channel;
}
frame() {
return this._frame;
}
id() {
return this._workerId;
}
url() {
return this._workerDebugger.url;
}
dispose() {
this._channel.dispose();
this._workerDebugger.removeListener(this._workerDebuggerListener);
}
}
function channelId(channel) {
if (channel instanceof Ci.nsIIdentChannel) {
const identChannel = channel.QueryInterface(Ci.nsIIdentChannel);
return String(identChannel.channelId);
}
return helper.generateId();
}
var EXPORTED_SYMBOLS = ['FrameTree'];
this.FrameTree = FrameTree;
| browser_patches/firefox-stable/juggler/content/FrameTree.js | 0 | https://github.com/microsoft/playwright/commit/a04c54ac28325e9dd420a6e570bdf7d5af5980ff | [
0.00024482732987962663,
0.0001727625058265403,
0.00016524529200978577,
0.00017224960902240127,
0.000009567685992806219
] |
{
"id": 1,
"code_window": [
" branches:\n",
" - master\n",
" - release-*\n",
" pull_request:\n",
" branches:\n",
" - master\n",
" - release-*\n",
"\n",
"env:\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" paths-ignore:\n",
" - 'browser_patches/**'\n"
],
"file_path": ".github/workflows/tests_primary.yml",
"type": "add",
"edit_start_line_idx": 8
} | #!/bin/bash
set -e
set +x
trap "cd $(pwd -P)" EXIT
if [[ ! -z "${FF_CHECKOUT_PATH}" ]]; then
cd "${FF_CHECKOUT_PATH}"
echo "WARNING: checkout path from FF_CHECKOUT_PATH env: ${FF_CHECKOUT_PATH}"
else
cd "$(dirname $0)"
cd "checkout"
fi
OBJ_FOLDER="obj-build-playwright"
if [[ -d $OBJ_FOLDER ]]; then
rm -rf $OBJ_FOLDER
fi
| browser_patches/firefox/clean.sh | 0 | https://github.com/microsoft/playwright/commit/a04c54ac28325e9dd420a6e570bdf7d5af5980ff | [
0.00027489016065374017,
0.00022236719087231904,
0.00016984422109089792,
0.00022236719087231904,
0.000052522969781421125
] |
{
"id": 2,
"code_window": [
"name: secondary tests\n",
"\n",
"on:\n",
" push:\n"
],
"labels": [
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"name: \"tests 2\"\n"
],
"file_path": ".github/workflows/tests_secondary.yml",
"type": "replace",
"edit_start_line_idx": 0
} | name: secondary tests
on:
push:
branches:
- master
- release-*
pull_request:
types: [ labeled ]
branches:
- master
- release-*
env:
# Force terminal colors. @see https://www.npmjs.com/package/colors
FORCE_COLOR: 1
FLAKINESS_CONNECTION_STRING: ${{ secrets.FLAKINESS_CONNECTION_STRING }}
jobs:
test_linux:
name: ${{ matrix.os }} (${{ matrix.browser }})
strategy:
fail-fast: false
matrix:
browser: [chromium, firefox, webkit]
os: [ubuntu-18.04]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
- run: npm run build
- run: node lib/cli/cli install-deps ${{ matrix.browser }} chromium
# XVFB-RUN merges both STDOUT and STDERR, whereas we need only STDERR
# Wrap `npm run` in a subshell to redirect STDERR to file.
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash -c "npm run test -- --project=${{ matrix.browser }}"
- run: node tests/config/checkCoverage.js ${{ matrix.browser }}
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: always()
with:
name: ${{ matrix.browser }}-${{ matrix.os }}-test-results
path: test-results
test_mac:
name: ${{ matrix.os }} (${{ matrix.browser }})
strategy:
fail-fast: false
matrix:
os: [macos-10.15, macos-11.0]
browser: [chromium, firefox, webkit]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
DEBUG: extract-zip
- run: npm run build
- run: node lib/cli/cli install-deps ${{ matrix.browser }} chromium
- run: npm run test -- --project=${{ matrix.browser }}
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: ${{ matrix.browser }}-${{ matrix.os }}-test-results
path: test-results
test_win:
name: "Windows"
strategy:
fail-fast: false
matrix:
browser: [chromium, firefox, webkit]
runs-on: windows-latest
steps:
- name: Install Media Pack
shell: powershell
run: Install-WindowsFeature Server-Media-Foundation
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
DEBUG: extract-zip
- run: npm run build
- run: node lib/cli/cli install-deps
- run: npm run test -- --project=${{ matrix.browser }}
shell: bash
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
shell: bash
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: ${{ matrix.browser }}-win-test-results
path: test-results
test-package-installations:
runs-on: ubuntu-20.04
strategy:
fail-fast: false
matrix:
node_version:
- "^12.0.0"
- "^14.1.0" # pre 14.1, zip extraction was broken (https://github.com/microsoft/playwright/issues/1988)
timeout-minutes: 20
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node_version }}
- run: npm ci
env:
DEBUG: extract-zip
- run: npm run build
- run: node lib/cli/cli install-deps
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash packages/installation-tests/installation-tests.sh
headful_linux:
name: "Headful Linux"
strategy:
fail-fast: false
matrix:
browser: [chromium, firefox, webkit]
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
- run: npm run build
- run: node lib/cli/cli install-deps ${{ matrix.browser }} chromium
# XVFB-RUN merges both STDOUT and STDERR, whereas we need only STDERR
# Wrap `npm run` in a subshell to redirect STDERR to file.
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash -c "npm run test -- --project=${{ matrix.browser }} --headed"
if: ${{ always() }}
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: headful-${{ matrix.browser }}-linux-test-results
path: test-results
transport_linux:
name: "Transport"
strategy:
fail-fast: false
matrix:
mode: [driver, service]
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
- run: npm run build
- run: node lib/cli/cli install-deps chromium
# XVFB-RUN merges both STDOUT and STDERR, whereas we need only STDERR
# Wrap `npm run` in a subshell to redirect STDERR to file.
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash -c "npm run ctest -- --mode=${{ matrix.mode }}"
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: mode-${{ matrix.mode }}-linux-test-results
path: test-results
video_linux:
name: "Video Linux"
strategy:
fail-fast: false
matrix:
browser: [chromium, firefox, webkit]
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
- run: npm run build
- run: node lib/cli/cli install-deps ${{ matrix.browser }} chromium
# XVFB-RUN merges both STDOUT and STDERR, whereas we need only STDERR
# Wrap `npm run` in a subshell to redirect STDERR to file.
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash -c "npm run test -- --project=${{ matrix.browser }} --video"
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: video-${{ matrix.browser }}-linux-test-results
path: test-results
test_android:
name: Android Emulator (shard ${{ matrix.shard }})
strategy:
fail-fast: false
matrix:
shard: [1, 2]
runs-on: macos-10.15
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 14
- run: npm ci
- run: npm run build
- run: node lib/cli/cli install-deps
- name: Create Android Emulator
run: utils/avd_recreate.sh
- name: Start Android Emulator
run: utils/avd_start.sh
- name: Run tests
run: npm run atest -- --shard=${{ matrix.shard }}/2
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: android-test-results
path: test-results
chrome_stable_linux:
name: "Chrome Stable (Linux)"
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- name: Install Chrome Stable
run: sudo apt install google-chrome-stable
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
- run: node lib/cli/cli install-deps chromium
# This only created problems, should we move ffmpeg back into npm?
- run: node lib/cli/cli install ffmpeg
# XVFB-RUN merges both STDOUT and STDERR, whereas we need only STDERR
# Wrap `npm run` in a subshell to redirect STDERR to file.
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash -c "npm run ctest -- --channel=chrome"
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: chrome-stable-linux-test-results
path: test-results
chrome_stable_win:
name: "Chrome Stable (Win)"
runs-on: windows-latest
steps:
- name: Install Media Pack
shell: powershell
run: Install-WindowsFeature Server-Media-Foundation
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
# This only created problems, should we move ffmpeg back into npm?
- run: node lib/cli/cli install ffmpeg
- run: npm run ctest -- --channel=chrome
shell: bash
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
shell: bash
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: chrome-stable-win-test-results
path: test-results
chrome_stable_mac:
name: "Chrome Stable (Mac)"
runs-on: macos-10.15
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
# This only created problems, should we move ffmpeg back into npm?
- run: node lib/cli/cli install ffmpeg
- run: npm run ctest -- --channel=chrome
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: chrome-stable-mac-test-results
path: test-results
firefox_stable_linux:
name: "Firefox Stable (Linux)"
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
- run: node lib/cli/cli install-deps firefox
- run: node lib/cli/cli install ffmpeg firefox-stable chromium
# XVFB-RUN merges both STDOUT and STDERR, whereas we need only STDERR
# Wrap `npm run` in a subshell to redirect STDERR to file.
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash -c "npm run ftest -- --channel=firefox-stable"
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: firefox-stable-linux-test-results
path: test-results
firefox_stable_win:
name: "Firefox Stable (Win)"
runs-on: windows-latest
steps:
- name: Install Media Pack
shell: powershell
run: Install-WindowsFeature Server-Media-Foundation
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
- run: node lib/cli/cli install ffmpeg firefox-stable chromium
- run: npm run ftest -- --channel=firefox-stable
shell: bash
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
shell: bash
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: firefox-stable-win-test-results
path: test-results
firefox_stable_mac:
name: "Firefox Stable (Mac)"
runs-on: macos-10.15
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
- run: node lib/cli/cli install ffmpeg firefox-stable chromium
- run: npm run ftest -- --channel=firefox-stable
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: firefox-stable-mac-test-results
path: test-results
edge_stable_win:
name: "Edge Stable (Win)"
runs-on: windows-latest
steps:
- name: Install Media Pack
shell: powershell
run: Install-WindowsFeature Server-Media-Foundation
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
# This only created problems, should we move ffmpeg back into npm?
- run: node lib/cli/cli install ffmpeg
- run: npm run ctest -- --channel=msedge
shell: bash
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: edge-stable-win-test-results
path: test-results
test_electron:
name: "Electron Linux"
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
- run: npm run build
- run: node lib/cli/cli install-deps chromium
# XVFB-RUN merges both STDOUT and STDERR, whereas we need only STDERR
# Wrap `npm run` in a subshell to redirect STDERR to file.
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash -c "npm run etest"
- run: node tests/config/checkCoverage.js electron
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: electron-linux-test-results
path: test-results
chrome_beta_linux:
name: "Chrome Beta (Linux)"
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- run: ./utils/install-chrome-beta/reinstall_linux.sh
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
- run: node lib/cli/cli install-deps chromium
- run: node lib/cli/cli install ffmpeg
# XVFB-RUN merges both STDOUT and STDERR, whereas we need only STDERR
# Wrap `npm run` in a subshell to redirect STDERR to file.
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash -c "npm run ctest -- --channel=chrome-beta"
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: chrome-beta-linux-test-results
path: test-results
chrome_beta_win:
name: "Chrome Beta (Win)"
runs-on: windows-latest
steps:
- name: Install Media Pack
shell: powershell
run: Install-WindowsFeature Server-Media-Foundation
- name: Install Chrome Beta
shell: powershell
run: choco install -y googlechromebeta --pre --force
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
- run: node lib/cli/cli install ffmpeg
- run: npm run ctest -- --channel=chrome-beta
shell: bash
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
shell: bash
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: chrome-beta-win-test-results
path: test-results
chrome_beta_mac:
name: "Chrome Beta (Mac)"
runs-on: macos-10.15
steps:
- uses: actions/checkout@v2
- run: ./utils/install-chrome-beta/reinstall_mac.sh
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
- run: node lib/cli/cli install ffmpeg
- run: npm run ctest -- --channel=chrome-beta
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: chrome-beta-mac-test-results
path: test-results
| .github/workflows/tests_secondary.yml | 1 | https://github.com/microsoft/playwright/commit/a04c54ac28325e9dd420a6e570bdf7d5af5980ff | [
0.007464998867362738,
0.00031954736914485693,
0.00016631177277304232,
0.0001694251986918971,
0.0010018491884693503
] |
{
"id": 2,
"code_window": [
"name: secondary tests\n",
"\n",
"on:\n",
" push:\n"
],
"labels": [
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"name: \"tests 2\"\n"
],
"file_path": ".github/workflows/tests_secondary.yml",
"type": "replace",
"edit_start_line_idx": 0
} | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
// Note: this file should be loadabale with eval() into worker environment.
// Avoid Components.*, ChromeUtils and global const variables.
if (!this.Debugger) {
// Worker has a Debugger defined already.
const {addDebuggerToGlobal} = ChromeUtils.import("resource://gre/modules/jsdebugger.jsm", {});
addDebuggerToGlobal(Components.utils.getGlobalForObject(this));
}
let lastId = 0;
function generateId() {
return 'id-' + (++lastId);
}
const consoleLevelToProtocolType = {
'dir': 'dir',
'log': 'log',
'debug': 'debug',
'info': 'info',
'error': 'error',
'warn': 'warning',
'dirxml': 'dirxml',
'table': 'table',
'trace': 'trace',
'clear': 'clear',
'group': 'startGroup',
'groupCollapsed': 'startGroupCollapsed',
'groupEnd': 'endGroup',
'assert': 'assert',
'profile': 'profile',
'profileEnd': 'profileEnd',
'count': 'count',
'countReset': 'countReset',
'time': null,
'timeLog': 'timeLog',
'timeEnd': 'timeEnd',
'timeStamp': 'timeStamp',
};
const disallowedMessageCategories = new Set([
'XPConnect JavaScript',
'component javascript',
'chrome javascript',
'chrome registration',
'XBL',
'XBL Prototype Handler',
'XBL Content Sink',
'xbl javascript',
]);
class Runtime {
constructor(isWorker = false) {
this._debugger = new Debugger();
this._pendingPromises = new Map();
this._executionContexts = new Map();
this._windowToExecutionContext = new Map();
this._eventListeners = [];
if (isWorker) {
this._registerWorkerConsoleHandler();
} else {
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
this._registerConsoleServiceListener(Services);
this._registerConsoleObserver(Services);
}
// We can't use event listener here to be compatible with Worker Global Context.
// Use plain callbacks instead.
this.events = {
onConsoleMessage: createEvent(),
onErrorFromWorker: createEvent(),
onExecutionContextCreated: createEvent(),
onExecutionContextDestroyed: createEvent(),
onBindingCalled: createEvent(),
};
}
executionContexts() {
return [...this._executionContexts.values()];
}
async evaluate({executionContextId, expression, returnByValue}) {
const executionContext = this.findExecutionContext(executionContextId);
if (!executionContext)
throw new Error('Failed to find execution context with id = ' + executionContextId);
const exceptionDetails = {};
let result = await executionContext.evaluateScript(expression, exceptionDetails);
if (!result)
return {exceptionDetails};
if (returnByValue)
result = executionContext.ensureSerializedToValue(result);
return {result};
}
async callFunction({executionContextId, functionDeclaration, args, returnByValue}) {
const executionContext = this.findExecutionContext(executionContextId);
if (!executionContext)
throw new Error('Failed to find execution context with id = ' + executionContextId);
const exceptionDetails = {};
let result = await executionContext.evaluateFunction(functionDeclaration, args, exceptionDetails);
if (!result)
return {exceptionDetails};
if (returnByValue)
result = executionContext.ensureSerializedToValue(result);
return {result};
}
async getObjectProperties({executionContextId, objectId}) {
const executionContext = this.findExecutionContext(executionContextId);
if (!executionContext)
throw new Error('Failed to find execution context with id = ' + executionContextId);
return {properties: executionContext.getObjectProperties(objectId)};
}
async disposeObject({executionContextId, objectId}) {
const executionContext = this.findExecutionContext(executionContextId);
if (!executionContext)
throw new Error('Failed to find execution context with id = ' + executionContextId);
return executionContext.disposeObject(objectId);
}
_registerConsoleServiceListener(Services) {
const Ci = Components.interfaces;
const consoleServiceListener = {
QueryInterface: ChromeUtils.generateQI([Ci.nsIConsoleListener]),
observe: message => {
if (!(message instanceof Ci.nsIScriptError) || !message.outerWindowID ||
!message.category || disallowedMessageCategories.has(message.category)) {
return;
}
const errorWindow = Services.wm.getOuterWindowWithId(message.outerWindowID);
if (message.category === 'Web Worker' && message.logLevel === Ci.nsIConsoleMessage.error) {
emitEvent(this.events.onErrorFromWorker, errorWindow, message.message, '' + message.stack);
return;
}
const executionContext = this._windowToExecutionContext.get(errorWindow);
if (!executionContext)
return;
const typeNames = {
[Ci.nsIConsoleMessage.debug]: 'debug',
[Ci.nsIConsoleMessage.info]: 'info',
[Ci.nsIConsoleMessage.warn]: 'warn',
[Ci.nsIConsoleMessage.error]: 'error',
};
emitEvent(this.events.onConsoleMessage, {
args: [{
value: message.message,
}],
type: typeNames[message.logLevel],
executionContextId: executionContext.id(),
location: {
lineNumber: message.lineNumber,
columnNumber: message.columnNumber,
url: message.sourceName,
},
});
},
};
Services.console.registerListener(consoleServiceListener);
this._eventListeners.push(() => Services.console.unregisterListener(consoleServiceListener));
}
_registerConsoleObserver(Services) {
const consoleObserver = ({wrappedJSObject}, topic, data) => {
const executionContext = Array.from(this._executionContexts.values()).find(context => {
// There is no easy way to determine isolated world context and we normally don't write
// objects to console from utility worlds so we always return main world context here.
if (context._isIsolatedWorldContext())
return false;
const domWindow = context._domWindow;
return domWindow && domWindow.windowGlobalChild.innerWindowId === wrappedJSObject.innerID;
});
if (!executionContext)
return;
this._onConsoleMessage(executionContext, wrappedJSObject);
};
Services.obs.addObserver(consoleObserver, "console-api-log-event");
this._eventListeners.push(() => Services.obs.removeObserver(consoleObserver, "console-api-log-event"));
}
_registerWorkerConsoleHandler() {
setConsoleEventHandler(message => {
const executionContext = Array.from(this._executionContexts.values())[0];
this._onConsoleMessage(executionContext, message);
});
this._eventListeners.push(() => setConsoleEventHandler(null));
}
_onConsoleMessage(executionContext, message) {
const type = consoleLevelToProtocolType[message.level];
if (!type)
return;
const args = message.arguments.map(arg => executionContext.rawValueToRemoteObject(arg));
emitEvent(this.events.onConsoleMessage, {
args,
type,
executionContextId: executionContext.id(),
location: {
lineNumber: message.lineNumber - 1,
columnNumber: message.columnNumber - 1,
url: message.filename,
},
});
}
dispose() {
for (const tearDown of this._eventListeners)
tearDown.call(null);
this._eventListeners = [];
}
async _awaitPromise(executionContext, obj, exceptionDetails = {}) {
if (obj.promiseState === 'fulfilled')
return {success: true, obj: obj.promiseValue};
if (obj.promiseState === 'rejected') {
const global = executionContext._global;
exceptionDetails.text = global.executeInGlobalWithBindings('e.message', {e: obj.promiseReason}).return;
exceptionDetails.stack = global.executeInGlobalWithBindings('e.stack', {e: obj.promiseReason}).return;
return {success: false, obj: null};
}
let resolve, reject;
const promise = new Promise((a, b) => {
resolve = a;
reject = b;
});
this._pendingPromises.set(obj.promiseID, {resolve, reject, executionContext, exceptionDetails});
if (this._pendingPromises.size === 1)
this._debugger.onPromiseSettled = this._onPromiseSettled.bind(this);
return await promise;
}
_onPromiseSettled(obj) {
const pendingPromise = this._pendingPromises.get(obj.promiseID);
if (!pendingPromise)
return;
this._pendingPromises.delete(obj.promiseID);
if (!this._pendingPromises.size)
this._debugger.onPromiseSettled = undefined;
if (obj.promiseState === 'fulfilled') {
pendingPromise.resolve({success: true, obj: obj.promiseValue});
return;
};
const global = pendingPromise.executionContext._global;
pendingPromise.exceptionDetails.text = global.executeInGlobalWithBindings('e.message', {e: obj.promiseReason}).return;
pendingPromise.exceptionDetails.stack = global.executeInGlobalWithBindings('e.stack', {e: obj.promiseReason}).return;
pendingPromise.resolve({success: false, obj: null});
}
createExecutionContext(domWindow, contextGlobal, auxData) {
// Note: domWindow is null for workers.
const context = new ExecutionContext(this, domWindow, contextGlobal, this._debugger.addDebuggee(contextGlobal), auxData);
this._executionContexts.set(context._id, context);
if (domWindow)
this._windowToExecutionContext.set(domWindow, context);
emitEvent(this.events.onExecutionContextCreated, context);
return context;
}
findExecutionContext(executionContextId) {
const executionContext = this._executionContexts.get(executionContextId);
if (!executionContext)
throw new Error('Failed to find execution context with id = ' + executionContextId);
return executionContext;
}
destroyExecutionContext(destroyedContext) {
for (const [promiseID, {reject, executionContext}] of this._pendingPromises) {
if (executionContext === destroyedContext) {
reject(new Error('Execution context was destroyed!'));
this._pendingPromises.delete(promiseID);
}
}
if (!this._pendingPromises.size)
this._debugger.onPromiseSettled = undefined;
this._debugger.removeDebuggee(destroyedContext._contextGlobal);
this._executionContexts.delete(destroyedContext._id);
if (destroyedContext._domWindow)
this._windowToExecutionContext.delete(destroyedContext._domWindow);
emitEvent(this.events.onExecutionContextDestroyed, destroyedContext);
}
}
class ExecutionContext {
constructor(runtime, domWindow, contextGlobal, global, auxData) {
this._runtime = runtime;
this._domWindow = domWindow;
this._contextGlobal = contextGlobal;
this._global = global;
this._remoteObjects = new Map();
this._id = generateId();
this._auxData = auxData;
this._jsonStringifyObject = this._global.executeInGlobal(`((stringify, dateProto, object) => {
const oldToJson = dateProto.toJSON;
dateProto.toJSON = undefined;
let hasSymbol = false;
const result = stringify(object, (key, value) => {
if (typeof value === 'symbol')
hasSymbol = true;
return value;
});
dateProto.toJSON = oldToJson;
return hasSymbol ? undefined : result;
}).bind(null, JSON.stringify.bind(JSON), Date.prototype)`).return;
}
id() {
return this._id;
}
auxData() {
return this._auxData;
}
_isIsolatedWorldContext() {
return !!this._auxData.name;
}
async evaluateScript(script, exceptionDetails = {}) {
const userInputHelper = this._domWindow ? this._domWindow.windowUtils.setHandlingUserInput(true) : null;
if (this._domWindow && this._domWindow.document)
this._domWindow.document.notifyUserGestureActivation();
let {success, obj} = this._getResult(this._global.executeInGlobal(script), exceptionDetails);
userInputHelper && userInputHelper.destruct();
if (!success)
return null;
if (obj && obj.isPromise) {
const awaitResult = await this._runtime._awaitPromise(this, obj, exceptionDetails);
if (!awaitResult.success)
return null;
obj = awaitResult.obj;
}
return this._createRemoteObject(obj);
}
async evaluateFunction(functionText, args, exceptionDetails = {}) {
const funEvaluation = this._getResult(this._global.executeInGlobal('(' + functionText + ')'), exceptionDetails);
if (!funEvaluation.success)
return null;
if (!funEvaluation.obj.callable)
throw new Error('functionText does not evaluate to a function!');
args = args.map(arg => {
if (arg.objectId) {
if (!this._remoteObjects.has(arg.objectId))
throw new Error('Cannot find object with id = ' + arg.objectId);
return this._remoteObjects.get(arg.objectId);
}
switch (arg.unserializableValue) {
case 'Infinity': return Infinity;
case '-Infinity': return -Infinity;
case '-0': return -0;
case 'NaN': return NaN;
default: return this._toDebugger(arg.value);
}
});
const userInputHelper = this._domWindow ? this._domWindow.windowUtils.setHandlingUserInput(true) : null;
if (this._domWindow && this._domWindow.document)
this._domWindow.document.notifyUserGestureActivation();
let {success, obj} = this._getResult(funEvaluation.obj.apply(null, args), exceptionDetails);
userInputHelper && userInputHelper.destruct();
if (!success)
return null;
if (obj && obj.isPromise) {
const awaitResult = await this._runtime._awaitPromise(this, obj, exceptionDetails);
if (!awaitResult.success)
return null;
obj = awaitResult.obj;
}
return this._createRemoteObject(obj);
}
addBinding(name, script) {
Cu.exportFunction((...args) => {
emitEvent(this._runtime.events.onBindingCalled, {
executionContextId: this._id,
name,
payload: args[0],
});
}, this._contextGlobal, {
defineAs: name,
});
try {
this._global.executeInGlobal(script);
} catch (e) {
dump(`ERROR: ${e.message}\n${e.stack}\n`);
}
}
unsafeObject(objectId) {
if (!this._remoteObjects.has(objectId))
return;
return { object: this._remoteObjects.get(objectId).unsafeDereference() };
}
rawValueToRemoteObject(rawValue) {
const debuggerObj = this._global.makeDebuggeeValue(rawValue);
return this._createRemoteObject(debuggerObj);
}
_instanceOf(debuggerObj, rawObj, className) {
if (this._domWindow)
return rawObj instanceof this._domWindow[className];
return this._global.executeInGlobalWithBindings('o instanceof this[className]', {o: debuggerObj, className: this._global.makeDebuggeeValue(className)}).return;
}
_createRemoteObject(debuggerObj) {
if (debuggerObj instanceof Debugger.Object) {
const objectId = generateId();
this._remoteObjects.set(objectId, debuggerObj);
const rawObj = debuggerObj.unsafeDereference();
const type = typeof rawObj;
let subtype = undefined;
if (debuggerObj.isProxy)
subtype = 'proxy';
else if (Array.isArray(rawObj))
subtype = 'array';
else if (Object.is(rawObj, null))
subtype = 'null';
else if (this._instanceOf(debuggerObj, rawObj, 'Node'))
subtype = 'node';
else if (this._instanceOf(debuggerObj, rawObj, 'RegExp'))
subtype = 'regexp';
else if (this._instanceOf(debuggerObj, rawObj, 'Date'))
subtype = 'date';
else if (this._instanceOf(debuggerObj, rawObj, 'Map'))
subtype = 'map';
else if (this._instanceOf(debuggerObj, rawObj, 'Set'))
subtype = 'set';
else if (this._instanceOf(debuggerObj, rawObj, 'WeakMap'))
subtype = 'weakmap';
else if (this._instanceOf(debuggerObj, rawObj, 'WeakSet'))
subtype = 'weakset';
else if (this._instanceOf(debuggerObj, rawObj, 'Error'))
subtype = 'error';
else if (this._instanceOf(debuggerObj, rawObj, 'Promise'))
subtype = 'promise';
else if ((this._instanceOf(debuggerObj, rawObj, 'Int8Array')) || (this._instanceOf(debuggerObj, rawObj, 'Uint8Array')) ||
(this._instanceOf(debuggerObj, rawObj, 'Uint8ClampedArray')) || (this._instanceOf(debuggerObj, rawObj, 'Int16Array')) ||
(this._instanceOf(debuggerObj, rawObj, 'Uint16Array')) || (this._instanceOf(debuggerObj, rawObj, 'Int32Array')) ||
(this._instanceOf(debuggerObj, rawObj, 'Uint32Array')) || (this._instanceOf(debuggerObj, rawObj, 'Float32Array')) ||
(this._instanceOf(debuggerObj, rawObj, 'Float64Array'))) {
subtype = 'typedarray';
}
return {objectId, type, subtype};
}
if (typeof debuggerObj === 'symbol') {
const objectId = generateId();
this._remoteObjects.set(objectId, debuggerObj);
return {objectId, type: 'symbol'};
}
let unserializableValue = undefined;
if (Object.is(debuggerObj, NaN))
unserializableValue = 'NaN';
else if (Object.is(debuggerObj, -0))
unserializableValue = '-0';
else if (Object.is(debuggerObj, Infinity))
unserializableValue = 'Infinity';
else if (Object.is(debuggerObj, -Infinity))
unserializableValue = '-Infinity';
return unserializableValue ? {unserializableValue} : {value: debuggerObj};
}
ensureSerializedToValue(protocolObject) {
if (!protocolObject.objectId)
return protocolObject;
const obj = this._remoteObjects.get(protocolObject.objectId);
this._remoteObjects.delete(protocolObject.objectId);
return {value: this._serialize(obj)};
}
_toDebugger(obj) {
if (typeof obj !== 'object')
return obj;
if (obj === null)
return obj;
const properties = {};
for (let [key, value] of Object.entries(obj)) {
properties[key] = {
configurable: true,
writable: true,
enumerable: true,
value: this._toDebugger(value),
};
}
const baseObject = Array.isArray(obj) ? '([])' : '({})';
const debuggerObj = this._global.executeInGlobal(baseObject).return;
debuggerObj.defineProperties(properties);
return debuggerObj;
}
_serialize(obj) {
const result = this._global.executeInGlobalWithBindings('stringify(e)', {e: obj, stringify: this._jsonStringifyObject});
if (result.throw)
throw new Error('Object is not serializable');
return result.return === undefined ? undefined : JSON.parse(result.return);
}
disposeObject(objectId) {
this._remoteObjects.delete(objectId);
}
getObjectProperties(objectId) {
if (!this._remoteObjects.has(objectId))
throw new Error('Cannot find object with id = ' + arg.objectId);
const result = [];
for (let obj = this._remoteObjects.get(objectId); obj; obj = obj.proto) {
for (const propertyName of obj.getOwnPropertyNames()) {
const descriptor = obj.getOwnPropertyDescriptor(propertyName);
if (!descriptor.enumerable)
continue;
result.push({
name: propertyName,
value: this._createRemoteObject(descriptor.value),
});
}
}
return result;
}
_getResult(completionValue, exceptionDetails = {}) {
if (!completionValue) {
exceptionDetails.text = 'Evaluation terminated!';
exceptionDetails.stack = '';
return {success: false, obj: null};
}
if (completionValue.throw) {
if (this._global.executeInGlobalWithBindings('e instanceof Error', {e: completionValue.throw}).return) {
exceptionDetails.text = this._global.executeInGlobalWithBindings('e.message', {e: completionValue.throw}).return;
exceptionDetails.stack = this._global.executeInGlobalWithBindings('e.stack', {e: completionValue.throw}).return;
} else {
exceptionDetails.value = this._serialize(completionValue.throw);
}
return {success: false, obj: null};
}
return {success: true, obj: completionValue.return};
}
}
const listenersSymbol = Symbol('listeners');
function createEvent() {
const listeners = new Set();
const subscribeFunction = listener => {
listeners.add(listener);
return () => listeners.delete(listener);
}
subscribeFunction[listenersSymbol] = listeners;
return subscribeFunction;
}
function emitEvent(event, ...args) {
let listeners = event[listenersSymbol];
if (!listeners || !listeners.size)
return;
listeners = new Set(listeners);
for (const listener of listeners)
listener.call(null, ...args);
}
var EXPORTED_SYMBOLS = ['Runtime'];
this.Runtime = Runtime;
| browser_patches/firefox/juggler/content/Runtime.js | 0 | https://github.com/microsoft/playwright/commit/a04c54ac28325e9dd420a6e570bdf7d5af5980ff | [
0.0003214570751879364,
0.00017695562564767897,
0.0001645550219109282,
0.00016920329653657973,
0.00003086735887336545
] |
{
"id": 2,
"code_window": [
"name: secondary tests\n",
"\n",
"on:\n",
" push:\n"
],
"labels": [
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"name: \"tests 2\"\n"
],
"file_path": ".github/workflows/tests_secondary.yml",
"type": "replace",
"edit_start_line_idx": 0
} | root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
| .editorconfig | 0 | https://github.com/microsoft/playwright/commit/a04c54ac28325e9dd420a6e570bdf7d5af5980ff | [
0.00016750270151533186,
0.00016750270151533186,
0.00016750270151533186,
0.00016750270151533186,
0
] |
{
"id": 2,
"code_window": [
"name: secondary tests\n",
"\n",
"on:\n",
" push:\n"
],
"labels": [
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"name: \"tests 2\"\n"
],
"file_path": ".github/workflows/tests_secondary.yml",
"type": "replace",
"edit_start_line_idx": 0
} | # class: Playwright
Playwright module provides a method to launch a browser instance. The following is a typical example of using Playwright
to drive automation:
```js
const { chromium, firefox, webkit } = require('playwright');
(async () => {
const browser = await chromium.launch(); // Or 'firefox' or 'webkit'.
const page = await browser.newPage();
await page.goto('http://example.com');
// other actions...
await browser.close();
})();
```
```java
import com.microsoft.playwright.*;
public class Example {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
BrowserType chromium = playwright.chromium();
Browser browser = chromium.launch();
Page page = browser.newPage();
page.navigate("http://example.com");
// other actions...
browser.close();
}
}
}
```
```python async
import asyncio
from playwright.async_api import async_playwright
async def run(playwright):
chromium = playwright.chromium # or "firefox" or "webkit".
browser = await chromium.launch()
page = await browser.new_page()
await page.goto("http://example.com")
# other actions...
await browser.close()
async def main():
async with async_playwright() as playwright:
await run(playwright)
asyncio.run(main())
```
```python sync
from playwright.sync_api import sync_playwright
def run(playwright):
chromium = playwright.chromium # or "firefox" or "webkit".
browser = chromium.launch()
page = browser.new_page()
page.goto("http://example.com")
# other actions...
browser.close()
with sync_playwright() as playwright:
run(playwright)
```
## property: Playwright.chromium
- type: <[BrowserType]>
This object can be used to launch or connect to Chromium, returning instances of [Browser].
## property: Playwright.devices
* langs: js, python
- type: <[Object]>
Returns a dictionary of devices to be used with [`method: Browser.newContext`] or [`method: Browser.newPage`].
```js
const { webkit, devices } = require('playwright');
const iPhone = devices['iPhone 6'];
(async () => {
const browser = await webkit.launch();
const context = await browser.newContext({
...iPhone
});
const page = await context.newPage();
await page.goto('http://example.com');
// other actions...
await browser.close();
})();
```
```python async
import asyncio
from playwright.async_api import async_playwright
async def run(playwright):
webkit = playwright.webkit
iphone = playwright.devices["iPhone 6"]
browser = await webkit.launch()
context = await browser.new_context(**iphone)
page = await context.new_page()
await page.goto("http://example.com")
# other actions...
await browser.close()
async def main():
async with async_playwright() as playwright:
await run(playwright)
asyncio.run(main())
```
```python sync
from playwright.sync_api import sync_playwright
def run(playwright):
webkit = playwright.webkit
iphone = playwright.devices["iPhone 6"]
browser = webkit.launch()
context = browser.new_context(**iphone)
page = context.new_page()
page.goto("http://example.com")
# other actions...
browser.close()
with sync_playwright() as playwright:
run(playwright)
```
## property: Playwright.errors
* langs: js
- type: <[Object]>
- `TimeoutError` <[function]> A class of [TimeoutError].
Playwright methods might throw errors if they are unable to fulfill a request. For example,
[`method: Page.waitForSelector`] might fail if the selector doesn't match any nodes during the given timeframe.
For certain types of errors Playwright uses specific error classes. These classes are available via
[`playwright.errors`](#playwrighterrors).
An example of handling a timeout error:
```js
try {
await page.waitForSelector('.foo');
} catch (e) {
if (e instanceof playwright.errors.TimeoutError) {
// Do something if this is a timeout.
}
}
```
```python async
try:
await page.wait_for_selector(".foo")
except TimeoutError as e:
# do something if this is a timeout.
```
```python sync
try:
page.wait_for_selector(".foo")
except TimeoutError as e:
# do something if this is a timeout.
```
## property: Playwright.firefox
- type: <[BrowserType]>
This object can be used to launch or connect to Firefox, returning instances of [Browser].
## property: Playwright.selectors
- type: <[Selectors]>
Selectors can be used to install custom selector engines. See
[Working with selectors](./selectors.md) for more information.
## property: Playwright.webkit
- type: <[BrowserType]>
This object can be used to launch or connect to WebKit, returning instances of [Browser].
| docs/src/api/class-playwright.md | 0 | https://github.com/microsoft/playwright/commit/a04c54ac28325e9dd420a6e570bdf7d5af5980ff | [
0.00017184611351694912,
0.00016871806292328984,
0.00016478427278343588,
0.00016895856242626905,
0.0000020290126485633664
] |
{
"id": 3,
"code_window": [
" push:\n",
" branches:\n",
" - master\n",
" - release-*\n",
" pull_request:\n",
" types: [ labeled ]\n",
" branches:\n",
" - master\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" paths-ignore:\n",
" - 'browser_patches/**'\n"
],
"file_path": ".github/workflows/tests_secondary.yml",
"type": "add",
"edit_start_line_idx": 8
} | name: secondary tests
on:
push:
branches:
- master
- release-*
pull_request:
types: [ labeled ]
branches:
- master
- release-*
env:
# Force terminal colors. @see https://www.npmjs.com/package/colors
FORCE_COLOR: 1
FLAKINESS_CONNECTION_STRING: ${{ secrets.FLAKINESS_CONNECTION_STRING }}
jobs:
test_linux:
name: ${{ matrix.os }} (${{ matrix.browser }})
strategy:
fail-fast: false
matrix:
browser: [chromium, firefox, webkit]
os: [ubuntu-18.04]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
- run: npm run build
- run: node lib/cli/cli install-deps ${{ matrix.browser }} chromium
# XVFB-RUN merges both STDOUT and STDERR, whereas we need only STDERR
# Wrap `npm run` in a subshell to redirect STDERR to file.
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash -c "npm run test -- --project=${{ matrix.browser }}"
- run: node tests/config/checkCoverage.js ${{ matrix.browser }}
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: always()
with:
name: ${{ matrix.browser }}-${{ matrix.os }}-test-results
path: test-results
test_mac:
name: ${{ matrix.os }} (${{ matrix.browser }})
strategy:
fail-fast: false
matrix:
os: [macos-10.15, macos-11.0]
browser: [chromium, firefox, webkit]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
DEBUG: extract-zip
- run: npm run build
- run: node lib/cli/cli install-deps ${{ matrix.browser }} chromium
- run: npm run test -- --project=${{ matrix.browser }}
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: ${{ matrix.browser }}-${{ matrix.os }}-test-results
path: test-results
test_win:
name: "Windows"
strategy:
fail-fast: false
matrix:
browser: [chromium, firefox, webkit]
runs-on: windows-latest
steps:
- name: Install Media Pack
shell: powershell
run: Install-WindowsFeature Server-Media-Foundation
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
DEBUG: extract-zip
- run: npm run build
- run: node lib/cli/cli install-deps
- run: npm run test -- --project=${{ matrix.browser }}
shell: bash
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
shell: bash
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: ${{ matrix.browser }}-win-test-results
path: test-results
test-package-installations:
runs-on: ubuntu-20.04
strategy:
fail-fast: false
matrix:
node_version:
- "^12.0.0"
- "^14.1.0" # pre 14.1, zip extraction was broken (https://github.com/microsoft/playwright/issues/1988)
timeout-minutes: 20
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node_version }}
- run: npm ci
env:
DEBUG: extract-zip
- run: npm run build
- run: node lib/cli/cli install-deps
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash packages/installation-tests/installation-tests.sh
headful_linux:
name: "Headful Linux"
strategy:
fail-fast: false
matrix:
browser: [chromium, firefox, webkit]
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
- run: npm run build
- run: node lib/cli/cli install-deps ${{ matrix.browser }} chromium
# XVFB-RUN merges both STDOUT and STDERR, whereas we need only STDERR
# Wrap `npm run` in a subshell to redirect STDERR to file.
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash -c "npm run test -- --project=${{ matrix.browser }} --headed"
if: ${{ always() }}
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: headful-${{ matrix.browser }}-linux-test-results
path: test-results
transport_linux:
name: "Transport"
strategy:
fail-fast: false
matrix:
mode: [driver, service]
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
- run: npm run build
- run: node lib/cli/cli install-deps chromium
# XVFB-RUN merges both STDOUT and STDERR, whereas we need only STDERR
# Wrap `npm run` in a subshell to redirect STDERR to file.
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash -c "npm run ctest -- --mode=${{ matrix.mode }}"
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: mode-${{ matrix.mode }}-linux-test-results
path: test-results
video_linux:
name: "Video Linux"
strategy:
fail-fast: false
matrix:
browser: [chromium, firefox, webkit]
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
- run: npm run build
- run: node lib/cli/cli install-deps ${{ matrix.browser }} chromium
# XVFB-RUN merges both STDOUT and STDERR, whereas we need only STDERR
# Wrap `npm run` in a subshell to redirect STDERR to file.
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash -c "npm run test -- --project=${{ matrix.browser }} --video"
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: video-${{ matrix.browser }}-linux-test-results
path: test-results
test_android:
name: Android Emulator (shard ${{ matrix.shard }})
strategy:
fail-fast: false
matrix:
shard: [1, 2]
runs-on: macos-10.15
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 14
- run: npm ci
- run: npm run build
- run: node lib/cli/cli install-deps
- name: Create Android Emulator
run: utils/avd_recreate.sh
- name: Start Android Emulator
run: utils/avd_start.sh
- name: Run tests
run: npm run atest -- --shard=${{ matrix.shard }}/2
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: android-test-results
path: test-results
chrome_stable_linux:
name: "Chrome Stable (Linux)"
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- name: Install Chrome Stable
run: sudo apt install google-chrome-stable
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
- run: node lib/cli/cli install-deps chromium
# This only created problems, should we move ffmpeg back into npm?
- run: node lib/cli/cli install ffmpeg
# XVFB-RUN merges both STDOUT and STDERR, whereas we need only STDERR
# Wrap `npm run` in a subshell to redirect STDERR to file.
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash -c "npm run ctest -- --channel=chrome"
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: chrome-stable-linux-test-results
path: test-results
chrome_stable_win:
name: "Chrome Stable (Win)"
runs-on: windows-latest
steps:
- name: Install Media Pack
shell: powershell
run: Install-WindowsFeature Server-Media-Foundation
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
# This only created problems, should we move ffmpeg back into npm?
- run: node lib/cli/cli install ffmpeg
- run: npm run ctest -- --channel=chrome
shell: bash
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
shell: bash
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: chrome-stable-win-test-results
path: test-results
chrome_stable_mac:
name: "Chrome Stable (Mac)"
runs-on: macos-10.15
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
# This only created problems, should we move ffmpeg back into npm?
- run: node lib/cli/cli install ffmpeg
- run: npm run ctest -- --channel=chrome
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: chrome-stable-mac-test-results
path: test-results
firefox_stable_linux:
name: "Firefox Stable (Linux)"
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
- run: node lib/cli/cli install-deps firefox
- run: node lib/cli/cli install ffmpeg firefox-stable chromium
# XVFB-RUN merges both STDOUT and STDERR, whereas we need only STDERR
# Wrap `npm run` in a subshell to redirect STDERR to file.
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash -c "npm run ftest -- --channel=firefox-stable"
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: firefox-stable-linux-test-results
path: test-results
firefox_stable_win:
name: "Firefox Stable (Win)"
runs-on: windows-latest
steps:
- name: Install Media Pack
shell: powershell
run: Install-WindowsFeature Server-Media-Foundation
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
- run: node lib/cli/cli install ffmpeg firefox-stable chromium
- run: npm run ftest -- --channel=firefox-stable
shell: bash
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
shell: bash
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: firefox-stable-win-test-results
path: test-results
firefox_stable_mac:
name: "Firefox Stable (Mac)"
runs-on: macos-10.15
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
- run: node lib/cli/cli install ffmpeg firefox-stable chromium
- run: npm run ftest -- --channel=firefox-stable
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: firefox-stable-mac-test-results
path: test-results
edge_stable_win:
name: "Edge Stable (Win)"
runs-on: windows-latest
steps:
- name: Install Media Pack
shell: powershell
run: Install-WindowsFeature Server-Media-Foundation
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
# This only created problems, should we move ffmpeg back into npm?
- run: node lib/cli/cli install ffmpeg
- run: npm run ctest -- --channel=msedge
shell: bash
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: edge-stable-win-test-results
path: test-results
test_electron:
name: "Electron Linux"
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
- run: npm run build
- run: node lib/cli/cli install-deps chromium
# XVFB-RUN merges both STDOUT and STDERR, whereas we need only STDERR
# Wrap `npm run` in a subshell to redirect STDERR to file.
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash -c "npm run etest"
- run: node tests/config/checkCoverage.js electron
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: electron-linux-test-results
path: test-results
chrome_beta_linux:
name: "Chrome Beta (Linux)"
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- run: ./utils/install-chrome-beta/reinstall_linux.sh
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
- run: node lib/cli/cli install-deps chromium
- run: node lib/cli/cli install ffmpeg
# XVFB-RUN merges both STDOUT and STDERR, whereas we need only STDERR
# Wrap `npm run` in a subshell to redirect STDERR to file.
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- bash -c "npm run ctest -- --channel=chrome-beta"
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: chrome-beta-linux-test-results
path: test-results
chrome_beta_win:
name: "Chrome Beta (Win)"
runs-on: windows-latest
steps:
- name: Install Media Pack
shell: powershell
run: Install-WindowsFeature Server-Media-Foundation
- name: Install Chrome Beta
shell: powershell
run: choco install -y googlechromebeta --pre --force
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
- run: node lib/cli/cli install ffmpeg
- run: npm run ctest -- --channel=chrome-beta
shell: bash
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
shell: bash
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: chrome-beta-win-test-results
path: test-results
chrome_beta_mac:
name: "Chrome Beta (Mac)"
runs-on: macos-10.15
steps:
- uses: actions/checkout@v2
- run: ./utils/install-chrome-beta/reinstall_mac.sh
- uses: actions/setup-node@v2
with:
node-version: 12
- run: npm ci
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npm run build
- run: node lib/cli/cli install ffmpeg
- run: npm run ctest -- --channel=chrome-beta
- run: ./utils/upload_flakiness_dashboard.sh ./test-results/report.json
if: always()
- uses: actions/upload-artifact@v1
if: ${{ always() }}
with:
name: chrome-beta-mac-test-results
path: test-results
| .github/workflows/tests_secondary.yml | 1 | https://github.com/microsoft/playwright/commit/a04c54ac28325e9dd420a6e570bdf7d5af5980ff | [
0.9603012800216675,
0.018656400963664055,
0.00016537989722564816,
0.00017208702047355473,
0.13185672461986542
] |
{
"id": 3,
"code_window": [
" push:\n",
" branches:\n",
" - master\n",
" - release-*\n",
" pull_request:\n",
" types: [ labeled ]\n",
" branches:\n",
" - master\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" paths-ignore:\n",
" - 'browser_patches/**'\n"
],
"file_path": ".github/workflows/tests_secondary.yml",
"type": "add",
"edit_start_line_idx": 8
} | # -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
# vim: set filetype=python:
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
Classes = [
{
'cid': '{d8c4d9e0-9462-445e-9e43-68d3872ad1de}',
'contract_ids': ['@mozilla.org/juggler/screencast;1'],
'type': 'nsIScreencastService',
'constructor': 'mozilla::nsScreencastService::GetSingleton',
'headers': ['/juggler/screencast/nsScreencastService.h'],
},
]
| browser_patches/firefox-stable/juggler/screencast/components.conf | 0 | https://github.com/microsoft/playwright/commit/a04c54ac28325e9dd420a6e570bdf7d5af5980ff | [
0.00017161914729513228,
0.0001704931491985917,
0.0001693671365501359,
0.0001704931491985917,
0.0000011260053724981844
] |
{
"id": 3,
"code_window": [
" push:\n",
" branches:\n",
" - master\n",
" - release-*\n",
" pull_request:\n",
" types: [ labeled ]\n",
" branches:\n",
" - master\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" paths-ignore:\n",
" - 'browser_patches/**'\n"
],
"file_path": ".github/workflows/tests_secondary.yml",
"type": "add",
"edit_start_line_idx": 8
} | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
// Note: this file should be loadabale with eval() into worker environment.
// Avoid Components.*, ChromeUtils and global const variables.
const SIMPLE_CHANNEL_MESSAGE_NAME = 'juggler:simplechannel';
class SimpleChannel {
static createForMessageManager(name, mm) {
const channel = new SimpleChannel(name);
const messageListener = {
receiveMessage: message => channel._onMessage(message.data)
};
mm.addMessageListener(SIMPLE_CHANNEL_MESSAGE_NAME, messageListener);
channel.setTransport({
sendMessage: obj => mm.sendAsyncMessage(SIMPLE_CHANNEL_MESSAGE_NAME, obj),
dispose: () => mm.removeMessageListener(SIMPLE_CHANNEL_MESSAGE_NAME, messageListener),
});
return channel;
}
constructor(name) {
this._name = name;
this._messageId = 0;
this._connectorId = 0;
this._pendingMessages = new Map();
this._handlers = new Map();
this._bufferedIncomingMessages = [];
this._bufferedOutgoingMessages = [];
this.transport = {
sendMessage: null,
dispose: null,
};
this._ready = false;
this._disposed = false;
}
setTransport(transport) {
this.transport = transport;
// connection handshake:
// 1. There are two channel ends in different processes.
// 2. Both ends start in the `ready = false` state, meaning that they will
// not send any messages over transport.
// 3. Once channel end is created, it sends `READY` message to the other end.
// 4. Eventually, at least one of the ends receives `READY` message and responds with
// `READY_ACK`. We assume at least one of the ends will receive "READY" event from the other, since
// channel ends have a "parent-child" relation, i.e. one end is always created before the other one.
// 5. Once channel end receives either `READY` or `READY_ACK`, it transitions to `ready` state.
this.transport.sendMessage('READY');
}
_markAsReady() {
if (this._ready)
return;
this._ready = true;
for (const msg of this._bufferedOutgoingMessages)
this.transport.sendMessage(msg);
this._bufferedOutgoingMessages = [];
}
dispose() {
if (this._disposed)
return;
this._disposed = true;
for (const {resolve, reject, methodName} of this._pendingMessages.values())
reject(new Error(`Failed "${methodName}": ${this._name} is disposed.`));
this._pendingMessages.clear();
this._handlers.clear();
this.transport.dispose();
}
_rejectCallbacksFromConnector(connectorId) {
for (const [messageId, callback] of this._pendingMessages) {
if (callback.connectorId === connectorId) {
callback.reject(new Error(`Failed "${callback.methodName}": connector for namespace "${callback.namespace}" in channel "${this._name}" is disposed.`));
this._pendingMessages.delete(messageId);
}
}
}
connect(namespace) {
const connectorId = ++this._connectorId;
return {
send: (...args) => this._send(namespace, connectorId, ...args),
emit: (...args) => void this._send(namespace, connectorId, ...args).catch(e => {}),
dispose: () => this._rejectCallbacksFromConnector(connectorId),
};
}
register(namespace, handler) {
if (this._handlers.has(namespace))
throw new Error('ERROR: double-register for namespace ' + namespace);
this._handlers.set(namespace, handler);
// Try to re-deliver all pending messages.
const bufferedRequests = this._bufferedIncomingMessages;
this._bufferedIncomingMessages = [];
for (const data of bufferedRequests) {
this._onMessage(data);
}
return () => this.unregister(namespace);
}
unregister(namespace) {
this._handlers.delete(namespace);
}
/**
* @param {string} namespace
* @param {number} connectorId
* @param {string} methodName
* @param {...*} params
* @return {!Promise<*>}
*/
async _send(namespace, connectorId, methodName, ...params) {
if (this._disposed)
throw new Error(`ERROR: channel ${this._name} is already disposed! Cannot send "${methodName}" to "${namespace}"`);
const id = ++this._messageId;
const promise = new Promise((resolve, reject) => {
this._pendingMessages.set(id, {connectorId, resolve, reject, methodName, namespace});
});
const message = {requestId: id, methodName, params, namespace};
if (this._ready)
this.transport.sendMessage(message);
else
this._bufferedOutgoingMessages.push(message);
return promise;
}
async _onMessage(data) {
if (data === 'READY') {
this.transport.sendMessage('READY_ACK');
this._markAsReady();
return;
}
if (data === 'READY_ACK') {
this._markAsReady();
return;
}
if (data.responseId) {
const {resolve, reject} = this._pendingMessages.get(data.responseId);
this._pendingMessages.delete(data.responseId);
if (data.error)
reject(new Error(data.error));
else
resolve(data.result);
} else if (data.requestId) {
const namespace = data.namespace;
const handler = this._handlers.get(namespace);
if (!handler) {
this._bufferedIncomingMessages.push(data);
return;
}
const method = handler[data.methodName];
if (!method) {
this.transport.sendMessage({responseId: data.requestId, error: `error in channel "${this._name}": No method "${data.methodName}" in namespace "${namespace}"`});
return;
}
try {
const result = await method.call(handler, ...data.params);
this.transport.sendMessage({responseId: data.requestId, result});
} catch (error) {
this.transport.sendMessage({responseId: data.requestId, error: `error in channel "${this._name}": exception while running method "${data.methodName}" in namespace "${namespace}": ${error.message} ${error.stack}`});
return;
}
} else {
dump(`
ERROR: unknown message in channel "${this._name}": ${JSON.stringify(data)}
`);
}
}
}
var EXPORTED_SYMBOLS = ['SimpleChannel'];
this.SimpleChannel = SimpleChannel;
| browser_patches/firefox-stable/juggler/SimpleChannel.js | 0 | https://github.com/microsoft/playwright/commit/a04c54ac28325e9dd420a6e570bdf7d5af5980ff | [
0.00017749685503076762,
0.00017163132724817842,
0.0001642195857129991,
0.0001723768509691581,
0.0000032950724744296167
] |
{
"id": 3,
"code_window": [
" push:\n",
" branches:\n",
" - master\n",
" - release-*\n",
" pull_request:\n",
" types: [ labeled ]\n",
" branches:\n",
" - master\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" paths-ignore:\n",
" - 'browser_patches/**'\n"
],
"file_path": ".github/workflows/tests_secondary.yml",
"type": "add",
"edit_start_line_idx": 8
} | # -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
# vim: set filetype=python:
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
XPIDL_SOURCES += [
'nsIRemoteDebuggingPipe.idl',
]
XPIDL_MODULE = 'jugglerpipe'
SOURCES += [
'nsRemoteDebuggingPipe.cpp',
]
XPCOM_MANIFESTS += [
'components.conf',
]
LOCAL_INCLUDES += [
]
FINAL_LIBRARY = 'xul'
| browser_patches/firefox/juggler/pipe/moz.build | 0 | https://github.com/microsoft/playwright/commit/a04c54ac28325e9dd420a6e570bdf7d5af5980ff | [
0.00017211832164321095,
0.0001700841821730137,
0.00016714754747226834,
0.000170986691955477,
0.0000021272887806844665
] |
{
"id": 0,
"code_window": [
" ComputedRef,\n",
" ReactiveEffect\n",
"} from '@vue/reactivity'\n",
"\n",
"import { currentInstance } from './component'\n",
"\n",
"// record effects created during a component's setup() so that they can be\n",
"// stopped when the component unmounts\n",
"export function recordEffect(effect: ReactiveEffect) {\n",
" if (currentInstance) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { isFunction } from '@vue/shared'\n"
],
"file_path": "packages/runtime-core/src/apiState.ts",
"type": "add",
"edit_start_line_idx": 28
} | import {
effect,
stop,
isRef,
Ref,
ReactiveEffectOptions
} from '@vue/reactivity'
import { queueJob, queuePostFlushCb } from './scheduler'
import { EMPTY_OBJ, isObject, isArray } from '@vue/shared'
import { recordEffect } from './apiState'
export interface WatchOptions {
lazy?: boolean
flush?: 'pre' | 'post' | 'sync'
deep?: boolean
onTrack?: ReactiveEffectOptions['onTrack']
onTrigger?: ReactiveEffectOptions['onTrigger']
}
type StopHandle = () => void
type WatcherSource<T = any> = Ref<T> | (() => T)
type MapSources<T> = {
[K in keyof T]: T[K] extends WatcherSource<infer V> ? V : never
}
type CleanupRegistrator = (invalidate: () => void) => void
type SimpleEffect = (onCleanup: CleanupRegistrator) => void
const invoke = (fn: Function) => fn()
export function watch(effect: SimpleEffect, options?: WatchOptions): StopHandle
export function watch<T>(
source: WatcherSource<T>,
cb: (newValue: T, oldValue: T, onCleanup: CleanupRegistrator) => any,
options?: WatchOptions
): StopHandle
export function watch<T extends WatcherSource<unknown>[]>(
sources: T,
cb: (
newValues: MapSources<T>,
oldValues: MapSources<T>,
onCleanup: CleanupRegistrator
) => any,
options?: WatchOptions
): StopHandle
// implementation
export function watch(
effectOrSource:
| WatcherSource<unknown>
| WatcherSource<unknown>[]
| SimpleEffect,
effectOrOptions?:
| ((value: any, oldValue: any, onCleanup: CleanupRegistrator) => any)
| WatchOptions,
options?: WatchOptions
): StopHandle {
if (typeof effectOrOptions === 'function') {
// effect callback as 2nd argument - this is a source watcher
return doWatch(effectOrSource, effectOrOptions, options)
} else {
// 2nd argument is either missing or an options object
// - this is a simple effect watcher
return doWatch(effectOrSource, null, effectOrOptions)
}
}
function doWatch(
source: WatcherSource | WatcherSource[] | SimpleEffect,
cb:
| ((newValue: any, oldValue: any, onCleanup: CleanupRegistrator) => any)
| null,
{ lazy, deep, flush, onTrack, onTrigger }: WatchOptions = EMPTY_OBJ
): StopHandle {
const scheduler =
flush === 'sync' ? invoke : flush === 'pre' ? queueJob : queuePostFlushCb
const baseGetter = isArray(source)
? () => source.map(s => (isRef(s) ? s.value : s()))
: isRef(source)
? () => source.value
: () => source(registerCleanup)
const getter = deep ? () => traverse(baseGetter()) : baseGetter
let cleanup: any
const registerCleanup: CleanupRegistrator = (fn: () => void) => {
// TODO wrap the cleanup fn for error handling
cleanup = runner.onStop = fn
}
let oldValue: any
const applyCb = cb
? () => {
const newValue = runner()
if (deep || newValue !== oldValue) {
// cleanup before running cb again
if (cleanup) {
cleanup()
}
// TODO handle error (including ASYNC)
try {
cb(newValue, oldValue, registerCleanup)
} catch (e) {}
oldValue = newValue
}
}
: void 0
const runner = effect(getter, {
lazy: true,
// so it runs before component update effects in pre flush mode
computed: true,
onTrack,
onTrigger,
scheduler: applyCb ? () => scheduler(applyCb) : void 0
})
if (!lazy) {
applyCb && scheduler(applyCb)
} else {
oldValue = runner()
}
recordEffect(runner)
return () => {
stop(runner)
}
}
function traverse(value: any, seen: Set<any> = new Set()) {
if (!isObject(value) || seen.has(value)) {
return
}
seen.add(value)
if (isArray(value)) {
for (let i = 0; i < value.length; i++) {
traverse(value[i], seen)
}
} else if (value instanceof Map || value instanceof Set) {
;(value as any).forEach((v: any) => {
traverse(v, seen)
})
} else {
for (const key in value) {
traverse(value[key], seen)
}
}
return value
}
| packages/runtime-core/src/apiWatch.ts | 1 | https://github.com/vuejs/core/commit/36ab2ab9806d85653f928446316158538f0c840c | [
0.9988294243812561,
0.12511545419692993,
0.00016301346477121115,
0.00017691036919131875,
0.3301127552986145
] |
{
"id": 0,
"code_window": [
" ComputedRef,\n",
" ReactiveEffect\n",
"} from '@vue/reactivity'\n",
"\n",
"import { currentInstance } from './component'\n",
"\n",
"// record effects created during a component's setup() so that they can be\n",
"// stopped when the component unmounts\n",
"export function recordEffect(effect: ReactiveEffect) {\n",
" if (currentInstance) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { isFunction } from '@vue/shared'\n"
],
"file_path": "packages/runtime-core/src/apiState.ts",
"type": "add",
"edit_start_line_idx": 28
} | {
"private": true,
"workspaces": [
"packages/*"
],
"scripts": {
"dev": "node scripts/dev.js",
"build": "node scripts/build.js",
"size": "node scripts/build.js runtime-dom -f esm-browser",
"lint": "prettier --write --parser typescript 'packages/**/*.ts'",
"test": "jest"
},
"gitHooks": {
"pre-commit": "lint-staged",
"commit-msg": "node scripts/verifyCommit.js"
},
"lint-staged": {
"*.js": [
"prettier --write",
"git add"
],
"*.ts": [
"prettier --parser=typescript --write",
"git add"
]
},
"devDependencies": {
"@types/jest": "^23.3.2",
"chalk": "^2.4.1",
"dts-bundle": "^0.7.3",
"execa": "^1.0.0",
"fs-extra": "^7.0.0",
"jest": "^23.6.0",
"lerna": "^3.4.0",
"lint-staged": "^7.2.2",
"minimist": "^1.2.0",
"prettier": "^1.14.2",
"rollup": "^0.65.0",
"rollup-plugin-alias": "^1.4.0",
"rollup-plugin-replace": "^2.0.0",
"rollup-plugin-terser": "^2.0.2",
"rollup-plugin-typescript2": "^0.17.0",
"ts-jest": "^23.10.0",
"typescript": "^3.5.0",
"yorkie": "^2.0.0"
}
}
| package.json | 0 | https://github.com/vuejs/core/commit/36ab2ab9806d85653f928446316158538f0c840c | [
0.00017656305863056332,
0.00017561095592100173,
0.00017479098460171372,
0.00017554058285895735,
6.028560051163367e-7
] |
{
"id": 0,
"code_window": [
" ComputedRef,\n",
" ReactiveEffect\n",
"} from '@vue/reactivity'\n",
"\n",
"import { currentInstance } from './component'\n",
"\n",
"// record effects created during a component's setup() so that they can be\n",
"// stopped when the component unmounts\n",
"export function recordEffect(effect: ReactiveEffect) {\n",
" if (currentInstance) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { isFunction } from '@vue/shared'\n"
],
"file_path": "packages/runtime-core/src/apiState.ts",
"type": "add",
"edit_start_line_idx": 28
} | semi: false
singleQuote: true
printWidth: 80
| .prettierrc | 0 | https://github.com/vuejs/core/commit/36ab2ab9806d85653f928446316158538f0c840c | [
0.00017766159726306796,
0.00017766159726306796,
0.00017766159726306796,
0.00017766159726306796,
0
] |
{
"id": 0,
"code_window": [
" ComputedRef,\n",
" ReactiveEffect\n",
"} from '@vue/reactivity'\n",
"\n",
"import { currentInstance } from './component'\n",
"\n",
"// record effects created during a component's setup() so that they can be\n",
"// stopped when the component unmounts\n",
"export function recordEffect(effect: ReactiveEffect) {\n",
" if (currentInstance) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { isFunction } from '@vue/shared'\n"
],
"file_path": "packages/runtime-core/src/apiState.ts",
"type": "add",
"edit_start_line_idx": 28
} | import { reactive, immutable, toRaw } from './reactive'
import { OperationTypes } from './operations'
import { track, trigger } from './effect'
import { LOCKED } from './lock'
import { isObject } from '@vue/shared'
import { isRef } from './ref'
const hasOwnProperty = Object.prototype.hasOwnProperty
const builtInSymbols = new Set(
Object.getOwnPropertyNames(Symbol)
.map(key => (Symbol as any)[key])
.filter(value => typeof value === 'symbol')
)
function createGetter(isImmutable: boolean) {
return function get(target: any, key: string | symbol, receiver: any) {
const res = Reflect.get(target, key, receiver)
if (typeof key === 'symbol' && builtInSymbols.has(key)) {
return res
}
if (isRef(res)) {
return res.value
}
track(target, OperationTypes.GET, key)
return isObject(res)
? isImmutable
? // need to lazy access immutable and reactive here to avoid
// circular dependency
immutable(res)
: reactive(res)
: res
}
}
function set(
target: any,
key: string | symbol,
value: any,
receiver: any
): boolean {
value = toRaw(value)
const hadKey = hasOwnProperty.call(target, key)
const oldValue = target[key]
if (isRef(oldValue) && !isRef(value)) {
oldValue.value = value
return true
}
const result = Reflect.set(target, key, value, receiver)
// don't trigger if target is something up in the prototype chain of original
if (target === toRaw(receiver)) {
/* istanbul ignore else */
if (__DEV__) {
const extraInfo = { oldValue, newValue: value }
if (!hadKey) {
trigger(target, OperationTypes.ADD, key, extraInfo)
} else if (value !== oldValue) {
trigger(target, OperationTypes.SET, key, extraInfo)
}
} else {
if (!hadKey) {
trigger(target, OperationTypes.ADD, key)
} else if (value !== oldValue) {
trigger(target, OperationTypes.SET, key)
}
}
}
return result
}
function deleteProperty(target: any, key: string | symbol): boolean {
const hadKey = hasOwnProperty.call(target, key)
const oldValue = target[key]
const result = Reflect.deleteProperty(target, key)
if (hadKey) {
/* istanbul ignore else */
if (__DEV__) {
trigger(target, OperationTypes.DELETE, key, { oldValue })
} else {
trigger(target, OperationTypes.DELETE, key)
}
}
return result
}
function has(target: any, key: string | symbol): boolean {
const result = Reflect.has(target, key)
track(target, OperationTypes.HAS, key)
return result
}
function ownKeys(target: any): (string | number | symbol)[] {
track(target, OperationTypes.ITERATE)
return Reflect.ownKeys(target)
}
export const mutableHandlers: ProxyHandler<any> = {
get: createGetter(false),
set,
deleteProperty,
has,
ownKeys
}
export const immutableHandlers: ProxyHandler<any> = {
get: createGetter(true),
set(target: any, key: string | symbol, value: any, receiver: any): boolean {
if (LOCKED) {
if (__DEV__) {
console.warn(
`Set operation on key "${key as any}" failed: target is immutable.`,
target
)
}
return true
} else {
return set(target, key, value, receiver)
}
},
deleteProperty(target: any, key: string | symbol): boolean {
if (LOCKED) {
if (__DEV__) {
console.warn(
`Delete operation on key "${key as any}" failed: target is immutable.`,
target
)
}
return true
} else {
return deleteProperty(target, key)
}
},
has,
ownKeys
}
| packages/reactivity/src/baseHandlers.ts | 0 | https://github.com/vuejs/core/commit/36ab2ab9806d85653f928446316158538f0c840c | [
0.00018700103100854903,
0.0001741313171805814,
0.0001669404882704839,
0.00017380318604409695,
0.000004406545940582873
] |
{
"id": 1,
"code_window": [
" ;(currentInstance.effects || (currentInstance.effects = [])).push(effect)\n",
" }\n",
"}\n",
"\n",
"// a wrapped version of raw computed to tear it down at component unmount\n",
"export function computed<T, C = null>(\n",
" getter: () => T,\n",
" setter?: (v: T) => void\n",
"): ComputedRef<T> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"interface ComputedOptions<T> {\n",
" get: () => T\n",
" set: (v: T) => void\n",
"}\n",
"\n",
"export function computed<T>(\n",
" getterOrOptions: (() => T) | ComputedOptions<T>\n"
],
"file_path": "packages/runtime-core/src/apiState.ts",
"type": "replace",
"edit_start_line_idx": 37
} | import {
effect,
stop,
isRef,
Ref,
ReactiveEffectOptions
} from '@vue/reactivity'
import { queueJob, queuePostFlushCb } from './scheduler'
import { EMPTY_OBJ, isObject, isArray } from '@vue/shared'
import { recordEffect } from './apiState'
export interface WatchOptions {
lazy?: boolean
flush?: 'pre' | 'post' | 'sync'
deep?: boolean
onTrack?: ReactiveEffectOptions['onTrack']
onTrigger?: ReactiveEffectOptions['onTrigger']
}
type StopHandle = () => void
type WatcherSource<T = any> = Ref<T> | (() => T)
type MapSources<T> = {
[K in keyof T]: T[K] extends WatcherSource<infer V> ? V : never
}
type CleanupRegistrator = (invalidate: () => void) => void
type SimpleEffect = (onCleanup: CleanupRegistrator) => void
const invoke = (fn: Function) => fn()
export function watch(effect: SimpleEffect, options?: WatchOptions): StopHandle
export function watch<T>(
source: WatcherSource<T>,
cb: (newValue: T, oldValue: T, onCleanup: CleanupRegistrator) => any,
options?: WatchOptions
): StopHandle
export function watch<T extends WatcherSource<unknown>[]>(
sources: T,
cb: (
newValues: MapSources<T>,
oldValues: MapSources<T>,
onCleanup: CleanupRegistrator
) => any,
options?: WatchOptions
): StopHandle
// implementation
export function watch(
effectOrSource:
| WatcherSource<unknown>
| WatcherSource<unknown>[]
| SimpleEffect,
effectOrOptions?:
| ((value: any, oldValue: any, onCleanup: CleanupRegistrator) => any)
| WatchOptions,
options?: WatchOptions
): StopHandle {
if (typeof effectOrOptions === 'function') {
// effect callback as 2nd argument - this is a source watcher
return doWatch(effectOrSource, effectOrOptions, options)
} else {
// 2nd argument is either missing or an options object
// - this is a simple effect watcher
return doWatch(effectOrSource, null, effectOrOptions)
}
}
function doWatch(
source: WatcherSource | WatcherSource[] | SimpleEffect,
cb:
| ((newValue: any, oldValue: any, onCleanup: CleanupRegistrator) => any)
| null,
{ lazy, deep, flush, onTrack, onTrigger }: WatchOptions = EMPTY_OBJ
): StopHandle {
const scheduler =
flush === 'sync' ? invoke : flush === 'pre' ? queueJob : queuePostFlushCb
const baseGetter = isArray(source)
? () => source.map(s => (isRef(s) ? s.value : s()))
: isRef(source)
? () => source.value
: () => source(registerCleanup)
const getter = deep ? () => traverse(baseGetter()) : baseGetter
let cleanup: any
const registerCleanup: CleanupRegistrator = (fn: () => void) => {
// TODO wrap the cleanup fn for error handling
cleanup = runner.onStop = fn
}
let oldValue: any
const applyCb = cb
? () => {
const newValue = runner()
if (deep || newValue !== oldValue) {
// cleanup before running cb again
if (cleanup) {
cleanup()
}
// TODO handle error (including ASYNC)
try {
cb(newValue, oldValue, registerCleanup)
} catch (e) {}
oldValue = newValue
}
}
: void 0
const runner = effect(getter, {
lazy: true,
// so it runs before component update effects in pre flush mode
computed: true,
onTrack,
onTrigger,
scheduler: applyCb ? () => scheduler(applyCb) : void 0
})
if (!lazy) {
applyCb && scheduler(applyCb)
} else {
oldValue = runner()
}
recordEffect(runner)
return () => {
stop(runner)
}
}
function traverse(value: any, seen: Set<any> = new Set()) {
if (!isObject(value) || seen.has(value)) {
return
}
seen.add(value)
if (isArray(value)) {
for (let i = 0; i < value.length; i++) {
traverse(value[i], seen)
}
} else if (value instanceof Map || value instanceof Set) {
;(value as any).forEach((v: any) => {
traverse(v, seen)
})
} else {
for (const key in value) {
traverse(value[key], seen)
}
}
return value
}
| packages/runtime-core/src/apiWatch.ts | 1 | https://github.com/vuejs/core/commit/36ab2ab9806d85653f928446316158538f0c840c | [
0.022471655160188675,
0.0017190619837492704,
0.00016636302461847663,
0.0001725782931316644,
0.005371125414967537
] |
{
"id": 1,
"code_window": [
" ;(currentInstance.effects || (currentInstance.effects = [])).push(effect)\n",
" }\n",
"}\n",
"\n",
"// a wrapped version of raw computed to tear it down at component unmount\n",
"export function computed<T, C = null>(\n",
" getter: () => T,\n",
" setter?: (v: T) => void\n",
"): ComputedRef<T> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"interface ComputedOptions<T> {\n",
" get: () => T\n",
" set: (v: T) => void\n",
"}\n",
"\n",
"export function computed<T>(\n",
" getterOrOptions: (() => T) | ComputedOptions<T>\n"
],
"file_path": "packages/runtime-core/src/apiState.ts",
"type": "replace",
"edit_start_line_idx": 37
} | {
"name": "@vue/server-renderer",
"version": "3.0.0-alpha.1",
"description": "@vue/server-renderer",
"main": "index.js",
"types": "dist/index.d.ts",
"buildOptions": {
"formats": ["cjs"]
},
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/vue.git"
},
"keywords": [
"vue"
],
"author": "Evan You",
"license": "MIT",
"bugs": {
"url": "https://github.com/vuejs/vue/issues"
},
"homepage": "https://github.com/vuejs/vue/tree/dev/packages/server-renderer#readme"
}
| packages/server-renderer/package.json | 0 | https://github.com/vuejs/core/commit/36ab2ab9806d85653f928446316158538f0c840c | [
0.00017771734565030783,
0.00017596386896912009,
0.0001749419025145471,
0.00017523237329442054,
0.0000012455495834728936
] |
{
"id": 1,
"code_window": [
" ;(currentInstance.effects || (currentInstance.effects = [])).push(effect)\n",
" }\n",
"}\n",
"\n",
"// a wrapped version of raw computed to tear it down at component unmount\n",
"export function computed<T, C = null>(\n",
" getter: () => T,\n",
" setter?: (v: T) => void\n",
"): ComputedRef<T> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"interface ComputedOptions<T> {\n",
" get: () => T\n",
" set: (v: T) => void\n",
"}\n",
"\n",
"export function computed<T>(\n",
" getterOrOptions: (() => T) | ComputedOptions<T>\n"
],
"file_path": "packages/runtime-core/src/apiState.ts",
"type": "replace",
"edit_start_line_idx": 37
} | semi: false
singleQuote: true
printWidth: 80
| .prettierrc | 0 | https://github.com/vuejs/core/commit/36ab2ab9806d85653f928446316158538f0c840c | [
0.00017459310765843838,
0.00017459310765843838,
0.00017459310765843838,
0.00017459310765843838,
0
] |
{
"id": 1,
"code_window": [
" ;(currentInstance.effects || (currentInstance.effects = [])).push(effect)\n",
" }\n",
"}\n",
"\n",
"// a wrapped version of raw computed to tear it down at component unmount\n",
"export function computed<T, C = null>(\n",
" getter: () => T,\n",
" setter?: (v: T) => void\n",
"): ComputedRef<T> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"interface ComputedOptions<T> {\n",
" get: () => T\n",
" set: (v: T) => void\n",
"}\n",
"\n",
"export function computed<T>(\n",
" getterOrOptions: (() => T) | ComputedOptions<T>\n"
],
"file_path": "packages/runtime-core/src/apiState.ts",
"type": "replace",
"edit_start_line_idx": 37
} | import { track, trigger } from './effect'
import { OperationTypes } from './operations'
import { isObject } from '@vue/shared'
import { reactive } from './reactive'
export const knownValues = new WeakSet()
export interface Ref<T> {
value: UnwrapNestedRefs<T>
}
export type UnwrapNestedRefs<T> = T extends Ref<any> ? T : UnwrapRef<T>
const convert = (val: any): any => (isObject(val) ? reactive(val) : val)
export function ref<T>(raw: T): Ref<T> {
raw = convert(raw)
const v = {
get value() {
track(v, OperationTypes.GET, '')
return raw
},
set value(newVal) {
raw = convert(newVal)
trigger(v, OperationTypes.SET, '')
}
}
knownValues.add(v)
return v as any
}
export function isRef(v: any): v is Ref<any> {
return knownValues.has(v)
}
type BailTypes =
| Function
| Map<any, any>
| Set<any>
| WeakMap<any, any>
| WeakSet<any>
// Recursively unwraps nested value bindings.
// Unfortunately TS cannot do recursive types, but this should be enough for
// practical use cases...
export type UnwrapRef<T> = T extends Ref<infer V>
? UnwrapRef2<V>
: T extends Array<infer V>
? Array<UnwrapRef2<V>>
: T extends BailTypes
? T // bail out on types that shouldn't be unwrapped
: T extends object ? { [K in keyof T]: UnwrapRef2<T[K]> } : T
type UnwrapRef2<T> = T extends Ref<infer V>
? UnwrapRef3<V>
: T extends Array<infer V>
? Array<UnwrapRef3<V>>
: T extends BailTypes
? T
: T extends object ? { [K in keyof T]: UnwrapRef3<T[K]> } : T
type UnwrapRef3<T> = T extends Ref<infer V>
? UnwrapRef4<V>
: T extends Array<infer V>
? Array<UnwrapRef4<V>>
: T extends BailTypes
? T
: T extends object ? { [K in keyof T]: UnwrapRef4<T[K]> } : T
type UnwrapRef4<T> = T extends Ref<infer V>
? UnwrapRef5<V>
: T extends Array<infer V>
? Array<UnwrapRef5<V>>
: T extends BailTypes
? T
: T extends object ? { [K in keyof T]: UnwrapRef5<T[K]> } : T
type UnwrapRef5<T> = T extends Ref<infer V>
? UnwrapRef6<V>
: T extends Array<infer V>
? Array<UnwrapRef6<V>>
: T extends BailTypes
? T
: T extends object ? { [K in keyof T]: UnwrapRef6<T[K]> } : T
type UnwrapRef6<T> = T extends Ref<infer V>
? UnwrapRef7<V>
: T extends Array<infer V>
? Array<UnwrapRef7<V>>
: T extends BailTypes
? T
: T extends object ? { [K in keyof T]: UnwrapRef7<T[K]> } : T
type UnwrapRef7<T> = T extends Ref<infer V>
? UnwrapRef8<V>
: T extends Array<infer V>
? Array<UnwrapRef8<V>>
: T extends BailTypes
? T
: T extends object ? { [K in keyof T]: UnwrapRef8<T[K]> } : T
type UnwrapRef8<T> = T extends Ref<infer V>
? UnwrapRef9<V>
: T extends Array<infer V>
? Array<UnwrapRef9<V>>
: T extends BailTypes
? T
: T extends object ? { [K in keyof T]: UnwrapRef9<T[K]> } : T
type UnwrapRef9<T> = T extends Ref<infer V>
? UnwrapRef10<V>
: T extends Array<infer V>
? Array<UnwrapRef10<V>>
: T extends BailTypes
? T
: T extends object ? { [K in keyof T]: UnwrapRef10<T[K]> } : T
type UnwrapRef10<T> = T extends Ref<infer V>
? V // stop recursion
: T
| packages/reactivity/src/ref.ts | 0 | https://github.com/vuejs/core/commit/36ab2ab9806d85653f928446316158538f0c840c | [
0.004918321967124939,
0.000767163815908134,
0.00017082928388845176,
0.0003357634413987398,
0.0012389527400955558
] |
{
"id": 2,
"code_window": [
"): ComputedRef<T> {\n",
" const c = _computed(getter, setter)\n",
" recordEffect(c.effect)\n",
" return c\n",
"}"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" let c: ComputedRef<T>\n",
" if (isFunction(getterOrOptions)) {\n",
" c = _computed(getterOrOptions)\n",
" } else {\n",
" c = _computed(getterOrOptions.get, getterOrOptions.set)\n",
" }\n"
],
"file_path": "packages/runtime-core/src/apiState.ts",
"type": "replace",
"edit_start_line_idx": 42
} | import {
effect,
stop,
isRef,
Ref,
ReactiveEffectOptions
} from '@vue/reactivity'
import { queueJob, queuePostFlushCb } from './scheduler'
import { EMPTY_OBJ, isObject, isArray } from '@vue/shared'
import { recordEffect } from './apiState'
export interface WatchOptions {
lazy?: boolean
flush?: 'pre' | 'post' | 'sync'
deep?: boolean
onTrack?: ReactiveEffectOptions['onTrack']
onTrigger?: ReactiveEffectOptions['onTrigger']
}
type StopHandle = () => void
type WatcherSource<T = any> = Ref<T> | (() => T)
type MapSources<T> = {
[K in keyof T]: T[K] extends WatcherSource<infer V> ? V : never
}
type CleanupRegistrator = (invalidate: () => void) => void
type SimpleEffect = (onCleanup: CleanupRegistrator) => void
const invoke = (fn: Function) => fn()
export function watch(effect: SimpleEffect, options?: WatchOptions): StopHandle
export function watch<T>(
source: WatcherSource<T>,
cb: (newValue: T, oldValue: T, onCleanup: CleanupRegistrator) => any,
options?: WatchOptions
): StopHandle
export function watch<T extends WatcherSource<unknown>[]>(
sources: T,
cb: (
newValues: MapSources<T>,
oldValues: MapSources<T>,
onCleanup: CleanupRegistrator
) => any,
options?: WatchOptions
): StopHandle
// implementation
export function watch(
effectOrSource:
| WatcherSource<unknown>
| WatcherSource<unknown>[]
| SimpleEffect,
effectOrOptions?:
| ((value: any, oldValue: any, onCleanup: CleanupRegistrator) => any)
| WatchOptions,
options?: WatchOptions
): StopHandle {
if (typeof effectOrOptions === 'function') {
// effect callback as 2nd argument - this is a source watcher
return doWatch(effectOrSource, effectOrOptions, options)
} else {
// 2nd argument is either missing or an options object
// - this is a simple effect watcher
return doWatch(effectOrSource, null, effectOrOptions)
}
}
function doWatch(
source: WatcherSource | WatcherSource[] | SimpleEffect,
cb:
| ((newValue: any, oldValue: any, onCleanup: CleanupRegistrator) => any)
| null,
{ lazy, deep, flush, onTrack, onTrigger }: WatchOptions = EMPTY_OBJ
): StopHandle {
const scheduler =
flush === 'sync' ? invoke : flush === 'pre' ? queueJob : queuePostFlushCb
const baseGetter = isArray(source)
? () => source.map(s => (isRef(s) ? s.value : s()))
: isRef(source)
? () => source.value
: () => source(registerCleanup)
const getter = deep ? () => traverse(baseGetter()) : baseGetter
let cleanup: any
const registerCleanup: CleanupRegistrator = (fn: () => void) => {
// TODO wrap the cleanup fn for error handling
cleanup = runner.onStop = fn
}
let oldValue: any
const applyCb = cb
? () => {
const newValue = runner()
if (deep || newValue !== oldValue) {
// cleanup before running cb again
if (cleanup) {
cleanup()
}
// TODO handle error (including ASYNC)
try {
cb(newValue, oldValue, registerCleanup)
} catch (e) {}
oldValue = newValue
}
}
: void 0
const runner = effect(getter, {
lazy: true,
// so it runs before component update effects in pre flush mode
computed: true,
onTrack,
onTrigger,
scheduler: applyCb ? () => scheduler(applyCb) : void 0
})
if (!lazy) {
applyCb && scheduler(applyCb)
} else {
oldValue = runner()
}
recordEffect(runner)
return () => {
stop(runner)
}
}
function traverse(value: any, seen: Set<any> = new Set()) {
if (!isObject(value) || seen.has(value)) {
return
}
seen.add(value)
if (isArray(value)) {
for (let i = 0; i < value.length; i++) {
traverse(value[i], seen)
}
} else if (value instanceof Map || value instanceof Set) {
;(value as any).forEach((v: any) => {
traverse(v, seen)
})
} else {
for (const key in value) {
traverse(value[key], seen)
}
}
return value
}
| packages/runtime-core/src/apiWatch.ts | 1 | https://github.com/vuejs/core/commit/36ab2ab9806d85653f928446316158538f0c840c | [
0.0034027176443487406,
0.0005259031895548105,
0.00016705816960893571,
0.00017452289466746151,
0.0008888409938663244
] |
{
"id": 2,
"code_window": [
"): ComputedRef<T> {\n",
" const c = _computed(getter, setter)\n",
" recordEffect(c.effect)\n",
" return c\n",
"}"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" let c: ComputedRef<T>\n",
" if (isFunction(getterOrOptions)) {\n",
" c = _computed(getterOrOptions)\n",
" } else {\n",
" c = _computed(getterOrOptions.get, getterOrOptions.set)\n",
" }\n"
],
"file_path": "packages/runtime-core/src/apiState.ts",
"type": "replace",
"edit_start_line_idx": 42
} | __tests__/
__mocks__/
dist/packages | packages/runtime-test/.npmignore | 0 | https://github.com/vuejs/core/commit/36ab2ab9806d85653f928446316158538f0c840c | [
0.000178979491465725,
0.000178979491465725,
0.000178979491465725,
0.000178979491465725,
0
] |
{
"id": 2,
"code_window": [
"): ComputedRef<T> {\n",
" const c = _computed(getter, setter)\n",
" recordEffect(c.effect)\n",
" return c\n",
"}"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" let c: ComputedRef<T>\n",
" if (isFunction(getterOrOptions)) {\n",
" c = _computed(getterOrOptions)\n",
" } else {\n",
" c = _computed(getterOrOptions.get, getterOrOptions.set)\n",
" }\n"
],
"file_path": "packages/runtime-core/src/apiState.ts",
"type": "replace",
"edit_start_line_idx": 42
} | // using DOM renderer because this case is mostly DOM-specific
import { h, render, Component, nextTick, cloneVNode } from '@vue/runtime-dom'
describe('attribute fallthrough', () => {
it('everything should be in props when component has no declared props', async () => {
const click = jest.fn()
const childUpdated = jest.fn()
class Hello extends Component {
count: number = 0
inc() {
this.count++
click()
}
render() {
return h(Child, {
foo: 1,
id: 'test',
class: 'c' + this.count,
style: { color: this.count ? 'red' : 'green' },
onClick: this.inc
})
}
}
class Child extends Component<{ [key: string]: any }> {
updated() {
childUpdated()
}
render(props: any) {
return cloneVNode(
h(
'div',
{
class: 'c2',
style: { fontWeight: 'bold' }
},
props.foo
),
props
)
}
}
const root = document.createElement('div')
document.body.appendChild(root)
await render(h(Hello), root)
const node = root.children[0] as HTMLElement
expect(node.getAttribute('id')).toBe('test')
expect(node.getAttribute('foo')).toBe('1')
expect(node.getAttribute('class')).toBe('c2 c0')
expect(node.style.color).toBe('green')
expect(node.style.fontWeight).toBe('bold')
node.dispatchEvent(new CustomEvent('click'))
expect(click).toHaveBeenCalled()
await nextTick()
expect(childUpdated).toHaveBeenCalled()
expect(node.getAttribute('id')).toBe('test')
expect(node.getAttribute('foo')).toBe('1')
expect(node.getAttribute('class')).toBe('c2 c1')
expect(node.style.color).toBe('red')
expect(node.style.fontWeight).toBe('bold')
})
it('should separate in attrs when component has declared props', async () => {
const click = jest.fn()
const childUpdated = jest.fn()
class Hello extends Component {
count = 0
inc() {
this.count++
click()
}
render() {
return h(Child, {
foo: 123,
id: 'test',
class: 'c' + this.count,
style: { color: this.count ? 'red' : 'green' },
onClick: this.inc
})
}
}
class Child extends Component<{ [key: string]: any; foo: number }> {
static props = {
foo: Number
}
updated() {
childUpdated()
}
render() {
return cloneVNode(
h(
'div',
{
class: 'c2',
style: { fontWeight: 'bold' }
},
this.$props.foo
),
this.$attrs
)
}
}
const root = document.createElement('div')
document.body.appendChild(root)
await render(h(Hello), root)
const node = root.children[0] as HTMLElement
// with declared props, any parent attr that isn't a prop falls through
expect(node.getAttribute('id')).toBe('test')
expect(node.getAttribute('class')).toBe('c2 c0')
expect(node.style.color).toBe('green')
expect(node.style.fontWeight).toBe('bold')
node.dispatchEvent(new CustomEvent('click'))
expect(click).toHaveBeenCalled()
// ...while declared ones remain props
expect(node.hasAttribute('foo')).toBe(false)
await nextTick()
expect(childUpdated).toHaveBeenCalled()
expect(node.getAttribute('id')).toBe('test')
expect(node.getAttribute('class')).toBe('c2 c1')
expect(node.style.color).toBe('red')
expect(node.style.fontWeight).toBe('bold')
expect(node.hasAttribute('foo')).toBe(false)
})
it('should fallthrough on multi-nested components', async () => {
const click = jest.fn()
const childUpdated = jest.fn()
const grandChildUpdated = jest.fn()
class Hello extends Component {
count = 0
inc() {
this.count++
click()
}
render() {
return h(Child, {
foo: 1,
id: 'test',
class: 'c' + this.count,
style: { color: this.count ? 'red' : 'green' },
onClick: this.inc
})
}
}
class Child extends Component<{ [key: string]: any; foo: number }> {
updated() {
childUpdated()
}
render() {
return h(GrandChild, this.$props)
}
}
class GrandChild extends Component<{ [key: string]: any; foo: number }> {
static props = {
foo: Number
}
updated() {
grandChildUpdated()
}
render(props: any) {
return cloneVNode(
h(
'div',
{
class: 'c2',
style: { fontWeight: 'bold' }
},
props.foo
),
this.$attrs
)
}
}
const root = document.createElement('div')
document.body.appendChild(root)
await render(h(Hello), root)
const node = root.children[0] as HTMLElement
// with declared props, any parent attr that isn't a prop falls through
expect(node.getAttribute('id')).toBe('test')
expect(node.getAttribute('class')).toBe('c2 c0')
expect(node.style.color).toBe('green')
expect(node.style.fontWeight).toBe('bold')
node.dispatchEvent(new CustomEvent('click'))
expect(click).toHaveBeenCalled()
// ...while declared ones remain props
expect(node.hasAttribute('foo')).toBe(false)
await nextTick()
expect(childUpdated).toHaveBeenCalled()
expect(grandChildUpdated).toHaveBeenCalled()
expect(node.getAttribute('id')).toBe('test')
expect(node.getAttribute('class')).toBe('c2 c1')
expect(node.style.color).toBe('red')
expect(node.style.fontWeight).toBe('bold')
expect(node.hasAttribute('foo')).toBe(false)
})
})
| packages/runtime-core/__tests__/attrsFallthrough.spec.ts | 0 | https://github.com/vuejs/core/commit/36ab2ab9806d85653f928446316158538f0c840c | [
0.00018051393271889538,
0.0001735390687827021,
0.0001677325344644487,
0.00017295597353950143,
0.000003332554342705407
] |
{
"id": 2,
"code_window": [
"): ComputedRef<T> {\n",
" const c = _computed(getter, setter)\n",
" recordEffect(c.effect)\n",
" return c\n",
"}"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" let c: ComputedRef<T>\n",
" if (isFunction(getterOrOptions)) {\n",
" c = _computed(getterOrOptions)\n",
" } else {\n",
" c = _computed(getterOrOptions.get, getterOrOptions.set)\n",
" }\n"
],
"file_path": "packages/runtime-core/src/apiState.ts",
"type": "replace",
"edit_start_line_idx": 42
} | {
"name": "@vue/reactivity",
"version": "3.0.0-alpha.1",
"description": "@vue/reactivity",
"main": "index.js",
"module": "dist/reactivity.esm-bundler.js",
"types": "dist/index.d.ts",
"unpkg": "dist/reactivity.global.js",
"sideEffects": false,
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/vue.git"
},
"buildOptions": {
"name": "VueObserver",
"formats": ["esm", "cjs", "global", "esm-browser"]
},
"keywords": [
"vue"
],
"author": "Evan You",
"license": "MIT",
"bugs": {
"url": "https://github.com/vuejs/vue/issues"
},
"homepage": "https://github.com/vuejs/vue/tree/dev/packages/reactivity#readme"
}
| packages/reactivity/package.json | 0 | https://github.com/vuejs/core/commit/36ab2ab9806d85653f928446316158538f0c840c | [
0.00017824070528149605,
0.0001763525215210393,
0.00017532112542539835,
0.00017549573385622352,
0.0000013370490705710836
] |
{
"id": 3,
"code_window": [
" ReactiveEffectOptions\n",
"} from '@vue/reactivity'\n",
"import { queueJob, queuePostFlushCb } from './scheduler'\n",
"import { EMPTY_OBJ, isObject, isArray } from '@vue/shared'\n",
"import { recordEffect } from './apiState'\n",
"\n",
"export interface WatchOptions {\n",
" lazy?: boolean\n",
" flush?: 'pre' | 'post' | 'sync'\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { EMPTY_OBJ, isObject, isArray, isFunction } from '@vue/shared'\n"
],
"file_path": "packages/runtime-core/src/apiWatch.ts",
"type": "replace",
"edit_start_line_idx": 8
} | export {
ref,
isRef,
reactive,
isReactive,
immutable,
isImmutable,
toRaw,
markImmutable,
markNonReactive,
effect,
// types
ReactiveEffect,
ReactiveEffectOptions,
DebuggerEvent,
OperationTypes,
Ref,
ComputedRef,
UnwrapRef
} from '@vue/reactivity'
import {
computed as _computed,
ComputedRef,
ReactiveEffect
} from '@vue/reactivity'
import { currentInstance } from './component'
// record effects created during a component's setup() so that they can be
// stopped when the component unmounts
export function recordEffect(effect: ReactiveEffect) {
if (currentInstance) {
;(currentInstance.effects || (currentInstance.effects = [])).push(effect)
}
}
// a wrapped version of raw computed to tear it down at component unmount
export function computed<T, C = null>(
getter: () => T,
setter?: (v: T) => void
): ComputedRef<T> {
const c = _computed(getter, setter)
recordEffect(c.effect)
return c
}
| packages/runtime-core/src/apiState.ts | 1 | https://github.com/vuejs/core/commit/36ab2ab9806d85653f928446316158538f0c840c | [
0.004647306632250547,
0.0017797015607357025,
0.0005054419161751866,
0.0009205012465827167,
0.0015350645408034325
] |
{
"id": 3,
"code_window": [
" ReactiveEffectOptions\n",
"} from '@vue/reactivity'\n",
"import { queueJob, queuePostFlushCb } from './scheduler'\n",
"import { EMPTY_OBJ, isObject, isArray } from '@vue/shared'\n",
"import { recordEffect } from './apiState'\n",
"\n",
"export interface WatchOptions {\n",
" lazy?: boolean\n",
" flush?: 'pre' | 'post' | 'sync'\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { EMPTY_OBJ, isObject, isArray, isFunction } from '@vue/shared'\n"
],
"file_path": "packages/runtime-core/src/apiWatch.ts",
"type": "replace",
"edit_start_line_idx": 8
} | export const enum OperationTypes {
// using literal strings instead of numbers so that it's easier to inspect
// debugger events
SET = 'set',
ADD = 'add',
DELETE = 'delete',
CLEAR = 'clear',
GET = 'get',
HAS = 'has',
ITERATE = 'iterate'
}
| packages/reactivity/src/operations.ts | 0 | https://github.com/vuejs/core/commit/36ab2ab9806d85653f928446316158538f0c840c | [
0.00017561744607519358,
0.00016988102288451046,
0.00016414459969382733,
0.00016988102288451046,
0.0000057364231906831264
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.