hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
sequencelengths 5
5
|
---|---|---|---|---|---|
{
"id": 0,
"code_window": [
"import { toggleComment } from './toggleComment';\n",
"import { fetchEditPoint } from './editPoint';\n",
"import { fetchSelectItem } from './selectItem';\n",
"import { evaluateMathExpression } from './evaluateMathExpression';\n",
"import { incrementDecrement } from './incrementDecrement';\n",
"import { LANGUAGE_MODES, getMappingForIncludedLanguages, updateEmmetExtensionsPath } from './util';\n",
"import { reflectCssValue } from './reflectCssValue';\n",
"\n",
"export function activateEmmetExtension(context: vscode.ExtensionContext) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { LANGUAGE_MODES, getMappingForIncludedLanguages, updateEmmetExtensionsPath, getPathBaseName } from './util';\n"
],
"file_path": "extensions/emmet/src/emmetCommon.ts",
"type": "replace",
"edit_start_line_idx": 19
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { dirname, basename, distinctParents, joinPath, normalizePath, isAbsolutePath, relativePath, removeTrailingPathSeparator, hasTrailingPathSeparator, resolvePath, addTrailingPathSeparator, extUri, extUriIgnorePathCase } from 'vs/base/common/resources';
import { URI } from 'vs/base/common/uri';
import { isWindows } from 'vs/base/common/platform';
import { toSlashes } from 'vs/base/common/extpath';
import { win32, posix } from 'vs/base/common/path';
suite('Resources', () => {
test('distinctParents', () => {
// Basic
let resources = [
URI.file('/some/folderA/file.txt'),
URI.file('/some/folderB/file.txt'),
URI.file('/some/folderC/file.txt')
];
let distinct = distinctParents(resources, r => r);
assert.equal(distinct.length, 3);
assert.equal(distinct[0].toString(), resources[0].toString());
assert.equal(distinct[1].toString(), resources[1].toString());
assert.equal(distinct[2].toString(), resources[2].toString());
// Parent / Child
resources = [
URI.file('/some/folderA'),
URI.file('/some/folderA/file.txt'),
URI.file('/some/folderA/child/file.txt'),
URI.file('/some/folderA2/file.txt'),
URI.file('/some/file.txt')
];
distinct = distinctParents(resources, r => r);
assert.equal(distinct.length, 3);
assert.equal(distinct[0].toString(), resources[0].toString());
assert.equal(distinct[1].toString(), resources[3].toString());
assert.equal(distinct[2].toString(), resources[4].toString());
});
test('dirname', () => {
if (isWindows) {
assert.equal(dirname(URI.file('c:\\some\\file\\test.txt')).toString(), 'file:///c%3A/some/file');
assert.equal(dirname(URI.file('c:\\some\\file')).toString(), 'file:///c%3A/some');
assert.equal(dirname(URI.file('c:\\some\\file\\')).toString(), 'file:///c%3A/some');
assert.equal(dirname(URI.file('c:\\some')).toString(), 'file:///c%3A/');
assert.equal(dirname(URI.file('C:\\some')).toString(), 'file:///c%3A/');
assert.equal(dirname(URI.file('c:\\')).toString(), 'file:///c%3A/');
} else {
assert.equal(dirname(URI.file('/some/file/test.txt')).toString(), 'file:///some/file');
assert.equal(dirname(URI.file('/some/file/')).toString(), 'file:///some');
assert.equal(dirname(URI.file('/some/file')).toString(), 'file:///some');
}
assert.equal(dirname(URI.parse('foo://a/some/file/test.txt')).toString(), 'foo://a/some/file');
assert.equal(dirname(URI.parse('foo://a/some/file/')).toString(), 'foo://a/some');
assert.equal(dirname(URI.parse('foo://a/some/file')).toString(), 'foo://a/some');
assert.equal(dirname(URI.parse('foo://a/some')).toString(), 'foo://a/');
assert.equal(dirname(URI.parse('foo://a/')).toString(), 'foo://a/');
assert.equal(dirname(URI.parse('foo://a')).toString(), 'foo://a');
// does not explode (https://github.com/microsoft/vscode/issues/41987)
dirname(URI.from({ scheme: 'file', authority: '/users/someone/portal.h' }));
assert.equal(dirname(URI.parse('foo://a/b/c?q')).toString(), 'foo://a/b?q');
});
test('basename', () => {
if (isWindows) {
assert.equal(basename(URI.file('c:\\some\\file\\test.txt')), 'test.txt');
assert.equal(basename(URI.file('c:\\some\\file')), 'file');
assert.equal(basename(URI.file('c:\\some\\file\\')), 'file');
assert.equal(basename(URI.file('C:\\some\\file\\')), 'file');
} else {
assert.equal(basename(URI.file('/some/file/test.txt')), 'test.txt');
assert.equal(basename(URI.file('/some/file/')), 'file');
assert.equal(basename(URI.file('/some/file')), 'file');
assert.equal(basename(URI.file('/some')), 'some');
}
assert.equal(basename(URI.parse('foo://a/some/file/test.txt')), 'test.txt');
assert.equal(basename(URI.parse('foo://a/some/file/')), 'file');
assert.equal(basename(URI.parse('foo://a/some/file')), 'file');
assert.equal(basename(URI.parse('foo://a/some')), 'some');
assert.equal(basename(URI.parse('foo://a/')), '');
assert.equal(basename(URI.parse('foo://a')), '');
});
test('joinPath', () => {
if (isWindows) {
assert.equal(joinPath(URI.file('c:\\foo\\bar'), '/file.js').toString(), 'file:///c%3A/foo/bar/file.js');
assert.equal(joinPath(URI.file('c:\\foo\\bar\\'), 'file.js').toString(), 'file:///c%3A/foo/bar/file.js');
assert.equal(joinPath(URI.file('c:\\foo\\bar\\'), '/file.js').toString(), 'file:///c%3A/foo/bar/file.js');
assert.equal(joinPath(URI.file('c:\\'), '/file.js').toString(), 'file:///c%3A/file.js');
assert.equal(joinPath(URI.file('c:\\'), 'bar/file.js').toString(), 'file:///c%3A/bar/file.js');
assert.equal(joinPath(URI.file('c:\\foo'), './file.js').toString(), 'file:///c%3A/foo/file.js');
assert.equal(joinPath(URI.file('c:\\foo'), '/./file.js').toString(), 'file:///c%3A/foo/file.js');
assert.equal(joinPath(URI.file('C:\\foo'), '../file.js').toString(), 'file:///c%3A/file.js');
assert.equal(joinPath(URI.file('C:\\foo\\.'), '../file.js').toString(), 'file:///c%3A/file.js');
} else {
assert.equal(joinPath(URI.file('/foo/bar'), '/file.js').toString(), 'file:///foo/bar/file.js');
assert.equal(joinPath(URI.file('/foo/bar'), 'file.js').toString(), 'file:///foo/bar/file.js');
assert.equal(joinPath(URI.file('/foo/bar/'), '/file.js').toString(), 'file:///foo/bar/file.js');
assert.equal(joinPath(URI.file('/'), '/file.js').toString(), 'file:///file.js');
assert.equal(joinPath(URI.file('/foo/bar'), './file.js').toString(), 'file:///foo/bar/file.js');
assert.equal(joinPath(URI.file('/foo/bar'), '/./file.js').toString(), 'file:///foo/bar/file.js');
assert.equal(joinPath(URI.file('/foo/bar'), '../file.js').toString(), 'file:///foo/file.js');
}
assert.equal(joinPath(URI.parse('foo://a/foo/bar')).toString(), 'foo://a/foo/bar');
assert.equal(joinPath(URI.parse('foo://a/foo/bar'), '/file.js').toString(), 'foo://a/foo/bar/file.js');
assert.equal(joinPath(URI.parse('foo://a/foo/bar'), 'file.js').toString(), 'foo://a/foo/bar/file.js');
assert.equal(joinPath(URI.parse('foo://a/foo/bar/'), '/file.js').toString(), 'foo://a/foo/bar/file.js');
assert.equal(joinPath(URI.parse('foo://a/'), '/file.js').toString(), 'foo://a/file.js');
assert.equal(joinPath(URI.parse('foo://a/foo/bar/'), './file.js').toString(), 'foo://a/foo/bar/file.js');
assert.equal(joinPath(URI.parse('foo://a/foo/bar/'), '/./file.js').toString(), 'foo://a/foo/bar/file.js');
assert.equal(joinPath(URI.parse('foo://a/foo/bar/'), '../file.js').toString(), 'foo://a/foo/file.js');
assert.equal(
joinPath(URI.from({ scheme: 'myScheme', authority: 'authority', path: '/path', query: 'query', fragment: 'fragment' }), '/file.js').toString(),
'myScheme://authority/path/file.js?query#fragment');
});
test('normalizePath', () => {
if (isWindows) {
assert.equal(normalizePath(URI.file('c:\\foo\\.\\bar')).toString(), 'file:///c%3A/foo/bar');
assert.equal(normalizePath(URI.file('c:\\foo\\.')).toString(), 'file:///c%3A/foo');
assert.equal(normalizePath(URI.file('c:\\foo\\.\\')).toString(), 'file:///c%3A/foo/');
assert.equal(normalizePath(URI.file('c:\\foo\\..')).toString(), 'file:///c%3A/');
assert.equal(normalizePath(URI.file('c:\\foo\\..\\bar')).toString(), 'file:///c%3A/bar');
assert.equal(normalizePath(URI.file('c:\\foo\\..\\..\\bar')).toString(), 'file:///c%3A/bar');
assert.equal(normalizePath(URI.file('c:\\foo\\foo\\..\\..\\bar')).toString(), 'file:///c%3A/bar');
assert.equal(normalizePath(URI.file('C:\\foo\\foo\\.\\..\\..\\bar')).toString(), 'file:///c%3A/bar');
assert.equal(normalizePath(URI.file('C:\\foo\\foo\\.\\..\\some\\..\\bar')).toString(), 'file:///c%3A/foo/bar');
} else {
assert.equal(normalizePath(URI.file('/foo/./bar')).toString(), 'file:///foo/bar');
assert.equal(normalizePath(URI.file('/foo/.')).toString(), 'file:///foo');
assert.equal(normalizePath(URI.file('/foo/./')).toString(), 'file:///foo/');
assert.equal(normalizePath(URI.file('/foo/..')).toString(), 'file:///');
assert.equal(normalizePath(URI.file('/foo/../bar')).toString(), 'file:///bar');
assert.equal(normalizePath(URI.file('/foo/../../bar')).toString(), 'file:///bar');
assert.equal(normalizePath(URI.file('/foo/foo/../../bar')).toString(), 'file:///bar');
assert.equal(normalizePath(URI.file('/foo/foo/./../../bar')).toString(), 'file:///bar');
assert.equal(normalizePath(URI.file('/foo/foo/./../some/../bar')).toString(), 'file:///foo/bar');
assert.equal(normalizePath(URI.file('/f')).toString(), 'file:///f');
}
assert.equal(normalizePath(URI.parse('foo://a/foo/./bar')).toString(), 'foo://a/foo/bar');
assert.equal(normalizePath(URI.parse('foo://a/foo/.')).toString(), 'foo://a/foo');
assert.equal(normalizePath(URI.parse('foo://a/foo/./')).toString(), 'foo://a/foo/');
assert.equal(normalizePath(URI.parse('foo://a/foo/..')).toString(), 'foo://a/');
assert.equal(normalizePath(URI.parse('foo://a/foo/../bar')).toString(), 'foo://a/bar');
assert.equal(normalizePath(URI.parse('foo://a/foo/../../bar')).toString(), 'foo://a/bar');
assert.equal(normalizePath(URI.parse('foo://a/foo/foo/../../bar')).toString(), 'foo://a/bar');
assert.equal(normalizePath(URI.parse('foo://a/foo/foo/./../../bar')).toString(), 'foo://a/bar');
assert.equal(normalizePath(URI.parse('foo://a/foo/foo/./../some/../bar')).toString(), 'foo://a/foo/bar');
assert.equal(normalizePath(URI.parse('foo://a')).toString(), 'foo://a');
assert.equal(normalizePath(URI.parse('foo://a/')).toString(), 'foo://a/');
assert.equal(normalizePath(URI.parse('foo://a/foo/./bar?q=1')).toString(), URI.parse('foo://a/foo/bar?q%3D1').toString());
});
test('isAbsolute', () => {
if (isWindows) {
assert.equal(isAbsolutePath(URI.file('c:\\foo\\')), true);
assert.equal(isAbsolutePath(URI.file('C:\\foo\\')), true);
assert.equal(isAbsolutePath(URI.file('bar')), true); // URI normalizes all file URIs to be absolute
} else {
assert.equal(isAbsolutePath(URI.file('/foo/bar')), true);
assert.equal(isAbsolutePath(URI.file('bar')), true); // URI normalizes all file URIs to be absolute
}
assert.equal(isAbsolutePath(URI.parse('foo:foo')), false);
assert.equal(isAbsolutePath(URI.parse('foo://a/foo/.')), true);
});
function assertTrailingSeparator(u1: URI, expected: boolean) {
assert.equal(hasTrailingPathSeparator(u1), expected, u1.toString());
}
function assertRemoveTrailingSeparator(u1: URI, expected: URI) {
assertEqualURI(removeTrailingPathSeparator(u1), expected, u1.toString());
}
function assertAddTrailingSeparator(u1: URI, expected: URI) {
assertEqualURI(addTrailingPathSeparator(u1), expected, u1.toString());
}
test('trailingPathSeparator', () => {
assertTrailingSeparator(URI.parse('foo://a/foo'), false);
assertTrailingSeparator(URI.parse('foo://a/foo/'), true);
assertTrailingSeparator(URI.parse('foo://a/'), false);
assertTrailingSeparator(URI.parse('foo://a'), false);
assertRemoveTrailingSeparator(URI.parse('foo://a/foo'), URI.parse('foo://a/foo'));
assertRemoveTrailingSeparator(URI.parse('foo://a/foo/'), URI.parse('foo://a/foo'));
assertRemoveTrailingSeparator(URI.parse('foo://a/'), URI.parse('foo://a/'));
assertRemoveTrailingSeparator(URI.parse('foo://a'), URI.parse('foo://a'));
assertAddTrailingSeparator(URI.parse('foo://a/foo'), URI.parse('foo://a/foo/'));
assertAddTrailingSeparator(URI.parse('foo://a/foo/'), URI.parse('foo://a/foo/'));
assertAddTrailingSeparator(URI.parse('foo://a/'), URI.parse('foo://a/'));
assertAddTrailingSeparator(URI.parse('foo://a'), URI.parse('foo://a/'));
if (isWindows) {
assertTrailingSeparator(URI.file('c:\\a\\foo'), false);
assertTrailingSeparator(URI.file('c:\\a\\foo\\'), true);
assertTrailingSeparator(URI.file('c:\\'), false);
assertTrailingSeparator(URI.file('\\\\server\\share\\some\\'), true);
assertTrailingSeparator(URI.file('\\\\server\\share\\'), false);
assertRemoveTrailingSeparator(URI.file('c:\\a\\foo'), URI.file('c:\\a\\foo'));
assertRemoveTrailingSeparator(URI.file('c:\\a\\foo\\'), URI.file('c:\\a\\foo'));
assertRemoveTrailingSeparator(URI.file('c:\\'), URI.file('c:\\'));
assertRemoveTrailingSeparator(URI.file('\\\\server\\share\\some\\'), URI.file('\\\\server\\share\\some'));
assertRemoveTrailingSeparator(URI.file('\\\\server\\share\\'), URI.file('\\\\server\\share\\'));
assertAddTrailingSeparator(URI.file('c:\\a\\foo'), URI.file('c:\\a\\foo\\'));
assertAddTrailingSeparator(URI.file('c:\\a\\foo\\'), URI.file('c:\\a\\foo\\'));
assertAddTrailingSeparator(URI.file('c:\\'), URI.file('c:\\'));
assertAddTrailingSeparator(URI.file('\\\\server\\share\\some'), URI.file('\\\\server\\share\\some\\'));
assertAddTrailingSeparator(URI.file('\\\\server\\share\\some\\'), URI.file('\\\\server\\share\\some\\'));
} else {
assertTrailingSeparator(URI.file('/foo/bar'), false);
assertTrailingSeparator(URI.file('/foo/bar/'), true);
assertTrailingSeparator(URI.file('/'), false);
assertRemoveTrailingSeparator(URI.file('/foo/bar'), URI.file('/foo/bar'));
assertRemoveTrailingSeparator(URI.file('/foo/bar/'), URI.file('/foo/bar'));
assertRemoveTrailingSeparator(URI.file('/'), URI.file('/'));
assertAddTrailingSeparator(URI.file('/foo/bar'), URI.file('/foo/bar/'));
assertAddTrailingSeparator(URI.file('/foo/bar/'), URI.file('/foo/bar/'));
assertAddTrailingSeparator(URI.file('/'), URI.file('/'));
}
});
function assertEqualURI(actual: URI, expected: URI, message?: string, ignoreCase?: boolean) {
let util = ignoreCase ? extUriIgnorePathCase : extUri;
if (!util.isEqual(expected, actual)) {
assert.equal(actual.toString(), expected.toString(), message);
}
}
function assertRelativePath(u1: URI, u2: URI, expectedPath: string | undefined, ignoreJoin?: boolean, ignoreCase?: boolean) {
let util = ignoreCase ? extUriIgnorePathCase : extUri;
assert.equal(util.relativePath(u1, u2), expectedPath, `from ${u1.toString()} to ${u2.toString()}`);
if (expectedPath !== undefined && !ignoreJoin) {
assertEqualURI(removeTrailingPathSeparator(joinPath(u1, expectedPath)), removeTrailingPathSeparator(u2), 'joinPath on relativePath should be equal', ignoreCase);
}
}
test('relativePath', () => {
assertRelativePath(URI.parse('foo://a/foo'), URI.parse('foo://a/foo/bar'), 'bar');
assertRelativePath(URI.parse('foo://a/foo'), URI.parse('foo://a/foo/bar/'), 'bar');
assertRelativePath(URI.parse('foo://a/foo'), URI.parse('foo://a/foo/bar/goo'), 'bar/goo');
assertRelativePath(URI.parse('foo://a/'), URI.parse('foo://a/foo/bar/goo'), 'foo/bar/goo');
assertRelativePath(URI.parse('foo://a/foo/xoo'), URI.parse('foo://a/foo/bar'), '../bar');
assertRelativePath(URI.parse('foo://a/foo/xoo/yoo'), URI.parse('foo://a'), '../../..', true);
assertRelativePath(URI.parse('foo://a/foo'), URI.parse('foo://a/foo/'), '');
assertRelativePath(URI.parse('foo://a/foo/'), URI.parse('foo://a/foo'), '');
assertRelativePath(URI.parse('foo://a/foo/'), URI.parse('foo://a/foo/'), '');
assertRelativePath(URI.parse('foo://a/foo'), URI.parse('foo://a/foo'), '');
assertRelativePath(URI.parse('foo://a'), URI.parse('foo://a'), '', true);
assertRelativePath(URI.parse('foo://a/'), URI.parse('foo://a/'), '');
assertRelativePath(URI.parse('foo://a/'), URI.parse('foo://a'), '', true);
assertRelativePath(URI.parse('foo://a/foo?q'), URI.parse('foo://a/foo/bar#h'), 'bar', true);
assertRelativePath(URI.parse('foo://'), URI.parse('foo://a/b'), undefined);
assertRelativePath(URI.parse('foo://a2/b'), URI.parse('foo://a/b'), undefined);
assertRelativePath(URI.parse('goo://a/b'), URI.parse('foo://a/b'), undefined);
assertRelativePath(URI.parse('foo://a/foo'), URI.parse('foo://A/FOO/bar/goo'), 'bar/goo', false, true);
assertRelativePath(URI.parse('foo://a/foo'), URI.parse('foo://A/FOO/BAR/GOO'), 'BAR/GOO', false, true);
assertRelativePath(URI.parse('foo://a/foo/xoo'), URI.parse('foo://A/FOO/BAR/GOO'), '../BAR/GOO', false, true);
assertRelativePath(URI.parse('foo:///c:/a/foo'), URI.parse('foo:///C:/a/foo/xoo/'), 'xoo', false, true);
if (isWindows) {
assertRelativePath(URI.file('c:\\foo\\bar'), URI.file('c:\\foo\\bar'), '');
assertRelativePath(URI.file('c:\\foo\\bar\\huu'), URI.file('c:\\foo\\bar'), '..');
assertRelativePath(URI.file('c:\\foo\\bar\\a1\\a2'), URI.file('c:\\foo\\bar'), '../..');
assertRelativePath(URI.file('c:\\foo\\bar\\'), URI.file('c:\\foo\\bar\\a1\\a2'), 'a1/a2');
assertRelativePath(URI.file('c:\\foo\\bar\\'), URI.file('c:\\foo\\bar\\a1\\a2\\'), 'a1/a2');
assertRelativePath(URI.file('c:\\'), URI.file('c:\\foo\\bar'), 'foo/bar');
assertRelativePath(URI.file('\\\\server\\share\\some\\'), URI.file('\\\\server\\share\\some\\path'), 'path');
assertRelativePath(URI.file('\\\\server\\share\\some\\'), URI.file('\\\\server\\share2\\some\\path'), '../../share2/some/path', true); // ignore joinPath assert: path.join is not root aware
} else {
assertRelativePath(URI.file('/a/foo'), URI.file('/a/foo/bar'), 'bar');
assertRelativePath(URI.file('/a/foo'), URI.file('/a/foo/bar/'), 'bar');
assertRelativePath(URI.file('/a/foo'), URI.file('/a/foo/bar/goo'), 'bar/goo');
assertRelativePath(URI.file('/a/'), URI.file('/a/foo/bar/goo'), 'foo/bar/goo');
assertRelativePath(URI.file('/'), URI.file('/a/foo/bar/goo'), 'a/foo/bar/goo');
assertRelativePath(URI.file('/a/foo/xoo'), URI.file('/a/foo/bar'), '../bar');
assertRelativePath(URI.file('/a/foo/xoo/yoo'), URI.file('/a'), '../../..');
assertRelativePath(URI.file('/a/foo'), URI.file('/a/foo/'), '');
assertRelativePath(URI.file('/a/foo'), URI.file('/b/foo/'), '../../b/foo');
}
});
function assertResolve(u1: URI, path: string, expected: URI) {
const actual = resolvePath(u1, path);
assertEqualURI(actual, expected, `from ${u1.toString()} and ${path}`);
const p = path.indexOf('/') !== -1 ? posix : win32;
if (!p.isAbsolute(path)) {
let expectedPath = isWindows ? toSlashes(path) : path;
expectedPath = expectedPath.startsWith('./') ? expectedPath.substr(2) : expectedPath;
assert.equal(relativePath(u1, actual), expectedPath, `relativePath (${u1.toString()}) on actual (${actual.toString()}) should be to path (${expectedPath})`);
}
}
test('resolve', () => {
if (isWindows) {
assertResolve(URI.file('c:\\foo\\bar'), 'file.js', URI.file('c:\\foo\\bar\\file.js'));
assertResolve(URI.file('c:\\foo\\bar'), 't\\file.js', URI.file('c:\\foo\\bar\\t\\file.js'));
assertResolve(URI.file('c:\\foo\\bar'), '.\\t\\file.js', URI.file('c:\\foo\\bar\\t\\file.js'));
assertResolve(URI.file('c:\\foo\\bar'), 'a1/file.js', URI.file('c:\\foo\\bar\\a1\\file.js'));
assertResolve(URI.file('c:\\foo\\bar'), './a1/file.js', URI.file('c:\\foo\\bar\\a1\\file.js'));
assertResolve(URI.file('c:\\foo\\bar'), '\\b1\\file.js', URI.file('c:\\b1\\file.js'));
assertResolve(URI.file('c:\\foo\\bar'), '/b1/file.js', URI.file('c:\\b1\\file.js'));
assertResolve(URI.file('c:\\foo\\bar\\'), 'file.js', URI.file('c:\\foo\\bar\\file.js'));
assertResolve(URI.file('c:\\'), 'file.js', URI.file('c:\\file.js'));
assertResolve(URI.file('c:\\'), '\\b1\\file.js', URI.file('c:\\b1\\file.js'));
assertResolve(URI.file('c:\\'), '/b1/file.js', URI.file('c:\\b1\\file.js'));
assertResolve(URI.file('c:\\'), 'd:\\foo\\bar.txt', URI.file('d:\\foo\\bar.txt'));
assertResolve(URI.file('\\\\server\\share\\some\\'), 'b1\\file.js', URI.file('\\\\server\\share\\some\\b1\\file.js'));
assertResolve(URI.file('\\\\server\\share\\some\\'), '\\file.js', URI.file('\\\\server\\share\\file.js'));
assertResolve(URI.file('c:\\'), '\\\\server\\share\\some\\', URI.file('\\\\server\\share\\some'));
assertResolve(URI.file('\\\\server\\share\\some\\'), 'c:\\', URI.file('c:\\'));
} else {
assertResolve(URI.file('/foo/bar'), 'file.js', URI.file('/foo/bar/file.js'));
assertResolve(URI.file('/foo/bar'), './file.js', URI.file('/foo/bar/file.js'));
assertResolve(URI.file('/foo/bar'), '/file.js', URI.file('/file.js'));
assertResolve(URI.file('/foo/bar/'), 'file.js', URI.file('/foo/bar/file.js'));
assertResolve(URI.file('/'), 'file.js', URI.file('/file.js'));
assertResolve(URI.file(''), './file.js', URI.file('/file.js'));
assertResolve(URI.file(''), '/file.js', URI.file('/file.js'));
}
assertResolve(URI.parse('foo://server/foo/bar'), 'file.js', URI.parse('foo://server/foo/bar/file.js'));
assertResolve(URI.parse('foo://server/foo/bar'), './file.js', URI.parse('foo://server/foo/bar/file.js'));
assertResolve(URI.parse('foo://server/foo/bar'), './file.js', URI.parse('foo://server/foo/bar/file.js'));
assertResolve(URI.parse('foo://server/foo/bar'), 'c:\\a1\\b1', URI.parse('foo://server/c:/a1/b1'));
assertResolve(URI.parse('foo://server/foo/bar'), 'c:\\', URI.parse('foo://server/c:'));
});
function assertIsEqual(u1: URI, u2: URI, ignoreCase: boolean | undefined, expected: boolean) {
let util = ignoreCase ? extUriIgnorePathCase : extUri;
assert.equal(util.isEqual(u1, u2), expected, `${u1.toString()}${expected ? '===' : '!=='}${u2.toString()}`);
assert.equal(util.compare(u1, u2) === 0, expected);
assert.equal(util.getComparisonKey(u1) === util.getComparisonKey(u2), expected, `comparison keys ${u1.toString()}, ${u2.toString()}`);
assert.equal(util.isEqualOrParent(u1, u2), expected, `isEqualOrParent ${u1.toString()}, ${u2.toString()}`);
if (!ignoreCase) {
assert.equal(u1.toString() === u2.toString(), expected);
}
}
test('isEqual', () => {
let fileURI = isWindows ? URI.file('c:\\foo\\bar') : URI.file('/foo/bar');
let fileURI2 = isWindows ? URI.file('C:\\foo\\Bar') : URI.file('/foo/Bar');
assertIsEqual(fileURI, fileURI, true, true);
assertIsEqual(fileURI, fileURI, false, true);
assertIsEqual(fileURI, fileURI, undefined, true);
assertIsEqual(fileURI, fileURI2, true, true);
assertIsEqual(fileURI, fileURI2, false, false);
let fileURI3 = URI.parse('foo://server:453/foo/bar');
let fileURI4 = URI.parse('foo://server:453/foo/Bar');
assertIsEqual(fileURI3, fileURI3, true, true);
assertIsEqual(fileURI3, fileURI3, false, true);
assertIsEqual(fileURI3, fileURI3, undefined, true);
assertIsEqual(fileURI3, fileURI4, true, true);
assertIsEqual(fileURI3, fileURI4, false, false);
assertIsEqual(fileURI, fileURI3, true, false);
assertIsEqual(URI.parse('file://server'), URI.parse('file://server/'), true, true);
assertIsEqual(URI.parse('http://server'), URI.parse('http://server/'), true, true);
assertIsEqual(URI.parse('foo://server'), URI.parse('foo://server/'), true, false); // only selected scheme have / as the default path
assertIsEqual(URI.parse('foo://server/foo'), URI.parse('foo://server/foo/'), true, false);
assertIsEqual(URI.parse('foo://server/foo'), URI.parse('foo://server/foo?'), true, true);
let fileURI5 = URI.parse('foo://server:453/foo/bar?q=1');
let fileURI6 = URI.parse('foo://server:453/foo/bar#xy');
assertIsEqual(fileURI5, fileURI5, true, true);
assertIsEqual(fileURI5, fileURI3, true, false);
assertIsEqual(fileURI6, fileURI6, true, true);
assertIsEqual(fileURI6, fileURI5, true, false);
assertIsEqual(fileURI6, fileURI3, true, false);
});
test('isEqualOrParent', () => {
let fileURI = isWindows ? URI.file('c:\\foo\\bar') : URI.file('/foo/bar');
let fileURI2 = isWindows ? URI.file('c:\\foo') : URI.file('/foo');
let fileURI2b = isWindows ? URI.file('C:\\Foo\\') : URI.file('/Foo/');
assert.equal(extUriIgnorePathCase.isEqualOrParent(fileURI, fileURI), true, '1');
assert.equal(extUri.isEqualOrParent(fileURI, fileURI), true, '2');
assert.equal(extUriIgnorePathCase.isEqualOrParent(fileURI, fileURI2), true, '3');
assert.equal(extUri.isEqualOrParent(fileURI, fileURI2), true, '4');
assert.equal(extUriIgnorePathCase.isEqualOrParent(fileURI, fileURI2b), true, '5');
assert.equal(extUri.isEqualOrParent(fileURI, fileURI2b), false, '6');
assert.equal(extUri.isEqualOrParent(fileURI2, fileURI), false, '7');
assert.equal(extUriIgnorePathCase.isEqualOrParent(fileURI2b, fileURI2), true, '8');
let fileURI3 = URI.parse('foo://server:453/foo/bar/goo');
let fileURI4 = URI.parse('foo://server:453/foo/');
let fileURI5 = URI.parse('foo://server:453/foo');
assert.equal(extUriIgnorePathCase.isEqualOrParent(fileURI3, fileURI3, true), true, '11');
assert.equal(extUri.isEqualOrParent(fileURI3, fileURI3), true, '12');
assert.equal(extUriIgnorePathCase.isEqualOrParent(fileURI3, fileURI4, true), true, '13');
assert.equal(extUri.isEqualOrParent(fileURI3, fileURI4), true, '14');
assert.equal(extUriIgnorePathCase.isEqualOrParent(fileURI3, fileURI, true), false, '15');
assert.equal(extUriIgnorePathCase.isEqualOrParent(fileURI5, fileURI5, true), true, '16');
let fileURI6 = URI.parse('foo://server:453/foo?q=1');
let fileURI7 = URI.parse('foo://server:453/foo/bar?q=1');
assert.equal(extUriIgnorePathCase.isEqualOrParent(fileURI6, fileURI5), false, '17');
assert.equal(extUriIgnorePathCase.isEqualOrParent(fileURI6, fileURI6), true, '18');
assert.equal(extUriIgnorePathCase.isEqualOrParent(fileURI7, fileURI6), true, '19');
assert.equal(extUriIgnorePathCase.isEqualOrParent(fileURI7, fileURI5), false, '20');
});
});
| src/vs/base/test/common/resources.test.ts | 0 | https://github.com/microsoft/vscode/commit/0fc17285e1f612f63deddaaa206f08162f190ec2 | [
0.0001770271483110264,
0.00017155410023406148,
0.00016462783969473094,
0.00017141227726824582,
0.000003025237674592063
] |
{
"id": 0,
"code_window": [
"import { toggleComment } from './toggleComment';\n",
"import { fetchEditPoint } from './editPoint';\n",
"import { fetchSelectItem } from './selectItem';\n",
"import { evaluateMathExpression } from './evaluateMathExpression';\n",
"import { incrementDecrement } from './incrementDecrement';\n",
"import { LANGUAGE_MODES, getMappingForIncludedLanguages, updateEmmetExtensionsPath } from './util';\n",
"import { reflectCssValue } from './reflectCssValue';\n",
"\n",
"export function activateEmmetExtension(context: vscode.ExtensionContext) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { LANGUAGE_MODES, getMappingForIncludedLanguages, updateEmmetExtensionsPath, getPathBaseName } from './util';\n"
],
"file_path": "extensions/emmet/src/emmetCommon.ts",
"type": "replace",
"edit_start_line_idx": 19
} | {
"version": "0.2.0",
"configurations": [
{
"name": "Launch Extension",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}"
],
"stopOnEntry": false,
"sourceMaps": true,
"outFiles": ["${workspaceFolder}/client/out"],
"preLaunchTask": "npm"
},
{
"name": "Launch Tests",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": ["--extensionDevelopmentPath=${workspaceFolder}", "--extensionTestsPath=${workspaceFolder}/client/out/test" ],
"stopOnEntry": false,
"sourceMaps": true,
"outFiles": ["${workspaceFolder}/client/out/test"],
"preLaunchTask": "npm"
},
{
"name": "Attach Language Server",
"type": "node",
"request": "attach",
"port": 6004,
"sourceMaps": true,
"outFiles": ["${workspaceFolder}/server/out"]
}
],
"compounds": [
{
"name": "Launch Extension and Attach Language Server",
"configurations": [
"Launch Extension",
"Attach Language Server"
]
}
]
} | extensions/json-language-features/.vscode/launch.json | 0 | https://github.com/microsoft/vscode/commit/0fc17285e1f612f63deddaaa206f08162f190ec2 | [
0.00017282317276112735,
0.00017162799485959113,
0.0001706563780317083,
0.00017109107284341007,
9.614933560442296e-7
] |
{
"id": 1,
"code_window": [
"\t\tif (e.affectsConfiguration('emmet.extensionsPath')) {\n",
"\t\t\tupdateEmmetExtensionsPath();\n",
"\t\t}\n",
"\t}));\n",
"}\n",
"\n",
"/**\n",
" * Holds any registered completion providers by their language strings\n",
" */\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\tcontext.subscriptions.push(vscode.workspace.onDidSaveTextDocument((e) => {\n",
"\t\tconst basefileName: string = getPathBaseName(e.fileName);\n",
"\t\tif (basefileName.startsWith('snippets') && basefileName.endsWith('.json')) {\n",
"\t\t\tupdateEmmetExtensionsPath();\n",
"\t\t}\n",
"\t}));\n"
],
"file_path": "extensions/emmet/src/emmetCommon.ts",
"type": "add",
"edit_start_line_idx": 136
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { DefaultCompletionItemProvider } from './defaultCompletionProvider';
import { expandEmmetAbbreviation, wrapWithAbbreviation, wrapIndividualLinesWithAbbreviation } from './abbreviationActions';
import { removeTag } from './removeTag';
import { updateTag } from './updateTag';
import { matchTag } from './matchTag';
import { balanceOut, balanceIn } from './balance';
import { splitJoinTag } from './splitJoinTag';
import { mergeLines } from './mergeLines';
import { toggleComment } from './toggleComment';
import { fetchEditPoint } from './editPoint';
import { fetchSelectItem } from './selectItem';
import { evaluateMathExpression } from './evaluateMathExpression';
import { incrementDecrement } from './incrementDecrement';
import { LANGUAGE_MODES, getMappingForIncludedLanguages, updateEmmetExtensionsPath } from './util';
import { reflectCssValue } from './reflectCssValue';
export function activateEmmetExtension(context: vscode.ExtensionContext) {
registerCompletionProviders(context);
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.wrapWithAbbreviation', (args) => {
wrapWithAbbreviation(args);
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.wrapIndividualLinesWithAbbreviation', (args) => {
wrapIndividualLinesWithAbbreviation(args);
}));
context.subscriptions.push(vscode.commands.registerCommand('emmet.expandAbbreviation', (args) => {
expandEmmetAbbreviation(args);
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.removeTag', () => {
return removeTag();
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.updateTag', (inputTag) => {
if (inputTag && typeof inputTag === 'string') {
return updateTag(inputTag);
}
return vscode.window.showInputBox({ prompt: 'Enter Tag' }).then(tagName => {
if (tagName) {
const update = updateTag(tagName);
return update ? update : false;
}
return false;
});
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.matchTag', () => {
matchTag();
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.balanceOut', () => {
balanceOut();
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.balanceIn', () => {
balanceIn();
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.splitJoinTag', () => {
return splitJoinTag();
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.mergeLines', () => {
mergeLines();
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.toggleComment', () => {
toggleComment();
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.nextEditPoint', () => {
fetchEditPoint('next');
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.prevEditPoint', () => {
fetchEditPoint('prev');
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.selectNextItem', () => {
fetchSelectItem('next');
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.selectPrevItem', () => {
fetchSelectItem('prev');
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.evaluateMathExpression', () => {
evaluateMathExpression();
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.incrementNumberByOneTenth', () => {
return incrementDecrement(0.1);
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.incrementNumberByOne', () => {
return incrementDecrement(1);
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.incrementNumberByTen', () => {
return incrementDecrement(10);
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.decrementNumberByOneTenth', () => {
return incrementDecrement(-0.1);
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.decrementNumberByOne', () => {
return incrementDecrement(-1);
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.decrementNumberByTen', () => {
return incrementDecrement(-10);
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.reflectCSSValue', () => {
return reflectCssValue();
}));
updateEmmetExtensionsPath();
context.subscriptions.push(vscode.workspace.onDidChangeConfiguration((e) => {
if (e.affectsConfiguration('emmet.includeLanguages')) {
registerCompletionProviders(context);
}
if (e.affectsConfiguration('emmet.extensionsPath')) {
updateEmmetExtensionsPath();
}
}));
}
/**
* Holds any registered completion providers by their language strings
*/
const languageMappingForCompletionProviders: Map<string, string> = new Map<string, string>();
const completionProvidersMapping: Map<string, vscode.Disposable> = new Map<string, vscode.Disposable>();
function registerCompletionProviders(context: vscode.ExtensionContext) {
let completionProvider = new DefaultCompletionItemProvider();
let includedLanguages = getMappingForIncludedLanguages();
Object.keys(includedLanguages).forEach(language => {
if (languageMappingForCompletionProviders.has(language) && languageMappingForCompletionProviders.get(language) === includedLanguages[language]) {
return;
}
if (languageMappingForCompletionProviders.has(language)) {
const mapping = completionProvidersMapping.get(language);
if (mapping) {
mapping.dispose();
}
languageMappingForCompletionProviders.delete(language);
completionProvidersMapping.delete(language);
}
const provider = vscode.languages.registerCompletionItemProvider({ language, scheme: '*' }, completionProvider, ...LANGUAGE_MODES[includedLanguages[language]]);
context.subscriptions.push(provider);
languageMappingForCompletionProviders.set(language, includedLanguages[language]);
completionProvidersMapping.set(language, provider);
});
Object.keys(LANGUAGE_MODES).forEach(language => {
if (!languageMappingForCompletionProviders.has(language)) {
const provider = vscode.languages.registerCompletionItemProvider({ language, scheme: '*' }, completionProvider, ...LANGUAGE_MODES[language]);
context.subscriptions.push(provider);
languageMappingForCompletionProviders.set(language, language);
completionProvidersMapping.set(language, provider);
}
});
}
export function deactivate() {
}
| extensions/emmet/src/emmetCommon.ts | 1 | https://github.com/microsoft/vscode/commit/0fc17285e1f612f63deddaaa206f08162f190ec2 | [
0.5457442402839661,
0.029220443218946457,
0.00016540024080313742,
0.00016781108570285141,
0.12175003439188004
] |
{
"id": 1,
"code_window": [
"\t\tif (e.affectsConfiguration('emmet.extensionsPath')) {\n",
"\t\t\tupdateEmmetExtensionsPath();\n",
"\t\t}\n",
"\t}));\n",
"}\n",
"\n",
"/**\n",
" * Holds any registered completion providers by their language strings\n",
" */\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\tcontext.subscriptions.push(vscode.workspace.onDidSaveTextDocument((e) => {\n",
"\t\tconst basefileName: string = getPathBaseName(e.fileName);\n",
"\t\tif (basefileName.startsWith('snippets') && basefileName.endsWith('.json')) {\n",
"\t\t\tupdateEmmetExtensionsPath();\n",
"\t\t}\n",
"\t}));\n"
],
"file_path": "extensions/emmet/src/emmetCommon.ts",
"type": "add",
"edit_start_line_idx": 136
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { join } from 'vs/base/common/path';
import { tmpdir } from 'os';
import { generateUuid } from 'vs/base/common/uuid';
import { IExtHostCommands } from 'vs/workbench/api/common/extHostCommands';
import { Disposable } from 'vs/base/common/lifecycle';
import { MainContext } from 'vs/workbench/api/common/extHost.protocol';
import { URI } from 'vs/base/common/uri';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
export class ExtHostDownloadService extends Disposable {
constructor(
@IExtHostRpcService extHostRpc: IExtHostRpcService,
@IExtHostCommands commands: IExtHostCommands
) {
super();
const proxy = extHostRpc.getProxy(MainContext.MainThreadDownloadService);
commands.registerCommand(false, '_workbench.downloadResource', async (resource: URI): Promise<any> => {
const location = URI.file(join(tmpdir(), generateUuid()));
await proxy.$download(resource, location);
return location;
});
}
}
| src/vs/workbench/api/node/extHostDownloadService.ts | 0 | https://github.com/microsoft/vscode/commit/0fc17285e1f612f63deddaaa206f08162f190ec2 | [
0.00017443120304960757,
0.00017357394972350448,
0.00017267871589865535,
0.00017359295452479273,
8.010517831280595e-7
] |
{
"id": 1,
"code_window": [
"\t\tif (e.affectsConfiguration('emmet.extensionsPath')) {\n",
"\t\t\tupdateEmmetExtensionsPath();\n",
"\t\t}\n",
"\t}));\n",
"}\n",
"\n",
"/**\n",
" * Holds any registered completion providers by their language strings\n",
" */\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\tcontext.subscriptions.push(vscode.workspace.onDidSaveTextDocument((e) => {\n",
"\t\tconst basefileName: string = getPathBaseName(e.fileName);\n",
"\t\tif (basefileName.startsWith('snippets') && basefileName.endsWith('.json')) {\n",
"\t\t\tupdateEmmetExtensionsPath();\n",
"\t\t}\n",
"\t}));\n"
],
"file_path": "extensions/emmet/src/emmetCommon.ts",
"type": "add",
"edit_start_line_idx": 136
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as DOM from 'vs/base/browser/dom';
import { IKeyboardEvent, StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { ActionBar, ActionsOrientation } from 'vs/base/browser/ui/actionbar/actionbar';
import { IInputOptions, InputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { Widget } from 'vs/base/browser/ui/widget';
import { Action, IAction } from 'vs/base/common/actions';
import { Emitter, Event } from 'vs/base/common/event';
import { MarkdownString } from 'vs/base/common/htmlContent';
import { KeyCode } from 'vs/base/common/keyCodes';
import { Disposable } from 'vs/base/common/lifecycle';
import { URI } from 'vs/base/common/uri';
import { IMarginData } from 'vs/editor/browser/controller/mouseTarget';
import { ICodeEditor, IEditorMouseEvent, IViewZone, MouseTargetType } from 'vs/editor/browser/editorBrowser';
import { ICursorPositionChangedEvent } from 'vs/editor/common/controller/cursorEvents';
import { Position } from 'vs/editor/common/core/position';
import { IModelDeltaDecoration, TrackedRangeStickiness } from 'vs/editor/common/model';
import { localize } from 'vs/nls';
import { ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
import { IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ILabelService } from 'vs/platform/label/common/label';
import { Schemas } from 'vs/base/common/network';
import { activeContrastBorder, badgeBackground, badgeForeground, contrastBorder, focusBorder } from 'vs/platform/theme/common/colorRegistry';
import { attachInputBoxStyler, attachStylerCallback } from 'vs/platform/theme/common/styler';
import { ICssStyleCollector, IColorTheme, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { IWorkspaceContextService, IWorkspaceFolder, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { PANEL_ACTIVE_TITLE_BORDER, PANEL_ACTIVE_TITLE_FOREGROUND, PANEL_INACTIVE_TITLE_FOREGROUND } from 'vs/workbench/common/theme';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { ISettingsGroup, IPreferencesService } from 'vs/workbench/services/preferences/common/preferences';
import { EditorOption } from 'vs/editor/common/config/editorOptions';
import { isEqual } from 'vs/base/common/resources';
import { registerIcon, Codicon } from 'vs/base/common/codicons';
import { BaseActionViewItem } from 'vs/base/browser/ui/actionbar/actionViewItems';
export class SettingsHeaderWidget extends Widget implements IViewZone {
private id!: string;
private _domNode!: HTMLElement;
protected titleContainer!: HTMLElement;
private messageElement!: HTMLElement;
constructor(protected editor: ICodeEditor, private title: string) {
super();
this.create();
this._register(this.editor.onDidChangeConfiguration(() => this.layout()));
this._register(this.editor.onDidLayoutChange(() => this.layout()));
}
get domNode(): HTMLElement {
return this._domNode;
}
get heightInLines(): number {
return 1;
}
get afterLineNumber(): number {
return 0;
}
protected create() {
this._domNode = DOM.$('.settings-header-widget');
this.titleContainer = DOM.append(this._domNode, DOM.$('.title-container'));
if (this.title) {
DOM.append(this.titleContainer, DOM.$('.title')).textContent = this.title;
}
this.messageElement = DOM.append(this.titleContainer, DOM.$('.message'));
if (this.title) {
this.messageElement.style.paddingLeft = '12px';
}
this.editor.changeViewZones(accessor => {
this.id = accessor.addZone(this);
this.layout();
});
}
setMessage(message: string): void {
this.messageElement.textContent = message;
}
private layout(): void {
const options = this.editor.getOptions();
const fontInfo = options.get(EditorOption.fontInfo);
this.titleContainer.style.fontSize = fontInfo.fontSize + 'px';
if (!options.get(EditorOption.folding)) {
this.titleContainer.style.paddingLeft = '6px';
}
}
dispose() {
this.editor.changeViewZones(accessor => {
accessor.removeZone(this.id);
});
super.dispose();
}
}
export class DefaultSettingsHeaderWidget extends SettingsHeaderWidget {
private _onClick = this._register(new Emitter<void>());
readonly onClick: Event<void> = this._onClick.event;
protected create() {
super.create();
this.toggleMessage(true);
}
toggleMessage(hasSettings: boolean): void {
if (hasSettings) {
this.setMessage(localize('defaultSettings', "Place your settings in the right hand side editor to override."));
} else {
this.setMessage(localize('noSettingsFound', "No Settings Found."));
}
}
}
export class SettingsGroupTitleWidget extends Widget implements IViewZone {
private id!: string;
private _afterLineNumber!: number;
private _domNode!: HTMLElement;
private titleContainer!: HTMLElement;
private icon!: HTMLElement;
private title!: HTMLElement;
private _onToggled = this._register(new Emitter<boolean>());
readonly onToggled: Event<boolean> = this._onToggled.event;
private previousPosition: Position | null = null;
constructor(private editor: ICodeEditor, public settingsGroup: ISettingsGroup) {
super();
this.create();
this._register(this.editor.onDidChangeConfiguration(() => this.layout()));
this._register(this.editor.onDidLayoutChange(() => this.layout()));
this._register(this.editor.onDidChangeCursorPosition((e) => this.onCursorChange(e)));
}
get domNode(): HTMLElement {
return this._domNode;
}
get heightInLines(): number {
return 1.5;
}
get afterLineNumber(): number {
return this._afterLineNumber;
}
private create() {
this._domNode = DOM.$('.settings-group-title-widget');
this.titleContainer = DOM.append(this._domNode, DOM.$('.title-container'));
this.titleContainer.tabIndex = 0;
this.onclick(this.titleContainer, () => this.toggle());
this.onkeydown(this.titleContainer, (e) => this.onKeyDown(e));
const focusTracker = this._register(DOM.trackFocus(this.titleContainer));
this._register(focusTracker.onDidFocus(() => this.toggleFocus(true)));
this._register(focusTracker.onDidBlur(() => this.toggleFocus(false)));
this.icon = DOM.append(this.titleContainer, DOM.$('.codicon.codicon-chevron-down'));
this.title = DOM.append(this.titleContainer, DOM.$('.title'));
this.title.textContent = this.settingsGroup.title + ` (${this.settingsGroup.sections.reduce((count, section) => count + section.settings.length, 0)})`;
this.layout();
}
render() {
if (!this.settingsGroup.range) {
// #61352
return;
}
this._afterLineNumber = this.settingsGroup.range.startLineNumber - 2;
this.editor.changeViewZones(accessor => {
this.id = accessor.addZone(this);
this.layout();
});
}
toggleCollapse(collapse: boolean) {
this.titleContainer.classList.toggle('collapsed', collapse);
}
toggleFocus(focus: boolean): void {
this.titleContainer.classList.toggle('focused', focus);
}
isCollapsed(): boolean {
return this.titleContainer.classList.contains('collapsed');
}
private layout(): void {
const options = this.editor.getOptions();
const fontInfo = options.get(EditorOption.fontInfo);
const layoutInfo = this.editor.getLayoutInfo();
this._domNode.style.width = layoutInfo.contentWidth - layoutInfo.verticalScrollbarWidth + 'px';
this.titleContainer.style.lineHeight = options.get(EditorOption.lineHeight) + 3 + 'px';
this.titleContainer.style.height = options.get(EditorOption.lineHeight) + 3 + 'px';
this.titleContainer.style.fontSize = fontInfo.fontSize + 'px';
this.icon.style.minWidth = `${this.getIconSize(16)}px`;
}
private getIconSize(minSize: number): number {
const fontSize = this.editor.getOption(EditorOption.fontInfo).fontSize;
return fontSize > 8 ? Math.max(fontSize, minSize) : 12;
}
private onKeyDown(keyboardEvent: IKeyboardEvent): void {
switch (keyboardEvent.keyCode) {
case KeyCode.Enter:
case KeyCode.Space:
this.toggle();
break;
case KeyCode.LeftArrow:
this.collapse(true);
break;
case KeyCode.RightArrow:
this.collapse(false);
break;
case KeyCode.UpArrow:
if (this.settingsGroup.range.startLineNumber - 3 !== 1) {
this.editor.focus();
const lineNumber = this.settingsGroup.range.startLineNumber - 2;
if (this.editor.hasModel()) {
this.editor.setPosition({ lineNumber, column: this.editor.getModel().getLineMinColumn(lineNumber) });
}
}
break;
case KeyCode.DownArrow:
const lineNumber = this.isCollapsed() ? this.settingsGroup.range.startLineNumber : this.settingsGroup.range.startLineNumber - 1;
this.editor.focus();
if (this.editor.hasModel()) {
this.editor.setPosition({ lineNumber, column: this.editor.getModel().getLineMinColumn(lineNumber) });
}
break;
}
}
private toggle() {
this.collapse(!this.isCollapsed());
}
private collapse(collapse: boolean) {
if (collapse !== this.isCollapsed()) {
this.titleContainer.classList.toggle('collapsed', collapse);
this._onToggled.fire(collapse);
}
}
private onCursorChange(e: ICursorPositionChangedEvent): void {
if (e.source !== 'mouse' && this.focusTitle(e.position)) {
this.titleContainer.focus();
}
}
private focusTitle(currentPosition: Position): boolean {
const previousPosition = this.previousPosition;
this.previousPosition = currentPosition;
if (!previousPosition) {
return false;
}
if (previousPosition.lineNumber === currentPosition.lineNumber) {
return false;
}
if (!this.settingsGroup.range) {
// #60460?
return false;
}
if (currentPosition.lineNumber === this.settingsGroup.range.startLineNumber - 1 || currentPosition.lineNumber === this.settingsGroup.range.startLineNumber - 2) {
return true;
}
if (this.isCollapsed() && currentPosition.lineNumber === this.settingsGroup.range.endLineNumber) {
return true;
}
return false;
}
dispose() {
this.editor.changeViewZones(accessor => {
accessor.removeZone(this.id);
});
super.dispose();
}
}
export class FolderSettingsActionViewItem extends BaseActionViewItem {
private _folder: IWorkspaceFolder | null;
private _folderSettingCounts = new Map<string, number>();
private container!: HTMLElement;
private anchorElement!: HTMLElement;
private labelElement!: HTMLElement;
private detailsElement!: HTMLElement;
private dropDownElement!: HTMLElement;
constructor(
action: IAction,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IContextMenuService private readonly contextMenuService: IContextMenuService,
@IPreferencesService private readonly preferencesService: IPreferencesService,
) {
super(null, action);
const workspace = this.contextService.getWorkspace();
this._folder = workspace.folders.length === 1 ? workspace.folders[0] : null;
this._register(this.contextService.onDidChangeWorkspaceFolders(() => this.onWorkspaceFoldersChanged()));
}
get folder(): IWorkspaceFolder | null {
return this._folder;
}
set folder(folder: IWorkspaceFolder | null) {
this._folder = folder;
this.update();
}
setCount(settingsTarget: URI, count: number): void {
const workspaceFolder = this.contextService.getWorkspaceFolder(settingsTarget);
if (!workspaceFolder) {
throw new Error('unknown folder');
}
const folder = workspaceFolder.uri;
this._folderSettingCounts.set(folder.toString(), count);
this.update();
}
render(container: HTMLElement): void {
this.element = container;
this.container = container;
this.labelElement = DOM.$('.action-title');
this.detailsElement = DOM.$('.action-details');
this.dropDownElement = DOM.$('.dropdown-icon.codicon.codicon-triangle-down.hide');
this.anchorElement = DOM.$('a.action-label.folder-settings', {
role: 'button',
'aria-haspopup': 'true',
'tabindex': '0'
}, this.labelElement, this.detailsElement, this.dropDownElement);
this._register(DOM.addDisposableListener(this.anchorElement, DOM.EventType.MOUSE_DOWN, e => DOM.EventHelper.stop(e)));
this._register(DOM.addDisposableListener(this.anchorElement, DOM.EventType.CLICK, e => this.onClick(e)));
this._register(DOM.addDisposableListener(this.anchorElement, DOM.EventType.KEY_UP, e => this.onKeyUp(e)));
DOM.append(this.container, this.anchorElement);
this.update();
}
private onKeyUp(event: any): void {
const keyboardEvent = new StandardKeyboardEvent(event);
switch (keyboardEvent.keyCode) {
case KeyCode.Enter:
case KeyCode.Space:
this.onClick(event);
return;
}
}
onClick(event: DOM.EventLike): void {
DOM.EventHelper.stop(event, true);
if (!this.folder || this._action.checked) {
this.showMenu();
} else {
this._action.run(this._folder);
}
}
protected updateEnabled(): void {
this.update();
}
protected updateChecked(): void {
this.update();
}
private onWorkspaceFoldersChanged(): void {
const oldFolder = this._folder;
const workspace = this.contextService.getWorkspace();
if (oldFolder) {
this._folder = workspace.folders.filter(folder => isEqual(folder.uri, oldFolder.uri))[0] || workspace.folders[0];
}
this._folder = this._folder ? this._folder : workspace.folders.length === 1 ? workspace.folders[0] : null;
this.update();
if (this._action.checked) {
this._action.run(this._folder);
}
}
private async update(): Promise<void> {
let total = 0;
this._folderSettingCounts.forEach(n => total += n);
const workspace = this.contextService.getWorkspace();
if (this._folder) {
this.labelElement.textContent = this._folder.name;
this.anchorElement.title = (await this.preferencesService.getEditableSettingsURI(ConfigurationTarget.WORKSPACE_FOLDER, this._folder.uri))?.fsPath || '';
const detailsText = this.labelWithCount(this._action.label, total);
this.detailsElement.textContent = detailsText;
this.dropDownElement.classList.toggle('hide', workspace.folders.length === 1 || !this._action.checked);
} else {
const labelText = this.labelWithCount(this._action.label, total);
this.labelElement.textContent = labelText;
this.detailsElement.textContent = '';
this.anchorElement.title = this._action.label;
this.dropDownElement.classList.remove('hide');
}
this.anchorElement.classList.toggle('checked', this._action.checked);
this.container.classList.toggle('disabled', !this._action.enabled);
}
private showMenu(): void {
this.contextMenuService.showContextMenu({
getAnchor: () => this.container,
getActions: () => this.getDropdownMenuActions(),
getActionViewItem: () => undefined,
onHide: () => {
this.anchorElement.blur();
}
});
}
private getDropdownMenuActions(): IAction[] {
const actions: IAction[] = [];
const workspaceFolders = this.contextService.getWorkspace().folders;
if (this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE && workspaceFolders.length > 0) {
actions.push(...workspaceFolders.map((folder, index) => {
const folderCount = this._folderSettingCounts.get(folder.uri.toString());
return <IAction>{
id: 'folderSettingsTarget' + index,
label: this.labelWithCount(folder.name, folderCount),
checked: this.folder && isEqual(this.folder.uri, folder.uri),
enabled: true,
run: () => this._action.run(folder)
};
}));
}
return actions;
}
private labelWithCount(label: string, count: number | undefined): string {
// Append the count if it's >0 and not undefined
if (count) {
label += ` (${count})`;
}
return label;
}
}
export type SettingsTarget = ConfigurationTarget.USER_LOCAL | ConfigurationTarget.USER_REMOTE | ConfigurationTarget.WORKSPACE | URI;
export interface ISettingsTargetsWidgetOptions {
enableRemoteSettings?: boolean;
}
export class SettingsTargetsWidget extends Widget {
private settingsSwitcherBar!: ActionBar;
private userLocalSettings!: Action;
private userRemoteSettings!: Action;
private workspaceSettings!: Action;
private folderSettings!: FolderSettingsActionViewItem;
private options: ISettingsTargetsWidgetOptions;
private _settingsTarget: SettingsTarget | null = null;
private readonly _onDidTargetChange = this._register(new Emitter<SettingsTarget>());
readonly onDidTargetChange: Event<SettingsTarget> = this._onDidTargetChange.event;
constructor(
parent: HTMLElement,
options: ISettingsTargetsWidgetOptions | undefined,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,
@ILabelService private readonly labelService: ILabelService,
@IPreferencesService private readonly preferencesService: IPreferencesService,
) {
super();
this.options = options || {};
this.create(parent);
this._register(this.contextService.onDidChangeWorkbenchState(() => this.onWorkbenchStateChanged()));
this._register(this.contextService.onDidChangeWorkspaceFolders(() => this.update()));
}
private create(parent: HTMLElement): void {
const settingsTabsWidget = DOM.append(parent, DOM.$('.settings-tabs-widget'));
this.settingsSwitcherBar = this._register(new ActionBar(settingsTabsWidget, {
orientation: ActionsOrientation.HORIZONTAL,
ariaLabel: localize('settingsSwitcherBarAriaLabel', "Settings Switcher"),
animated: false,
actionViewItemProvider: (action: IAction) => action.id === 'folderSettings' ? this.folderSettings : undefined
}));
this.userLocalSettings = new Action('userSettings', localize('userSettings', "User"), '.settings-tab', true, () => this.updateTarget(ConfigurationTarget.USER_LOCAL));
this.preferencesService.getEditableSettingsURI(ConfigurationTarget.USER_LOCAL).then(uri => {
// Don't wait to create UI on resolving remote
this.userLocalSettings.tooltip = uri?.fsPath || '';
});
const remoteAuthority = this.environmentService.remoteAuthority;
const hostLabel = remoteAuthority && this.labelService.getHostLabel(Schemas.vscodeRemote, remoteAuthority);
const remoteSettingsLabel = localize('userSettingsRemote', "Remote") +
(hostLabel ? ` [${hostLabel}]` : '');
this.userRemoteSettings = new Action('userSettingsRemote', remoteSettingsLabel, '.settings-tab', true, () => this.updateTarget(ConfigurationTarget.USER_REMOTE));
this.preferencesService.getEditableSettingsURI(ConfigurationTarget.USER_REMOTE).then(uri => {
this.userRemoteSettings.tooltip = uri?.fsPath || '';
});
this.workspaceSettings = new Action('workspaceSettings', localize('workspaceSettings', "Workspace"), '.settings-tab', false, () => this.updateTarget(ConfigurationTarget.WORKSPACE));
const folderSettingsAction = new Action('folderSettings', localize('folderSettings', "Folder"), '.settings-tab', false,
(folder: IWorkspaceFolder | null) => this.updateTarget(folder ? folder.uri : ConfigurationTarget.USER_LOCAL));
this.folderSettings = this.instantiationService.createInstance(FolderSettingsActionViewItem, folderSettingsAction);
this.update();
this.settingsSwitcherBar.push([this.userLocalSettings, this.userRemoteSettings, this.workspaceSettings, folderSettingsAction]);
}
get settingsTarget(): SettingsTarget | null {
return this._settingsTarget;
}
set settingsTarget(settingsTarget: SettingsTarget | null) {
this._settingsTarget = settingsTarget;
this.userLocalSettings.checked = ConfigurationTarget.USER_LOCAL === this.settingsTarget;
this.userRemoteSettings.checked = ConfigurationTarget.USER_REMOTE === this.settingsTarget;
this.workspaceSettings.checked = ConfigurationTarget.WORKSPACE === this.settingsTarget;
if (this.settingsTarget instanceof URI) {
this.folderSettings.getAction().checked = true;
this.folderSettings.folder = this.contextService.getWorkspaceFolder(this.settingsTarget as URI);
} else {
this.folderSettings.getAction().checked = false;
}
}
setResultCount(settingsTarget: SettingsTarget, count: number): void {
if (settingsTarget === ConfigurationTarget.WORKSPACE) {
let label = localize('workspaceSettings', "Workspace");
if (count) {
label += ` (${count})`;
}
this.workspaceSettings.label = label;
} else if (settingsTarget === ConfigurationTarget.USER_LOCAL) {
let label = localize('userSettings', "User");
if (count) {
label += ` (${count})`;
}
this.userLocalSettings.label = label;
} else if (settingsTarget instanceof URI) {
this.folderSettings.setCount(settingsTarget, count);
}
}
private onWorkbenchStateChanged(): void {
this.folderSettings.folder = null;
this.update();
if (this.settingsTarget === ConfigurationTarget.WORKSPACE && this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE) {
this.updateTarget(ConfigurationTarget.USER_LOCAL);
}
}
updateTarget(settingsTarget: SettingsTarget): Promise<void> {
const isSameTarget = this.settingsTarget === settingsTarget ||
settingsTarget instanceof URI &&
this.settingsTarget instanceof URI &&
isEqual(this.settingsTarget, settingsTarget);
if (!isSameTarget) {
this.settingsTarget = settingsTarget;
this._onDidTargetChange.fire(this.settingsTarget);
}
return Promise.resolve(undefined);
}
private async update(): Promise<void> {
this.settingsSwitcherBar.domNode.classList.toggle('empty-workbench', this.contextService.getWorkbenchState() === WorkbenchState.EMPTY);
this.userRemoteSettings.enabled = !!(this.options.enableRemoteSettings && this.environmentService.remoteAuthority);
this.workspaceSettings.enabled = this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY;
this.folderSettings.getAction().enabled = this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE && this.contextService.getWorkspace().folders.length > 0;
this.workspaceSettings.tooltip = (await this.preferencesService.getEditableSettingsURI(ConfigurationTarget.WORKSPACE))?.fsPath || '';
}
}
export interface SearchOptions extends IInputOptions {
focusKey?: IContextKey<boolean>;
showResultCount?: boolean;
ariaLive?: string;
ariaLabelledBy?: string;
}
export class SearchWidget extends Widget {
domNode!: HTMLElement;
private countElement!: HTMLElement;
private searchContainer!: HTMLElement;
inputBox!: InputBox;
private controlsDiv!: HTMLElement;
private readonly _onDidChange: Emitter<string> = this._register(new Emitter<string>());
readonly onDidChange: Event<string> = this._onDidChange.event;
private readonly _onFocus: Emitter<void> = this._register(new Emitter<void>());
readonly onFocus: Event<void> = this._onFocus.event;
constructor(parent: HTMLElement, protected options: SearchOptions,
@IContextViewService private readonly contextViewService: IContextViewService,
@IInstantiationService protected instantiationService: IInstantiationService,
@IThemeService private readonly themeService: IThemeService
) {
super();
this.create(parent);
}
private create(parent: HTMLElement) {
this.domNode = DOM.append(parent, DOM.$('div.settings-header-widget'));
this.createSearchContainer(DOM.append(this.domNode, DOM.$('div.settings-search-container')));
this.controlsDiv = DOM.append(this.domNode, DOM.$('div.settings-search-controls'));
if (this.options.showResultCount) {
this.countElement = DOM.append(this.controlsDiv, DOM.$('.settings-count-widget'));
this._register(attachStylerCallback(this.themeService, { badgeBackground, contrastBorder }, colors => {
const background = colors.badgeBackground ? colors.badgeBackground.toString() : '';
const border = colors.contrastBorder ? colors.contrastBorder.toString() : '';
this.countElement.style.backgroundColor = background;
this.countElement.style.borderWidth = border ? '1px' : '';
this.countElement.style.borderStyle = border ? 'solid' : '';
this.countElement.style.borderColor = border;
const color = this.themeService.getColorTheme().getColor(badgeForeground);
this.countElement.style.color = color ? color.toString() : '';
}));
}
this.inputBox.inputElement.setAttribute('aria-live', this.options.ariaLive || 'off');
if (this.options.ariaLabelledBy) {
this.inputBox.inputElement.setAttribute('aria-labelledBy', this.options.ariaLabelledBy);
}
const focusTracker = this._register(DOM.trackFocus(this.inputBox.inputElement));
this._register(focusTracker.onDidFocus(() => this._onFocus.fire()));
const focusKey = this.options.focusKey;
if (focusKey) {
this._register(focusTracker.onDidFocus(() => focusKey.set(true)));
this._register(focusTracker.onDidBlur(() => focusKey.set(false)));
}
}
private createSearchContainer(searchContainer: HTMLElement) {
this.searchContainer = searchContainer;
const searchInput = DOM.append(this.searchContainer, DOM.$('div.settings-search-input'));
this.inputBox = this._register(this.createInputBox(searchInput));
this._register(this.inputBox.onDidChange(value => this._onDidChange.fire(value)));
}
protected createInputBox(parent: HTMLElement): InputBox {
const box = this._register(new InputBox(parent, this.contextViewService, this.options));
this._register(attachInputBoxStyler(box, this.themeService));
return box;
}
showMessage(message: string): void {
// Avoid setting the aria-label unnecessarily, the screenreader will read the count every time it's set, since it's aria-live:assertive. #50968
if (this.countElement && message !== this.countElement.textContent) {
this.countElement.textContent = message;
this.inputBox.inputElement.setAttribute('aria-label', message);
this.inputBox.inputElement.style.paddingRight = this.getControlsWidth() + 'px';
}
}
layout(dimension: DOM.Dimension) {
if (dimension.width < 400) {
if (this.countElement) {
this.countElement.classList.add('hide');
}
this.inputBox.inputElement.style.paddingRight = '0px';
} else {
if (this.countElement) {
this.countElement.classList.remove('hide');
}
this.inputBox.inputElement.style.paddingRight = this.getControlsWidth() + 'px';
}
}
private getControlsWidth(): number {
const countWidth = this.countElement ? DOM.getTotalWidth(this.countElement) : 0;
return countWidth + 20;
}
focus() {
this.inputBox.focus();
if (this.getValue()) {
this.inputBox.select();
}
}
hasFocus(): boolean {
return this.inputBox.hasFocus();
}
clear() {
this.inputBox.value = '';
}
getValue(): string {
return this.inputBox.value;
}
setValue(value: string): string {
return this.inputBox.value = value;
}
dispose(): void {
if (this.options.focusKey) {
this.options.focusKey.set(false);
}
super.dispose();
}
}
export const preferencesEditIcon = registerIcon('preferences-edit', Codicon.edit, localize('preferencesEditIcon', 'Icon for the edit action in preferences.'));
export class EditPreferenceWidget<T> extends Disposable {
private _line: number = -1;
private _preferences: T[] = [];
private _editPreferenceDecoration: string[];
private readonly _onClick = this._register(new Emitter<IEditorMouseEvent>());
readonly onClick: Event<IEditorMouseEvent> = this._onClick.event;
constructor(private editor: ICodeEditor
) {
super();
this._editPreferenceDecoration = [];
this._register(this.editor.onMouseDown((e: IEditorMouseEvent) => {
const data = e.target.detail as IMarginData;
if (e.target.type !== MouseTargetType.GUTTER_GLYPH_MARGIN || data.isAfterLines || !this.isVisible()) {
return;
}
this._onClick.fire(e);
}));
}
get preferences(): T[] {
return this._preferences;
}
getLine(): number {
return this._line;
}
show(line: number, hoverMessage: string, preferences: T[]): void {
this._preferences = preferences;
const newDecoration: IModelDeltaDecoration[] = [];
this._line = line;
newDecoration.push({
options: {
glyphMarginClassName: preferencesEditIcon.classNames,
glyphMarginHoverMessage: new MarkdownString().appendText(hoverMessage),
stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
},
range: {
startLineNumber: line,
startColumn: 1,
endLineNumber: line,
endColumn: 1
}
});
this._editPreferenceDecoration = this.editor.deltaDecorations(this._editPreferenceDecoration, newDecoration);
}
hide(): void {
this._editPreferenceDecoration = this.editor.deltaDecorations(this._editPreferenceDecoration, []);
}
isVisible(): boolean {
return this._editPreferenceDecoration.length > 0;
}
dispose(): void {
this.hide();
super.dispose();
}
}
registerThemingParticipant((theme: IColorTheme, collector: ICssStyleCollector) => {
collector.addRule(`
.settings-tabs-widget > .monaco-action-bar .action-item .action-label:focus,
.settings-tabs-widget > .monaco-action-bar .action-item .action-label.checked {
border-bottom: 1px solid;
}
`);
// Title Active
const titleActive = theme.getColor(PANEL_ACTIVE_TITLE_FOREGROUND);
const titleActiveBorder = theme.getColor(PANEL_ACTIVE_TITLE_BORDER);
if (titleActive || titleActiveBorder) {
collector.addRule(`
.settings-tabs-widget > .monaco-action-bar .action-item .action-label:hover,
.settings-tabs-widget > .monaco-action-bar .action-item .action-label.checked {
color: ${titleActive};
border-bottom-color: ${titleActiveBorder};
}
`);
}
// Title Inactive
const titleInactive = theme.getColor(PANEL_INACTIVE_TITLE_FOREGROUND);
if (titleInactive) {
collector.addRule(`
.settings-tabs-widget > .monaco-action-bar .action-item .action-label {
color: ${titleInactive};
}
`);
}
// Title focus
const focusBorderColor = theme.getColor(focusBorder);
if (focusBorderColor) {
collector.addRule(`
.settings-tabs-widget > .monaco-action-bar .action-item .action-label:focus {
border-bottom-color: ${focusBorderColor} !important;
}
`);
collector.addRule(`
.settings-tabs-widget > .monaco-action-bar .action-item .action-label:focus {
outline: none;
}
`);
}
// Styling with Outline color (e.g. high contrast theme)
const outline = theme.getColor(activeContrastBorder);
if (outline) {
const outline = theme.getColor(activeContrastBorder);
collector.addRule(`
.settings-tabs-widget > .monaco-action-bar .action-item .action-label.checked,
.settings-tabs-widget > .monaco-action-bar .action-item .action-label:hover {
outline-color: ${outline};
outline-width: 1px;
outline-style: solid;
border-bottom: none;
padding-bottom: 0;
outline-offset: -1px;
}
.settings-tabs-widget > .monaco-action-bar .action-item .action-label:not(.checked):hover {
outline-style: dashed;
}
`);
}
});
| src/vs/workbench/contrib/preferences/browser/preferencesWidgets.ts | 0 | https://github.com/microsoft/vscode/commit/0fc17285e1f612f63deddaaa206f08162f190ec2 | [
0.00017458760703448206,
0.00016999167564790696,
0.00016392154793720692,
0.00017027376452460885,
0.0000022157437342684716
] |
{
"id": 1,
"code_window": [
"\t\tif (e.affectsConfiguration('emmet.extensionsPath')) {\n",
"\t\t\tupdateEmmetExtensionsPath();\n",
"\t\t}\n",
"\t}));\n",
"}\n",
"\n",
"/**\n",
" * Holds any registered completion providers by their language strings\n",
" */\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
"\tcontext.subscriptions.push(vscode.workspace.onDidSaveTextDocument((e) => {\n",
"\t\tconst basefileName: string = getPathBaseName(e.fileName);\n",
"\t\tif (basefileName.startsWith('snippets') && basefileName.endsWith('.json')) {\n",
"\t\t\tupdateEmmetExtensionsPath();\n",
"\t\t}\n",
"\t}));\n"
],
"file_path": "extensions/emmet/src/emmetCommon.ts",
"type": "add",
"edit_start_line_idx": 136
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import type * as vscode from 'vscode';
import { Event, Emitter } from 'vs/base/common/event';
import { ExtHostTerminalServiceShape, MainContext, MainThreadTerminalServiceShape, IShellLaunchConfigDto, IShellDefinitionDto, IShellAndArgsDto, ITerminalDimensionsDto, ITerminalLinkDto } from 'vs/workbench/api/common/extHost.protocol';
import { ExtHostConfigProvider } from 'vs/workbench/api/common/extHostConfiguration';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { URI, UriComponents } from 'vs/base/common/uri';
import { ITerminalChildProcess, ITerminalDimensions, EXT_HOST_CREATION_DELAY, ITerminalLaunchError } from 'vs/workbench/contrib/terminal/common/terminal';
import { timeout } from 'vs/base/common/async';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
import { TerminalDataBufferer } from 'vs/workbench/contrib/terminal/common/terminalDataBuffering';
import { IDisposable, DisposableStore, Disposable } from 'vs/base/common/lifecycle';
import { Disposable as VSCodeDisposable, EnvironmentVariableMutatorType } from './extHostTypes';
import { IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { ISerializableEnvironmentVariableCollection } from 'vs/workbench/contrib/terminal/common/environmentVariable';
import { localize } from 'vs/nls';
import { NotSupportedError } from 'vs/base/common/errors';
import { serializeEnvironmentVariableCollection } from 'vs/workbench/contrib/terminal/common/environmentVariableShared';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
export interface IExtHostTerminalService extends ExtHostTerminalServiceShape, IDisposable {
readonly _serviceBrand: undefined;
activeTerminal: vscode.Terminal | undefined;
terminals: vscode.Terminal[];
onDidCloseTerminal: Event<vscode.Terminal>;
onDidOpenTerminal: Event<vscode.Terminal>;
onDidChangeActiveTerminal: Event<vscode.Terminal | undefined>;
onDidChangeTerminalDimensions: Event<vscode.TerminalDimensionsChangeEvent>;
onDidWriteTerminalData: Event<vscode.TerminalDataWriteEvent>;
createTerminal(name?: string, shellPath?: string, shellArgs?: string[] | string): vscode.Terminal;
createTerminalFromOptions(options: vscode.TerminalOptions): vscode.Terminal;
createExtensionTerminal(options: vscode.ExtensionTerminalOptions): vscode.Terminal;
attachPtyToTerminal(id: number, pty: vscode.Pseudoterminal): void;
getDefaultShell(useAutomationShell: boolean, configProvider: ExtHostConfigProvider): string;
getDefaultShellArgs(useAutomationShell: boolean, configProvider: ExtHostConfigProvider): string[] | string;
registerLinkProvider(provider: vscode.TerminalLinkProvider): vscode.Disposable;
getEnvironmentVariableCollection(extension: IExtensionDescription, persistent?: boolean): vscode.EnvironmentVariableCollection;
}
export const IExtHostTerminalService = createDecorator<IExtHostTerminalService>('IExtHostTerminalService');
export class BaseExtHostTerminal {
public _id: number | undefined;
protected _idPromise: Promise<number>;
private _idPromiseComplete: ((value: number) => any) | undefined;
private _disposed: boolean = false;
private _queuedRequests: ApiRequest[] = [];
constructor(
protected _proxy: MainThreadTerminalServiceShape,
id?: number
) {
this._idPromise = new Promise<number>(c => {
if (id !== undefined) {
this._id = id;
c(id);
} else {
this._idPromiseComplete = c;
}
});
}
public dispose(): void {
if (!this._disposed) {
this._disposed = true;
this._queueApiRequest(this._proxy.$dispose, []);
}
}
protected _checkDisposed() {
if (this._disposed) {
throw new Error('Terminal has already been disposed');
}
}
protected _queueApiRequest(callback: (...args: any[]) => void, args: any[]): void {
const request: ApiRequest = new ApiRequest(callback, args);
if (!this._id) {
this._queuedRequests.push(request);
return;
}
request.run(this._proxy, this._id);
}
public _runQueuedRequests(id: number): void {
this._id = id;
if (this._idPromiseComplete) {
this._idPromiseComplete(id);
this._idPromiseComplete = undefined;
}
this._queuedRequests.forEach((r) => {
r.run(this._proxy, id);
});
this._queuedRequests.length = 0;
}
}
export class ExtHostTerminal extends BaseExtHostTerminal implements vscode.Terminal {
private _pidPromise: Promise<number | undefined>;
private _cols: number | undefined;
private _pidPromiseComplete: ((value: number | undefined) => any) | undefined;
private _rows: number | undefined;
private _exitStatus: vscode.TerminalExitStatus | undefined;
public isOpen: boolean = false;
constructor(
proxy: MainThreadTerminalServiceShape,
private readonly _creationOptions: vscode.TerminalOptions | vscode.ExtensionTerminalOptions,
private _name?: string,
id?: number
) {
super(proxy, id);
this._creationOptions = Object.freeze(this._creationOptions);
this._pidPromise = new Promise<number | undefined>(c => this._pidPromiseComplete = c);
}
public async create(
shellPath?: string,
shellArgs?: string[] | string,
cwd?: string | URI,
env?: { [key: string]: string | null },
waitOnExit?: boolean,
strictEnv?: boolean,
hideFromUser?: boolean
): Promise<void> {
const result = await this._proxy.$createTerminal({ name: this._name, shellPath, shellArgs, cwd, env, waitOnExit, strictEnv, hideFromUser });
this._name = result.name;
this._runQueuedRequests(result.id);
}
public async createExtensionTerminal(): Promise<number> {
const result = await this._proxy.$createTerminal({ name: this._name, isExtensionTerminal: true });
this._name = result.name;
this._runQueuedRequests(result.id);
return result.id;
}
public get name(): string {
return this._name || '';
}
public set name(name: string) {
this._name = name;
}
public get exitStatus(): vscode.TerminalExitStatus | undefined {
return this._exitStatus;
}
public get dimensions(): vscode.TerminalDimensions | undefined {
if (this._cols === undefined || this._rows === undefined) {
return undefined;
}
return {
columns: this._cols,
rows: this._rows
};
}
public setExitCode(code: number | undefined) {
this._exitStatus = Object.freeze({ code });
}
public setDimensions(cols: number, rows: number): boolean {
if (cols === this._cols && rows === this._rows) {
// Nothing changed
return false;
}
if (cols === 0 || rows === 0) {
return false;
}
this._cols = cols;
this._rows = rows;
return true;
}
public get processId(): Promise<number | undefined> {
return this._pidPromise;
}
public get creationOptions(): Readonly<vscode.TerminalOptions | vscode.ExtensionTerminalOptions> {
return this._creationOptions;
}
public sendText(text: string, addNewLine: boolean = true): void {
this._checkDisposed();
this._queueApiRequest(this._proxy.$sendText, [text, addNewLine]);
}
public show(preserveFocus: boolean): void {
this._checkDisposed();
this._queueApiRequest(this._proxy.$show, [preserveFocus]);
}
public hide(): void {
this._checkDisposed();
this._queueApiRequest(this._proxy.$hide, []);
}
public _setProcessId(processId: number | undefined): void {
// The event may fire 2 times when the panel is restored
if (this._pidPromiseComplete) {
this._pidPromiseComplete(processId);
this._pidPromiseComplete = undefined;
} else {
// Recreate the promise if this is the nth processId set (e.g. reused task terminals)
this._pidPromise.then(pid => {
if (pid !== processId) {
this._pidPromise = Promise.resolve(processId);
}
});
}
}
}
class ApiRequest {
private _callback: (...args: any[]) => void;
private _args: any[];
constructor(callback: (...args: any[]) => void, args: any[]) {
this._callback = callback;
this._args = args;
}
public run(proxy: MainThreadTerminalServiceShape, id: number) {
this._callback.apply(proxy, [id].concat(this._args));
}
}
export class ExtHostPseudoterminal implements ITerminalChildProcess {
private readonly _onProcessData = new Emitter<string>();
public readonly onProcessData: Event<string> = this._onProcessData.event;
private readonly _onProcessExit = new Emitter<number | undefined>();
public readonly onProcessExit: Event<number | undefined> = this._onProcessExit.event;
private readonly _onProcessReady = new Emitter<{ pid: number, cwd: string }>();
public get onProcessReady(): Event<{ pid: number, cwd: string }> { return this._onProcessReady.event; }
private readonly _onProcessTitleChanged = new Emitter<string>();
public readonly onProcessTitleChanged: Event<string> = this._onProcessTitleChanged.event;
private readonly _onProcessOverrideDimensions = new Emitter<ITerminalDimensions | undefined>();
public get onProcessOverrideDimensions(): Event<ITerminalDimensions | undefined> { return this._onProcessOverrideDimensions.event; }
constructor(private readonly _pty: vscode.Pseudoterminal) { }
async start(): Promise<undefined> {
return undefined;
}
shutdown(): void {
this._pty.close();
}
input(data: string): void {
if (this._pty.handleInput) {
this._pty.handleInput(data);
}
}
resize(cols: number, rows: number): void {
if (this._pty.setDimensions) {
this._pty.setDimensions({ columns: cols, rows });
}
}
getInitialCwd(): Promise<string> {
return Promise.resolve('');
}
getCwd(): Promise<string> {
return Promise.resolve('');
}
getLatency(): Promise<number> {
return Promise.resolve(0);
}
startSendingEvents(initialDimensions: ITerminalDimensionsDto | undefined): void {
// Attach the listeners
this._pty.onDidWrite(e => this._onProcessData.fire(e));
if (this._pty.onDidClose) {
this._pty.onDidClose((e: number | void = undefined) => {
this._onProcessExit.fire(e === void 0 ? undefined : e);
});
}
if (this._pty.onDidOverrideDimensions) {
this._pty.onDidOverrideDimensions(e => this._onProcessOverrideDimensions.fire(e ? { cols: e.columns, rows: e.rows } : e));
}
this._pty.open(initialDimensions ? initialDimensions : undefined);
this._onProcessReady.fire({ pid: -1, cwd: '' });
}
}
let nextLinkId = 1;
interface ICachedLinkEntry {
provider: vscode.TerminalLinkProvider;
link: vscode.TerminalLink;
}
export abstract class BaseExtHostTerminalService extends Disposable implements IExtHostTerminalService, ExtHostTerminalServiceShape {
readonly _serviceBrand: undefined;
protected _proxy: MainThreadTerminalServiceShape;
protected _activeTerminal: ExtHostTerminal | undefined;
protected _terminals: ExtHostTerminal[] = [];
protected _terminalProcesses: Map<number, ITerminalChildProcess> = new Map();
protected _terminalProcessDisposables: { [id: number]: IDisposable } = {};
protected _extensionTerminalAwaitingStart: { [id: number]: { initialDimensions: ITerminalDimensionsDto | undefined } | undefined } = {};
protected _getTerminalPromises: { [id: number]: Promise<ExtHostTerminal | undefined> } = {};
protected _environmentVariableCollections: Map<string, EnvironmentVariableCollection> = new Map();
private readonly _bufferer: TerminalDataBufferer;
private readonly _linkProviders: Set<vscode.TerminalLinkProvider> = new Set();
private readonly _terminalLinkCache: Map<number, Map<number, ICachedLinkEntry>> = new Map();
private readonly _terminalLinkCancellationSource: Map<number, CancellationTokenSource> = new Map();
public get activeTerminal(): ExtHostTerminal | undefined { return this._activeTerminal; }
public get terminals(): ExtHostTerminal[] { return this._terminals; }
protected readonly _onDidCloseTerminal: Emitter<vscode.Terminal> = new Emitter<vscode.Terminal>();
public get onDidCloseTerminal(): Event<vscode.Terminal> { return this._onDidCloseTerminal && this._onDidCloseTerminal.event; }
protected readonly _onDidOpenTerminal: Emitter<vscode.Terminal> = new Emitter<vscode.Terminal>();
public get onDidOpenTerminal(): Event<vscode.Terminal> { return this._onDidOpenTerminal && this._onDidOpenTerminal.event; }
protected readonly _onDidChangeActiveTerminal: Emitter<vscode.Terminal | undefined> = new Emitter<vscode.Terminal | undefined>();
public get onDidChangeActiveTerminal(): Event<vscode.Terminal | undefined> { return this._onDidChangeActiveTerminal && this._onDidChangeActiveTerminal.event; }
protected readonly _onDidChangeTerminalDimensions: Emitter<vscode.TerminalDimensionsChangeEvent> = new Emitter<vscode.TerminalDimensionsChangeEvent>();
public get onDidChangeTerminalDimensions(): Event<vscode.TerminalDimensionsChangeEvent> { return this._onDidChangeTerminalDimensions && this._onDidChangeTerminalDimensions.event; }
protected readonly _onDidWriteTerminalData: Emitter<vscode.TerminalDataWriteEvent>;
public get onDidWriteTerminalData(): Event<vscode.TerminalDataWriteEvent> { return this._onDidWriteTerminalData && this._onDidWriteTerminalData.event; }
constructor(
supportsProcesses: boolean,
@IExtHostRpcService extHostRpc: IExtHostRpcService
) {
super();
this._proxy = extHostRpc.getProxy(MainContext.MainThreadTerminalService);
this._bufferer = new TerminalDataBufferer(this._proxy.$sendProcessData);
this._onDidWriteTerminalData = new Emitter<vscode.TerminalDataWriteEvent>({
onFirstListenerAdd: () => this._proxy.$startSendingDataEvents(),
onLastListenerRemove: () => this._proxy.$stopSendingDataEvents()
});
this._proxy.$registerProcessSupport(supportsProcesses);
this._register({
dispose: () => {
for (const [_, terminalProcess] of this._terminalProcesses) {
terminalProcess.shutdown(true);
}
}
});
}
public abstract createTerminal(name?: string, shellPath?: string, shellArgs?: string[] | string): vscode.Terminal;
public abstract createTerminalFromOptions(options: vscode.TerminalOptions): vscode.Terminal;
public abstract getDefaultShell(useAutomationShell: boolean, configProvider: ExtHostConfigProvider): string;
public abstract getDefaultShellArgs(useAutomationShell: boolean, configProvider: ExtHostConfigProvider): string[] | string;
public abstract $spawnExtHostProcess(id: number, shellLaunchConfigDto: IShellLaunchConfigDto, activeWorkspaceRootUriComponents: UriComponents, cols: number, rows: number, isWorkspaceShellAllowed: boolean): Promise<ITerminalLaunchError | undefined>;
public abstract $getAvailableShells(): Promise<IShellDefinitionDto[]>;
public abstract $getDefaultShellAndArgs(useAutomationShell: boolean): Promise<IShellAndArgsDto>;
public abstract $acceptWorkspacePermissionsChanged(isAllowed: boolean): void;
public createExtensionTerminal(options: vscode.ExtensionTerminalOptions): vscode.Terminal {
const terminal = new ExtHostTerminal(this._proxy, options, options.name);
const p = new ExtHostPseudoterminal(options.pty);
terminal.createExtensionTerminal().then(id => {
const disposable = this._setupExtHostProcessListeners(id, p);
this._terminalProcessDisposables[id] = disposable;
});
this._terminals.push(terminal);
return terminal;
}
public attachPtyToTerminal(id: number, pty: vscode.Pseudoterminal): void {
const terminal = this._getTerminalByIdEventually(id);
if (!terminal) {
throw new Error(`Cannot resolve terminal with id ${id} for virtual process`);
}
const p = new ExtHostPseudoterminal(pty);
const disposable = this._setupExtHostProcessListeners(id, p);
this._terminalProcessDisposables[id] = disposable;
}
public async $acceptActiveTerminalChanged(id: number | null): Promise<void> {
const original = this._activeTerminal;
if (id === null) {
this._activeTerminal = undefined;
if (original !== this._activeTerminal) {
this._onDidChangeActiveTerminal.fire(this._activeTerminal);
}
return;
}
const terminal = await this._getTerminalByIdEventually(id);
if (terminal) {
this._activeTerminal = terminal;
if (original !== this._activeTerminal) {
this._onDidChangeActiveTerminal.fire(this._activeTerminal);
}
}
}
public async $acceptTerminalProcessData(id: number, data: string): Promise<void> {
const terminal = await this._getTerminalByIdEventually(id);
if (terminal) {
this._onDidWriteTerminalData.fire({ terminal, data });
}
}
public async $acceptTerminalDimensions(id: number, cols: number, rows: number): Promise<void> {
const terminal = await this._getTerminalByIdEventually(id);
if (terminal) {
if (terminal.setDimensions(cols, rows)) {
this._onDidChangeTerminalDimensions.fire({
terminal: terminal,
dimensions: terminal.dimensions as vscode.TerminalDimensions
});
}
}
}
public async $acceptTerminalMaximumDimensions(id: number, cols: number, rows: number): Promise<void> {
await this._getTerminalByIdEventually(id);
// Extension pty terminal only - when virtual process resize fires it means that the
// terminal's maximum dimensions changed
this._terminalProcesses.get(id)?.resize(cols, rows);
}
public async $acceptTerminalTitleChange(id: number, name: string): Promise<void> {
await this._getTerminalByIdEventually(id);
const extHostTerminal = this._getTerminalObjectById(this.terminals, id);
if (extHostTerminal) {
extHostTerminal.name = name;
}
}
public async $acceptTerminalClosed(id: number, exitCode: number | undefined): Promise<void> {
await this._getTerminalByIdEventually(id);
const index = this._getTerminalObjectIndexById(this.terminals, id);
if (index !== null) {
const terminal = this._terminals.splice(index, 1)[0];
terminal.setExitCode(exitCode);
this._onDidCloseTerminal.fire(terminal);
}
}
public $acceptTerminalOpened(id: number, name: string, shellLaunchConfigDto: IShellLaunchConfigDto): void {
const index = this._getTerminalObjectIndexById(this._terminals, id);
if (index !== null) {
// The terminal has already been created (via createTerminal*), only fire the event
this._onDidOpenTerminal.fire(this.terminals[index]);
this.terminals[index].isOpen = true;
return;
}
const creationOptions: vscode.TerminalOptions = {
name: shellLaunchConfigDto.name,
shellPath: shellLaunchConfigDto.executable,
shellArgs: shellLaunchConfigDto.args,
cwd: typeof shellLaunchConfigDto.cwd === 'string' ? shellLaunchConfigDto.cwd : URI.revive(shellLaunchConfigDto.cwd),
env: shellLaunchConfigDto.env,
hideFromUser: shellLaunchConfigDto.hideFromUser
};
const terminal = new ExtHostTerminal(this._proxy, creationOptions, name, id);
this._terminals.push(terminal);
this._onDidOpenTerminal.fire(terminal);
terminal.isOpen = true;
}
public async $acceptTerminalProcessId(id: number, processId: number): Promise<void> {
const terminal = await this._getTerminalByIdEventually(id);
if (terminal) {
terminal._setProcessId(processId);
}
}
public async $startExtensionTerminal(id: number, initialDimensions: ITerminalDimensionsDto | undefined): Promise<ITerminalLaunchError | undefined> {
// Make sure the ExtHostTerminal exists so onDidOpenTerminal has fired before we call
// Pseudoterminal.start
const terminal = await this._getTerminalByIdEventually(id);
if (!terminal) {
return { message: localize('launchFail.idMissingOnExtHost', "Could not find the terminal with id {0} on the extension host", id) };
}
// Wait for onDidOpenTerminal to fire
if (!terminal.isOpen) {
await new Promise<void>(r => {
// Ensure open is called after onDidOpenTerminal
const listener = this.onDidOpenTerminal(async e => {
if (e === terminal) {
listener.dispose();
r();
}
});
});
}
const terminalProcess = this._terminalProcesses.get(id);
if (terminalProcess) {
(terminalProcess as ExtHostPseudoterminal).startSendingEvents(initialDimensions);
} else {
// Defer startSendingEvents call to when _setupExtHostProcessListeners is called
this._extensionTerminalAwaitingStart[id] = { initialDimensions };
}
return undefined;
}
protected _setupExtHostProcessListeners(id: number, p: ITerminalChildProcess): IDisposable {
const disposables = new DisposableStore();
disposables.add(p.onProcessReady((e: { pid: number, cwd: string }) => this._proxy.$sendProcessReady(id, e.pid, e.cwd)));
disposables.add(p.onProcessTitleChanged(title => this._proxy.$sendProcessTitle(id, title)));
// Buffer data events to reduce the amount of messages going to the renderer
this._bufferer.startBuffering(id, p.onProcessData);
disposables.add(p.onProcessExit(exitCode => this._onProcessExit(id, exitCode)));
if (p.onProcessOverrideDimensions) {
disposables.add(p.onProcessOverrideDimensions(e => this._proxy.$sendOverrideDimensions(id, e)));
}
this._terminalProcesses.set(id, p);
const awaitingStart = this._extensionTerminalAwaitingStart[id];
if (awaitingStart && p instanceof ExtHostPseudoterminal) {
p.startSendingEvents(awaitingStart.initialDimensions);
delete this._extensionTerminalAwaitingStart[id];
}
return disposables;
}
public $acceptProcessInput(id: number, data: string): void {
this._terminalProcesses.get(id)?.input(data);
}
public $acceptProcessResize(id: number, cols: number, rows: number): void {
try {
this._terminalProcesses.get(id)?.resize(cols, rows);
} catch (error) {
// We tried to write to a closed pipe / channel.
if (error.code !== 'EPIPE' && error.code !== 'ERR_IPC_CHANNEL_CLOSED') {
throw (error);
}
}
}
public $acceptProcessShutdown(id: number, immediate: boolean): void {
this._terminalProcesses.get(id)?.shutdown(immediate);
}
public $acceptProcessRequestInitialCwd(id: number): void {
this._terminalProcesses.get(id)?.getInitialCwd().then(initialCwd => this._proxy.$sendProcessInitialCwd(id, initialCwd));
}
public $acceptProcessRequestCwd(id: number): void {
this._terminalProcesses.get(id)?.getCwd().then(cwd => this._proxy.$sendProcessCwd(id, cwd));
}
public $acceptProcessRequestLatency(id: number): number {
return id;
}
public registerLinkProvider(provider: vscode.TerminalLinkProvider): vscode.Disposable {
this._linkProviders.add(provider);
if (this._linkProviders.size === 1) {
this._proxy.$startLinkProvider();
}
return new VSCodeDisposable(() => {
this._linkProviders.delete(provider);
if (this._linkProviders.size === 0) {
this._proxy.$stopLinkProvider();
}
});
}
public async $provideLinks(terminalId: number, line: string): Promise<ITerminalLinkDto[]> {
const terminal = this._getTerminalById(terminalId);
if (!terminal) {
return [];
}
// Discard any cached links the terminal has been holding, currently all links are released
// when new links are provided.
this._terminalLinkCache.delete(terminalId);
const oldToken = this._terminalLinkCancellationSource.get(terminalId);
if (oldToken) {
oldToken.dispose(true);
}
const cancellationSource = new CancellationTokenSource();
this._terminalLinkCancellationSource.set(terminalId, cancellationSource);
const result: ITerminalLinkDto[] = [];
const context: vscode.TerminalLinkContext = { terminal, line };
const promises: vscode.ProviderResult<{ provider: vscode.TerminalLinkProvider, links: vscode.TerminalLink[] }>[] = [];
for (const provider of this._linkProviders) {
promises.push(new Promise(async r => {
cancellationSource.token.onCancellationRequested(() => r({ provider, links: [] }));
const links = (await provider.provideTerminalLinks(context, cancellationSource.token)) || [];
if (!cancellationSource.token.isCancellationRequested) {
r({ provider, links });
}
}));
}
const provideResults = await Promise.all(promises);
if (cancellationSource.token.isCancellationRequested) {
return [];
}
const cacheLinkMap = new Map<number, ICachedLinkEntry>();
for (const provideResult of provideResults) {
if (provideResult && provideResult.links.length > 0) {
result.push(...provideResult.links.map(providerLink => {
const link = {
id: nextLinkId++,
startIndex: providerLink.startIndex,
length: providerLink.length,
label: providerLink.tooltip
};
cacheLinkMap.set(link.id, {
provider: provideResult.provider,
link: providerLink
});
return link;
}));
}
}
this._terminalLinkCache.set(terminalId, cacheLinkMap);
return result;
}
$activateLink(terminalId: number, linkId: number): void {
const cachedLink = this._terminalLinkCache.get(terminalId)?.get(linkId);
if (!cachedLink) {
return;
}
cachedLink.provider.handleTerminalLink(cachedLink.link);
}
private _onProcessExit(id: number, exitCode: number | undefined): void {
this._bufferer.stopBuffering(id);
// Remove process reference
this._terminalProcesses.delete(id);
delete this._extensionTerminalAwaitingStart[id];
// Clean up process disposables
const processDiposable = this._terminalProcessDisposables[id];
if (processDiposable) {
processDiposable.dispose();
delete this._terminalProcessDisposables[id];
}
// Send exit event to main side
this._proxy.$sendProcessExit(id, exitCode);
}
// TODO: This could be improved by using a single promise and resolve it when the terminal is ready
private _getTerminalByIdEventually(id: number, retries: number = 5): Promise<ExtHostTerminal | undefined> {
if (!this._getTerminalPromises[id]) {
this._getTerminalPromises[id] = this._createGetTerminalPromise(id, retries);
}
return this._getTerminalPromises[id];
}
private _createGetTerminalPromise(id: number, retries: number = 5): Promise<ExtHostTerminal | undefined> {
return new Promise(c => {
if (retries === 0) {
c(undefined);
return;
}
const terminal = this._getTerminalById(id);
if (terminal) {
c(terminal);
} else {
// This should only be needed immediately after createTerminalRenderer is called as
// the ExtHostTerminal has not yet been iniitalized
timeout(EXT_HOST_CREATION_DELAY * 2).then(() => c(this._createGetTerminalPromise(id, retries - 1)));
}
});
}
private _getTerminalById(id: number): ExtHostTerminal | null {
return this._getTerminalObjectById(this._terminals, id);
}
private _getTerminalObjectById<T extends ExtHostTerminal>(array: T[], id: number): T | null {
const index = this._getTerminalObjectIndexById(array, id);
return index !== null ? array[index] : null;
}
private _getTerminalObjectIndexById<T extends ExtHostTerminal>(array: T[], id: number): number | null {
let index: number | null = null;
array.some((item, i) => {
const thisId = item._id;
if (thisId === id) {
index = i;
return true;
}
return false;
});
return index;
}
public getEnvironmentVariableCollection(extension: IExtensionDescription): vscode.EnvironmentVariableCollection {
let collection = this._environmentVariableCollections.get(extension.identifier.value);
if (!collection) {
collection = new EnvironmentVariableCollection();
this._setEnvironmentVariableCollection(extension.identifier.value, collection);
}
return collection;
}
private _syncEnvironmentVariableCollection(extensionIdentifier: string, collection: EnvironmentVariableCollection): void {
const serialized = serializeEnvironmentVariableCollection(collection.map);
this._proxy.$setEnvironmentVariableCollection(extensionIdentifier, collection.persistent, serialized.length === 0 ? undefined : serialized);
}
public $initEnvironmentVariableCollections(collections: [string, ISerializableEnvironmentVariableCollection][]): void {
collections.forEach(entry => {
const extensionIdentifier = entry[0];
const collection = new EnvironmentVariableCollection(entry[1]);
this._setEnvironmentVariableCollection(extensionIdentifier, collection);
});
}
private _setEnvironmentVariableCollection(extensionIdentifier: string, collection: EnvironmentVariableCollection): void {
this._environmentVariableCollections.set(extensionIdentifier, collection);
collection.onDidChangeCollection(() => {
// When any collection value changes send this immediately, this is done to ensure
// following calls to createTerminal will be created with the new environment. It will
// result in more noise by sending multiple updates when called but collections are
// expected to be small.
this._syncEnvironmentVariableCollection(extensionIdentifier, collection!);
});
}
}
export class EnvironmentVariableCollection implements vscode.EnvironmentVariableCollection {
readonly map: Map<string, vscode.EnvironmentVariableMutator> = new Map();
private _persistent: boolean = true;
public get persistent(): boolean { return this._persistent; }
public set persistent(value: boolean) {
this._persistent = value;
this._onDidChangeCollection.fire();
}
protected readonly _onDidChangeCollection: Emitter<void> = new Emitter<void>();
get onDidChangeCollection(): Event<void> { return this._onDidChangeCollection && this._onDidChangeCollection.event; }
constructor(
serialized?: ISerializableEnvironmentVariableCollection
) {
this.map = new Map(serialized);
}
get size(): number {
return this.map.size;
}
replace(variable: string, value: string): void {
this._setIfDiffers(variable, { value, type: EnvironmentVariableMutatorType.Replace });
}
append(variable: string, value: string): void {
this._setIfDiffers(variable, { value, type: EnvironmentVariableMutatorType.Append });
}
prepend(variable: string, value: string): void {
this._setIfDiffers(variable, { value, type: EnvironmentVariableMutatorType.Prepend });
}
private _setIfDiffers(variable: string, mutator: vscode.EnvironmentVariableMutator): void {
const current = this.map.get(variable);
if (!current || current.value !== mutator.value || current.type !== mutator.type) {
this.map.set(variable, mutator);
this._onDidChangeCollection.fire();
}
}
get(variable: string): vscode.EnvironmentVariableMutator | undefined {
return this.map.get(variable);
}
forEach(callback: (variable: string, mutator: vscode.EnvironmentVariableMutator, collection: vscode.EnvironmentVariableCollection) => any, thisArg?: any): void {
this.map.forEach((value, key) => callback.call(thisArg, key, value, this));
}
delete(variable: string): void {
this.map.delete(variable);
this._onDidChangeCollection.fire();
}
clear(): void {
this.map.clear();
this._onDidChangeCollection.fire();
}
}
export class WorkerExtHostTerminalService extends BaseExtHostTerminalService {
constructor(
@IExtHostRpcService extHostRpc: IExtHostRpcService
) {
super(false, extHostRpc);
}
public createTerminal(name?: string, shellPath?: string, shellArgs?: string[] | string): vscode.Terminal {
throw new NotSupportedError();
}
public createTerminalFromOptions(options: vscode.TerminalOptions): vscode.Terminal {
throw new NotSupportedError();
}
public getDefaultShell(useAutomationShell: boolean, configProvider: ExtHostConfigProvider): string {
// Return the empty string to avoid throwing
return '';
}
public getDefaultShellArgs(useAutomationShell: boolean, configProvider: ExtHostConfigProvider): string[] | string {
throw new NotSupportedError();
}
public $spawnExtHostProcess(id: number, shellLaunchConfigDto: IShellLaunchConfigDto, activeWorkspaceRootUriComponents: UriComponents, cols: number, rows: number, isWorkspaceShellAllowed: boolean): Promise<ITerminalLaunchError | undefined> {
throw new NotSupportedError();
}
public $getAvailableShells(): Promise<IShellDefinitionDto[]> {
throw new NotSupportedError();
}
public async $getDefaultShellAndArgs(useAutomationShell: boolean): Promise<IShellAndArgsDto> {
throw new NotSupportedError();
}
public $acceptWorkspacePermissionsChanged(isAllowed: boolean): void {
// No-op for web worker ext host as workspace permissions aren't used
}
}
| src/vs/workbench/api/common/extHostTerminalService.ts | 0 | https://github.com/microsoft/vscode/commit/0fc17285e1f612f63deddaaa206f08162f190ec2 | [
0.0002246313088107854,
0.00017060253594536334,
0.00016376454732380807,
0.00017032321193255484,
0.000006194171874085441
] |
{
"id": 2,
"code_window": [
"}\n",
"\n",
"export function toLSTextDocument(doc: vscode.TextDocument): LSTextDocument {\n",
"\treturn LSTextDocument.create(doc.uri.toString(), doc.languageId, doc.version, doc.getText());\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"export function getPathBaseName(path: string): string {\n",
"\tconst pathAfterSlashSplit = path.split('/').pop();\n",
"\tconst pathAfterBackslashSplit = pathAfterSlashSplit ? pathAfterSlashSplit.split('\\\\').pop() : '';\n",
"\treturn pathAfterBackslashSplit ?? '';\n",
"}"
],
"file_path": "extensions/emmet/src/util.ts",
"type": "add",
"edit_start_line_idx": 649
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { DefaultCompletionItemProvider } from './defaultCompletionProvider';
import { expandEmmetAbbreviation, wrapWithAbbreviation, wrapIndividualLinesWithAbbreviation } from './abbreviationActions';
import { removeTag } from './removeTag';
import { updateTag } from './updateTag';
import { matchTag } from './matchTag';
import { balanceOut, balanceIn } from './balance';
import { splitJoinTag } from './splitJoinTag';
import { mergeLines } from './mergeLines';
import { toggleComment } from './toggleComment';
import { fetchEditPoint } from './editPoint';
import { fetchSelectItem } from './selectItem';
import { evaluateMathExpression } from './evaluateMathExpression';
import { incrementDecrement } from './incrementDecrement';
import { LANGUAGE_MODES, getMappingForIncludedLanguages, updateEmmetExtensionsPath } from './util';
import { reflectCssValue } from './reflectCssValue';
export function activateEmmetExtension(context: vscode.ExtensionContext) {
registerCompletionProviders(context);
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.wrapWithAbbreviation', (args) => {
wrapWithAbbreviation(args);
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.wrapIndividualLinesWithAbbreviation', (args) => {
wrapIndividualLinesWithAbbreviation(args);
}));
context.subscriptions.push(vscode.commands.registerCommand('emmet.expandAbbreviation', (args) => {
expandEmmetAbbreviation(args);
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.removeTag', () => {
return removeTag();
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.updateTag', (inputTag) => {
if (inputTag && typeof inputTag === 'string') {
return updateTag(inputTag);
}
return vscode.window.showInputBox({ prompt: 'Enter Tag' }).then(tagName => {
if (tagName) {
const update = updateTag(tagName);
return update ? update : false;
}
return false;
});
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.matchTag', () => {
matchTag();
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.balanceOut', () => {
balanceOut();
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.balanceIn', () => {
balanceIn();
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.splitJoinTag', () => {
return splitJoinTag();
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.mergeLines', () => {
mergeLines();
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.toggleComment', () => {
toggleComment();
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.nextEditPoint', () => {
fetchEditPoint('next');
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.prevEditPoint', () => {
fetchEditPoint('prev');
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.selectNextItem', () => {
fetchSelectItem('next');
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.selectPrevItem', () => {
fetchSelectItem('prev');
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.evaluateMathExpression', () => {
evaluateMathExpression();
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.incrementNumberByOneTenth', () => {
return incrementDecrement(0.1);
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.incrementNumberByOne', () => {
return incrementDecrement(1);
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.incrementNumberByTen', () => {
return incrementDecrement(10);
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.decrementNumberByOneTenth', () => {
return incrementDecrement(-0.1);
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.decrementNumberByOne', () => {
return incrementDecrement(-1);
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.decrementNumberByTen', () => {
return incrementDecrement(-10);
}));
context.subscriptions.push(vscode.commands.registerCommand('editor.emmet.action.reflectCSSValue', () => {
return reflectCssValue();
}));
updateEmmetExtensionsPath();
context.subscriptions.push(vscode.workspace.onDidChangeConfiguration((e) => {
if (e.affectsConfiguration('emmet.includeLanguages')) {
registerCompletionProviders(context);
}
if (e.affectsConfiguration('emmet.extensionsPath')) {
updateEmmetExtensionsPath();
}
}));
}
/**
* Holds any registered completion providers by their language strings
*/
const languageMappingForCompletionProviders: Map<string, string> = new Map<string, string>();
const completionProvidersMapping: Map<string, vscode.Disposable> = new Map<string, vscode.Disposable>();
function registerCompletionProviders(context: vscode.ExtensionContext) {
let completionProvider = new DefaultCompletionItemProvider();
let includedLanguages = getMappingForIncludedLanguages();
Object.keys(includedLanguages).forEach(language => {
if (languageMappingForCompletionProviders.has(language) && languageMappingForCompletionProviders.get(language) === includedLanguages[language]) {
return;
}
if (languageMappingForCompletionProviders.has(language)) {
const mapping = completionProvidersMapping.get(language);
if (mapping) {
mapping.dispose();
}
languageMappingForCompletionProviders.delete(language);
completionProvidersMapping.delete(language);
}
const provider = vscode.languages.registerCompletionItemProvider({ language, scheme: '*' }, completionProvider, ...LANGUAGE_MODES[includedLanguages[language]]);
context.subscriptions.push(provider);
languageMappingForCompletionProviders.set(language, includedLanguages[language]);
completionProvidersMapping.set(language, provider);
});
Object.keys(LANGUAGE_MODES).forEach(language => {
if (!languageMappingForCompletionProviders.has(language)) {
const provider = vscode.languages.registerCompletionItemProvider({ language, scheme: '*' }, completionProvider, ...LANGUAGE_MODES[language]);
context.subscriptions.push(provider);
languageMappingForCompletionProviders.set(language, language);
completionProvidersMapping.set(language, provider);
}
});
}
export function deactivate() {
}
| extensions/emmet/src/emmetCommon.ts | 1 | https://github.com/microsoft/vscode/commit/0fc17285e1f612f63deddaaa206f08162f190ec2 | [
0.00017465722339693457,
0.0001693685189820826,
0.0001647905446588993,
0.00017028885486070067,
0.0000028466370167734567
] |
{
"id": 2,
"code_window": [
"}\n",
"\n",
"export function toLSTextDocument(doc: vscode.TextDocument): LSTextDocument {\n",
"\treturn LSTextDocument.create(doc.uri.toString(), doc.languageId, doc.version, doc.getText());\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"export function getPathBaseName(path: string): string {\n",
"\tconst pathAfterSlashSplit = path.split('/').pop();\n",
"\tconst pathAfterBackslashSplit = pathAfterSlashSplit ? pathAfterSlashSplit.split('\\\\').pop() : '';\n",
"\treturn pathAfterBackslashSplit ?? '';\n",
"}"
],
"file_path": "extensions/emmet/src/util.ts",
"type": "add",
"edit_start_line_idx": 649
} | {
"extends": "../../shared.tsconfig.json",
"compilerOptions": {
"outDir": "./out"
},
"include": [
"src/**/*"
]
} | extensions/json-language-features/client/tsconfig.json | 0 | https://github.com/microsoft/vscode/commit/0fc17285e1f612f63deddaaa206f08162f190ec2 | [
0.00017345909145660698,
0.00017345909145660698,
0.00017345909145660698,
0.00017345909145660698,
0
] |
{
"id": 2,
"code_window": [
"}\n",
"\n",
"export function toLSTextDocument(doc: vscode.TextDocument): LSTextDocument {\n",
"\treturn LSTextDocument.create(doc.uri.toString(), doc.languageId, doc.version, doc.getText());\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"export function getPathBaseName(path: string): string {\n",
"\tconst pathAfterSlashSplit = path.split('/').pop();\n",
"\tconst pathAfterBackslashSplit = pathAfterSlashSplit ? pathAfterSlashSplit.split('\\\\').pop() : '';\n",
"\treturn pathAfterBackslashSplit ?? '';\n",
"}"
],
"file_path": "extensions/emmet/src/util.ts",
"type": "add",
"edit_start_line_idx": 649
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { ISharedProcessService } from 'vs/platform/ipc/electron-browser/sharedProcessService';
import { Action2, registerAction2 } from 'vs/platform/actions/common/actions';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { CATEGORIES } from 'vs/workbench/common/actions';
class ToggleSharedProcessAction extends Action2 {
constructor() {
super({
id: 'workbench.action.toggleSharedProcess',
title: { value: nls.localize('toggleSharedProcess', "Toggle Shared Process"), original: 'Toggle Shared Process' },
category: CATEGORIES.Developer,
f1: true
});
}
async run(accessor: ServicesAccessor): Promise<void> {
return accessor.get(ISharedProcessService).toggleSharedProcessWindow();
}
}
registerAction2(ToggleSharedProcessAction);
| src/vs/workbench/electron-browser/actions/developerActions.ts | 0 | https://github.com/microsoft/vscode/commit/0fc17285e1f612f63deddaaa206f08162f190ec2 | [
0.00017566733004059643,
0.00017403357196599245,
0.000172490777913481,
0.00017394256428815424,
0.0000012984171462449012
] |
{
"id": 2,
"code_window": [
"}\n",
"\n",
"export function toLSTextDocument(doc: vscode.TextDocument): LSTextDocument {\n",
"\treturn LSTextDocument.create(doc.uri.toString(), doc.languageId, doc.version, doc.getText());\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"export function getPathBaseName(path: string): string {\n",
"\tconst pathAfterSlashSplit = path.split('/').pop();\n",
"\tconst pathAfterBackslashSplit = pathAfterSlashSplit ? pathAfterSlashSplit.split('\\\\').pop() : '';\n",
"\treturn pathAfterBackslashSplit ?? '';\n",
"}"
],
"file_path": "extensions/emmet/src/util.ts",
"type": "add",
"edit_start_line_idx": 649
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as path from 'vs/base/common/path';
import { originalFSPath, joinPath } from 'vs/base/common/resources';
import { Barrier, timeout } from 'vs/base/common/async';
import { dispose, toDisposable, DisposableStore, Disposable } from 'vs/base/common/lifecycle';
import { TernarySearchTree } from 'vs/base/common/map';
import { URI } from 'vs/base/common/uri';
import { ILogService } from 'vs/platform/log/common/log';
import { ExtHostExtensionServiceShape, IInitData, MainContext, MainThreadExtensionServiceShape, MainThreadTelemetryShape, MainThreadWorkspaceShape, IResolveAuthorityResult } from 'vs/workbench/api/common/extHost.protocol';
import { ExtHostConfiguration, IExtHostConfiguration } from 'vs/workbench/api/common/extHostConfiguration';
import { ActivatedExtension, EmptyExtension, ExtensionActivationReason, ExtensionActivationTimes, ExtensionActivationTimesBuilder, ExtensionsActivator, IExtensionAPI, IExtensionModule, HostExtension, ExtensionActivationTimesFragment } from 'vs/workbench/api/common/extHostExtensionActivator';
import { ExtHostStorage, IExtHostStorage } from 'vs/workbench/api/common/extHostStorage';
import { ExtHostWorkspace, IExtHostWorkspace } from 'vs/workbench/api/common/extHostWorkspace';
import { ExtensionActivationError, checkProposedApiEnabled, ActivationKind } from 'vs/workbench/services/extensions/common/extensions';
import { ExtensionDescriptionRegistry } from 'vs/workbench/services/extensions/common/extensionDescriptionRegistry';
import * as errors from 'vs/base/common/errors';
import type * as vscode from 'vscode';
import { ExtensionIdentifier, IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { Schemas } from 'vs/base/common/network';
import { VSBuffer } from 'vs/base/common/buffer';
import { ExtensionMemento } from 'vs/workbench/api/common/extHostMemento';
import { RemoteAuthorityResolverError, ExtensionMode, ExtensionRuntime } from 'vs/workbench/api/common/extHostTypes';
import { ResolvedAuthority, ResolvedOptions, RemoteAuthorityResolverErrorCode, IRemoteConnectionData } from 'vs/platform/remote/common/remoteAuthorityResolver';
import { IInstantiationService, createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IExtHostInitDataService } from 'vs/workbench/api/common/extHostInitDataService';
import { IExtensionStoragePaths } from 'vs/workbench/api/common/extHostStoragePaths';
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { IExtHostTunnelService } from 'vs/workbench/api/common/extHostTunnelService';
import { IExtHostTerminalService } from 'vs/workbench/api/common/extHostTerminalService';
import { Emitter, Event } from 'vs/base/common/event';
import { IExtensionActivationHost, checkActivateWorkspaceContainsExtension } from 'vs/workbench/api/common/shared/workspaceContains';
interface ITestRunner {
/** Old test runner API, as exported from `vscode/lib/testrunner` */
run(testsRoot: string, clb: (error: Error, failures?: number) => void): void;
}
interface INewTestRunner {
/** New test runner API, as explained in the extension test doc */
run(): Promise<void>;
}
export const IHostUtils = createDecorator<IHostUtils>('IHostUtils');
export interface IHostUtils {
readonly _serviceBrand: undefined;
exit(code?: number): void;
exists(path: string): Promise<boolean>;
realpath(path: string): Promise<string>;
}
type TelemetryActivationEventFragment = {
id: { classification: 'PublicNonPersonalData', purpose: 'FeatureInsight' };
name: { classification: 'PublicNonPersonalData', purpose: 'FeatureInsight' };
extensionVersion: { classification: 'PublicNonPersonalData', purpose: 'FeatureInsight' };
publisherDisplayName: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
activationEvents: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
isBuiltin: { classification: 'SystemMetaData', purpose: 'FeatureInsight', isMeasurement: true };
reason: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
reasonId: { classification: 'PublicNonPersonalData', purpose: 'FeatureInsight' };
};
export abstract class AbstractExtHostExtensionService extends Disposable implements ExtHostExtensionServiceShape {
readonly _serviceBrand: undefined;
abstract readonly extensionRuntime: ExtensionRuntime;
private readonly _onDidChangeRemoteConnectionData = this._register(new Emitter<void>());
public readonly onDidChangeRemoteConnectionData = this._onDidChangeRemoteConnectionData.event;
protected readonly _hostUtils: IHostUtils;
protected readonly _initData: IInitData;
protected readonly _extHostContext: IExtHostRpcService;
protected readonly _instaService: IInstantiationService;
protected readonly _extHostWorkspace: ExtHostWorkspace;
protected readonly _extHostConfiguration: ExtHostConfiguration;
protected readonly _logService: ILogService;
protected readonly _extHostTunnelService: IExtHostTunnelService;
protected readonly _extHostTerminalService: IExtHostTerminalService;
protected readonly _mainThreadWorkspaceProxy: MainThreadWorkspaceShape;
protected readonly _mainThreadTelemetryProxy: MainThreadTelemetryShape;
protected readonly _mainThreadExtensionsProxy: MainThreadExtensionServiceShape;
private readonly _almostReadyToRunExtensions: Barrier;
private readonly _readyToStartExtensionHost: Barrier;
private readonly _readyToRunExtensions: Barrier;
protected readonly _registry: ExtensionDescriptionRegistry;
private readonly _storage: ExtHostStorage;
private readonly _storagePath: IExtensionStoragePaths;
private readonly _activator: ExtensionsActivator;
private _extensionPathIndex: Promise<TernarySearchTree<string, IExtensionDescription>> | null;
private readonly _resolvers: { [authorityPrefix: string]: vscode.RemoteAuthorityResolver; };
private _started: boolean;
private _remoteConnectionData: IRemoteConnectionData | null;
private readonly _disposables: DisposableStore;
constructor(
@IInstantiationService instaService: IInstantiationService,
@IHostUtils hostUtils: IHostUtils,
@IExtHostRpcService extHostContext: IExtHostRpcService,
@IExtHostWorkspace extHostWorkspace: IExtHostWorkspace,
@IExtHostConfiguration extHostConfiguration: IExtHostConfiguration,
@ILogService logService: ILogService,
@IExtHostInitDataService initData: IExtHostInitDataService,
@IExtensionStoragePaths storagePath: IExtensionStoragePaths,
@IExtHostTunnelService extHostTunnelService: IExtHostTunnelService,
@IExtHostTerminalService extHostTerminalService: IExtHostTerminalService
) {
super();
this._hostUtils = hostUtils;
this._extHostContext = extHostContext;
this._initData = initData;
this._extHostWorkspace = extHostWorkspace;
this._extHostConfiguration = extHostConfiguration;
this._logService = logService;
this._extHostTunnelService = extHostTunnelService;
this._extHostTerminalService = extHostTerminalService;
this._disposables = new DisposableStore();
this._mainThreadWorkspaceProxy = this._extHostContext.getProxy(MainContext.MainThreadWorkspace);
this._mainThreadTelemetryProxy = this._extHostContext.getProxy(MainContext.MainThreadTelemetry);
this._mainThreadExtensionsProxy = this._extHostContext.getProxy(MainContext.MainThreadExtensionService);
this._almostReadyToRunExtensions = new Barrier();
this._readyToStartExtensionHost = new Barrier();
this._readyToRunExtensions = new Barrier();
this._registry = new ExtensionDescriptionRegistry(this._initData.extensions);
this._storage = new ExtHostStorage(this._extHostContext);
this._storagePath = storagePath;
this._instaService = instaService.createChild(new ServiceCollection(
[IExtHostStorage, this._storage]
));
const hostExtensions = new Set<string>();
this._initData.hostExtensions.forEach((extensionId) => hostExtensions.add(ExtensionIdentifier.toKey(extensionId)));
this._activator = new ExtensionsActivator(
this._registry,
this._initData.resolvedExtensions,
this._initData.hostExtensions,
{
onExtensionActivationError: (extensionId: ExtensionIdentifier, error: ExtensionActivationError): void => {
this._mainThreadExtensionsProxy.$onExtensionActivationError(extensionId, error);
},
actualActivateExtension: async (extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<ActivatedExtension> => {
if (hostExtensions.has(ExtensionIdentifier.toKey(extensionId))) {
await this._mainThreadExtensionsProxy.$activateExtension(extensionId, reason);
return new HostExtension();
}
const extensionDescription = this._registry.getExtensionDescription(extensionId)!;
return this._activateExtension(extensionDescription, reason);
}
},
this._logService
);
this._extensionPathIndex = null;
this._resolvers = Object.create(null);
this._started = false;
this._remoteConnectionData = this._initData.remote.connectionData;
}
public getRemoteConnectionData(): IRemoteConnectionData | null {
return this._remoteConnectionData;
}
public async initialize(): Promise<void> {
try {
await this._beforeAlmostReadyToRunExtensions();
this._almostReadyToRunExtensions.open();
await this._extHostWorkspace.waitForInitializeCall();
this._readyToStartExtensionHost.open();
if (this._initData.autoStart) {
this._startExtensionHost();
}
} catch (err) {
errors.onUnexpectedError(err);
}
}
public async deactivateAll(): Promise<void> {
let allPromises: Promise<void>[] = [];
try {
const allExtensions = this._registry.getAllExtensionDescriptions();
const allExtensionsIds = allExtensions.map(ext => ext.identifier);
const activatedExtensions = allExtensionsIds.filter(id => this.isActivated(id));
allPromises = activatedExtensions.map((extensionId) => {
return this._deactivate(extensionId);
});
} catch (err) {
// TODO: write to log once we have one
}
await Promise.all(allPromises);
}
public isActivated(extensionId: ExtensionIdentifier): boolean {
if (this._readyToRunExtensions.isOpen()) {
return this._activator.isActivated(extensionId);
}
return false;
}
private _activateByEvent(activationEvent: string, startup: boolean): Promise<void> {
return this._activator.activateByEvent(activationEvent, startup);
}
private _activateById(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<void> {
return this._activator.activateById(extensionId, reason);
}
public activateByIdWithErrors(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<void> {
return this._activateById(extensionId, reason).then(() => {
const extension = this._activator.getActivatedExtension(extensionId);
if (extension.activationFailed) {
// activation failed => bubble up the error as the promise result
return Promise.reject(extension.activationFailedError);
}
return undefined;
});
}
public getExtensionRegistry(): Promise<ExtensionDescriptionRegistry> {
return this._readyToRunExtensions.wait().then(_ => this._registry);
}
public getExtensionExports(extensionId: ExtensionIdentifier): IExtensionAPI | null | undefined {
if (this._readyToRunExtensions.isOpen()) {
return this._activator.getActivatedExtension(extensionId).exports;
} else {
return null;
}
}
// create trie to enable fast 'filename -> extension id' look up
public getExtensionPathIndex(): Promise<TernarySearchTree<string, IExtensionDescription>> {
if (!this._extensionPathIndex) {
const tree = TernarySearchTree.forPaths<IExtensionDescription>();
const extensions = this._registry.getAllExtensionDescriptions().map(ext => {
if (!this._getEntryPoint(ext)) {
return undefined;
}
return this._hostUtils.realpath(ext.extensionLocation.fsPath).then(value => tree.set(URI.file(value).fsPath, ext));
});
this._extensionPathIndex = Promise.all(extensions).then(() => tree);
}
return this._extensionPathIndex;
}
private _deactivate(extensionId: ExtensionIdentifier): Promise<void> {
let result = Promise.resolve(undefined);
if (!this._readyToRunExtensions.isOpen()) {
return result;
}
if (!this._activator.isActivated(extensionId)) {
return result;
}
const extension = this._activator.getActivatedExtension(extensionId);
if (!extension) {
return result;
}
// call deactivate if available
try {
if (typeof extension.module.deactivate === 'function') {
result = Promise.resolve(extension.module.deactivate()).then(undefined, (err) => {
// TODO: Do something with err if this is not the shutdown case
return Promise.resolve(undefined);
});
}
} catch (err) {
// TODO: Do something with err if this is not the shutdown case
}
// clean up subscriptions
try {
dispose(extension.subscriptions);
} catch (err) {
// TODO: Do something with err if this is not the shutdown case
}
return result;
}
// --- impl
private async _activateExtension(extensionDescription: IExtensionDescription, reason: ExtensionActivationReason): Promise<ActivatedExtension> {
if (!this._initData.remote.isRemote) {
// local extension host process
await this._mainThreadExtensionsProxy.$onWillActivateExtension(extensionDescription.identifier);
} else {
// remote extension host process
// do not wait for renderer confirmation
this._mainThreadExtensionsProxy.$onWillActivateExtension(extensionDescription.identifier);
}
return this._doActivateExtension(extensionDescription, reason).then((activatedExtension) => {
const activationTimes = activatedExtension.activationTimes;
this._mainThreadExtensionsProxy.$onDidActivateExtension(extensionDescription.identifier, activationTimes.codeLoadingTime, activationTimes.activateCallTime, activationTimes.activateResolvedTime, reason);
this._logExtensionActivationTimes(extensionDescription, reason, 'success', activationTimes);
return activatedExtension;
}, (err) => {
this._logExtensionActivationTimes(extensionDescription, reason, 'failure');
throw err;
});
}
private _logExtensionActivationTimes(extensionDescription: IExtensionDescription, reason: ExtensionActivationReason, outcome: string, activationTimes?: ExtensionActivationTimes) {
const event = getTelemetryActivationEvent(extensionDescription, reason);
type ExtensionActivationTimesClassification = {
outcome: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
} & TelemetryActivationEventFragment & ExtensionActivationTimesFragment;
type ExtensionActivationTimesEvent = {
outcome: string
} & ActivationTimesEvent & TelemetryActivationEvent;
type ActivationTimesEvent = {
startup?: boolean;
codeLoadingTime?: number;
activateCallTime?: number;
activateResolvedTime?: number;
};
this._mainThreadTelemetryProxy.$publicLog2<ExtensionActivationTimesEvent, ExtensionActivationTimesClassification>('extensionActivationTimes', {
...event,
...(activationTimes || {}),
outcome
});
}
private _doActivateExtension(extensionDescription: IExtensionDescription, reason: ExtensionActivationReason): Promise<ActivatedExtension> {
const event = getTelemetryActivationEvent(extensionDescription, reason);
type ActivatePluginClassification = {} & TelemetryActivationEventFragment;
this._mainThreadTelemetryProxy.$publicLog2<TelemetryActivationEvent, ActivatePluginClassification>('activatePlugin', event);
const entryPoint = this._getEntryPoint(extensionDescription);
if (!entryPoint) {
// Treat the extension as being empty => NOT AN ERROR CASE
return Promise.resolve(new EmptyExtension(ExtensionActivationTimes.NONE));
}
this._logService.info(`ExtensionService#_doActivateExtension ${extensionDescription.identifier.value} ${JSON.stringify(reason)}`);
this._logService.flush();
const activationTimesBuilder = new ExtensionActivationTimesBuilder(reason.startup);
return Promise.all([
this._loadCommonJSModule<IExtensionModule>(joinPath(extensionDescription.extensionLocation, entryPoint), activationTimesBuilder),
this._loadExtensionContext(extensionDescription)
]).then(values => {
return AbstractExtHostExtensionService._callActivate(this._logService, extensionDescription.identifier, values[0], values[1], activationTimesBuilder);
});
}
private _loadExtensionContext(extensionDescription: IExtensionDescription): Promise<vscode.ExtensionContext> {
const globalState = new ExtensionMemento(extensionDescription.identifier.value, true, this._storage);
const workspaceState = new ExtensionMemento(extensionDescription.identifier.value, false, this._storage);
const extensionMode = extensionDescription.isUnderDevelopment
? (this._initData.environment.extensionTestsLocationURI ? ExtensionMode.Test : ExtensionMode.Development)
: ExtensionMode.Production;
this._logService.trace(`ExtensionService#loadExtensionContext ${extensionDescription.identifier.value}`);
return Promise.all([
globalState.whenReady,
workspaceState.whenReady,
this._storagePath.whenReady
]).then(() => {
const that = this;
return Object.freeze<vscode.ExtensionContext>({
globalState,
workspaceState,
subscriptions: [],
get extensionUri() { return extensionDescription.extensionLocation; },
get extensionPath() { return extensionDescription.extensionLocation.fsPath; },
asAbsolutePath(relativePath: string) { return path.join(extensionDescription.extensionLocation.fsPath, relativePath); },
get storagePath() { return that._storagePath.workspaceValue(extensionDescription)?.fsPath; },
get globalStoragePath() { return that._storagePath.globalValue(extensionDescription).fsPath; },
get logPath() { return path.join(that._initData.logsLocation.fsPath, extensionDescription.identifier.value); },
get logUri() { return URI.joinPath(that._initData.logsLocation, extensionDescription.identifier.value); },
get storageUri() { return that._storagePath.workspaceValue(extensionDescription); },
get globalStorageUri() { return that._storagePath.globalValue(extensionDescription); },
get extensionMode() { return extensionMode; },
get extensionRuntime() {
checkProposedApiEnabled(extensionDescription);
return that.extensionRuntime;
},
get environmentVariableCollection() { return that._extHostTerminalService.getEnvironmentVariableCollection(extensionDescription); }
});
});
}
private static _callActivate(logService: ILogService, extensionId: ExtensionIdentifier, extensionModule: IExtensionModule, context: vscode.ExtensionContext, activationTimesBuilder: ExtensionActivationTimesBuilder): Promise<ActivatedExtension> {
// Make sure the extension's surface is not undefined
extensionModule = extensionModule || {
activate: undefined,
deactivate: undefined
};
return this._callActivateOptional(logService, extensionId, extensionModule, context, activationTimesBuilder).then((extensionExports) => {
return new ActivatedExtension(false, null, activationTimesBuilder.build(), extensionModule, extensionExports, context.subscriptions);
});
}
private static _callActivateOptional(logService: ILogService, extensionId: ExtensionIdentifier, extensionModule: IExtensionModule, context: vscode.ExtensionContext, activationTimesBuilder: ExtensionActivationTimesBuilder): Promise<IExtensionAPI> {
if (typeof extensionModule.activate === 'function') {
try {
activationTimesBuilder.activateCallStart();
logService.trace(`ExtensionService#_callActivateOptional ${extensionId.value}`);
const scope = typeof global === 'object' ? global : self; // `global` is nodejs while `self` is for workers
const activateResult: Promise<IExtensionAPI> = extensionModule.activate.apply(scope, [context]);
activationTimesBuilder.activateCallStop();
activationTimesBuilder.activateResolveStart();
return Promise.resolve(activateResult).then((value) => {
activationTimesBuilder.activateResolveStop();
return value;
});
} catch (err) {
return Promise.reject(err);
}
} else {
// No activate found => the module is the extension's exports
return Promise.resolve<IExtensionAPI>(extensionModule);
}
}
// -- eager activation
private _activateOneStartupFinished(desc: IExtensionDescription, activationEvent: string): void {
this._activateById(desc.identifier, {
startup: false,
extensionId: desc.identifier,
activationEvent: activationEvent
}).then(undefined, (err) => {
this._logService.error(err);
});
}
private _activateAllStartupFinished(): void {
for (const desc of this._registry.getAllExtensionDescriptions()) {
if (desc.activationEvents) {
for (const activationEvent of desc.activationEvents) {
if (activationEvent === 'onStartupFinished') {
this._activateOneStartupFinished(desc, activationEvent);
}
}
}
}
}
// Handle "eager" activation extensions
private _handleEagerExtensions(): Promise<void> {
const starActivation = this._activateByEvent('*', true).then(undefined, (err) => {
this._logService.error(err);
});
this._disposables.add(this._extHostWorkspace.onDidChangeWorkspace((e) => this._handleWorkspaceContainsEagerExtensions(e.added)));
const folders = this._extHostWorkspace.workspace ? this._extHostWorkspace.workspace.folders : [];
const workspaceContainsActivation = this._handleWorkspaceContainsEagerExtensions(folders);
const eagerExtensionsActivation = Promise.all([starActivation, workspaceContainsActivation]).then(() => { });
Promise.race([eagerExtensionsActivation, timeout(10000)]).then(() => {
this._activateAllStartupFinished();
});
return eagerExtensionsActivation;
}
private _handleWorkspaceContainsEagerExtensions(folders: ReadonlyArray<vscode.WorkspaceFolder>): Promise<void> {
if (folders.length === 0) {
return Promise.resolve(undefined);
}
return Promise.all(
this._registry.getAllExtensionDescriptions().map((desc) => {
return this._handleWorkspaceContainsEagerExtension(folders, desc);
})
).then(() => { });
}
private async _handleWorkspaceContainsEagerExtension(folders: ReadonlyArray<vscode.WorkspaceFolder>, desc: IExtensionDescription): Promise<void> {
if (this.isActivated(desc.identifier)) {
return;
}
const localWithRemote = !this._initData.remote.isRemote && !!this._initData.remote.authority;
const host: IExtensionActivationHost = {
folders: folders.map(folder => folder.uri),
forceUsingSearch: localWithRemote,
exists: (uri) => this._hostUtils.exists(uri.fsPath),
checkExists: (folders, includes, token) => this._mainThreadWorkspaceProxy.$checkExists(folders, includes, token)
};
const result = await checkActivateWorkspaceContainsExtension(host, desc);
if (!result) {
return;
}
return (
this._activateById(desc.identifier, { startup: true, extensionId: desc.identifier, activationEvent: result.activationEvent })
.then(undefined, err => this._logService.error(err))
);
}
private _handleExtensionTests(): Promise<void> {
return this._doHandleExtensionTests().then(undefined, error => {
console.error(error); // ensure any error message makes it onto the console
return Promise.reject(error);
});
}
private async _doHandleExtensionTests(): Promise<void> {
const { extensionDevelopmentLocationURI, extensionTestsLocationURI } = this._initData.environment;
if (!(extensionDevelopmentLocationURI && extensionTestsLocationURI && extensionTestsLocationURI.scheme === Schemas.file)) {
return Promise.resolve(undefined);
}
const extensionTestsPath = originalFSPath(extensionTestsLocationURI);
// Require the test runner via node require from the provided path
let testRunner: ITestRunner | INewTestRunner | undefined;
let requireError: Error | undefined;
try {
testRunner = await this._loadCommonJSModule(URI.file(extensionTestsPath), new ExtensionActivationTimesBuilder(false));
} catch (error) {
requireError = error;
}
// Execute the runner if it follows the old `run` spec
if (testRunner && typeof testRunner.run === 'function') {
return new Promise<void>((c, e) => {
const oldTestRunnerCallback = (error: Error, failures: number | undefined) => {
if (error) {
e(error.toString());
} else {
c(undefined);
}
// after tests have run, we shutdown the host
this._testRunnerExit(error || (typeof failures === 'number' && failures > 0) ? 1 /* ERROR */ : 0 /* OK */);
};
const runResult = testRunner!.run(extensionTestsPath, oldTestRunnerCallback);
// Using the new API `run(): Promise<void>`
if (runResult && runResult.then) {
runResult
.then(() => {
c();
this._testRunnerExit(0);
})
.catch((err: Error) => {
e(err.toString());
this._testRunnerExit(1);
});
}
});
}
// Otherwise make sure to shutdown anyway even in case of an error
else {
this._testRunnerExit(1 /* ERROR */);
}
return Promise.reject(new Error(requireError ? requireError.toString() : nls.localize('extensionTestError', "Path {0} does not point to a valid extension test runner.", extensionTestsPath)));
}
private _testRunnerExit(code: number): void {
// wait at most 5000ms for the renderer to confirm our exit request and for the renderer socket to drain
// (this is to ensure all outstanding messages reach the renderer)
const exitPromise = this._mainThreadExtensionsProxy.$onExtensionHostExit(code);
const drainPromise = this._extHostContext.drain();
Promise.race([Promise.all([exitPromise, drainPromise]), timeout(5000)]).then(() => {
this._hostUtils.exit(code);
});
}
private _startExtensionHost(): Promise<void> {
if (this._started) {
throw new Error(`Extension host is already started!`);
}
this._started = true;
return this._readyToStartExtensionHost.wait()
.then(() => this._readyToRunExtensions.open())
.then(() => this._handleEagerExtensions())
.then(() => this._handleExtensionTests())
.then(() => {
this._logService.info(`eager extensions activated`);
});
}
// -- called by extensions
public registerRemoteAuthorityResolver(authorityPrefix: string, resolver: vscode.RemoteAuthorityResolver): vscode.Disposable {
this._resolvers[authorityPrefix] = resolver;
return toDisposable(() => {
delete this._resolvers[authorityPrefix];
});
}
// -- called by main thread
public async $resolveAuthority(remoteAuthority: string, resolveAttempt: number): Promise<IResolveAuthorityResult> {
const authorityPlusIndex = remoteAuthority.indexOf('+');
if (authorityPlusIndex === -1) {
throw new Error(`Not an authority that can be resolved!`);
}
const authorityPrefix = remoteAuthority.substr(0, authorityPlusIndex);
await this._almostReadyToRunExtensions.wait();
await this._activateByEvent(`onResolveRemoteAuthority:${authorityPrefix}`, false);
const resolver = this._resolvers[authorityPrefix];
if (!resolver) {
return {
type: 'error',
error: {
code: RemoteAuthorityResolverErrorCode.NoResolverFound,
message: `No remote extension installed to resolve ${authorityPrefix}.`,
detail: undefined
}
};
}
try {
const result = await resolver.resolve(remoteAuthority, { resolveAttempt });
this._disposables.add(await this._extHostTunnelService.setTunnelExtensionFunctions(resolver));
// Split merged API result into separate authority/options
const authority: ResolvedAuthority = {
authority: remoteAuthority,
host: result.host,
port: result.port
};
const options: ResolvedOptions = {
extensionHostEnv: result.extensionHostEnv
};
return {
type: 'ok',
value: {
authority,
options,
tunnelInformation: { environmentTunnels: result.environmentTunnels }
}
};
} catch (err) {
if (err instanceof RemoteAuthorityResolverError) {
return {
type: 'error',
error: {
code: err._code,
message: err._message,
detail: err._detail
}
};
}
throw err;
}
}
public $startExtensionHost(enabledExtensionIds: ExtensionIdentifier[]): Promise<void> {
this._registry.keepOnly(enabledExtensionIds);
return this._startExtensionHost();
}
public $activateByEvent(activationEvent: string, activationKind: ActivationKind): Promise<void> {
if (activationKind === ActivationKind.Immediate) {
return this._activateByEvent(activationEvent, false);
}
return (
this._readyToRunExtensions.wait()
.then(_ => this._activateByEvent(activationEvent, false))
);
}
public async $activate(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<boolean> {
await this._readyToRunExtensions.wait();
if (!this._registry.getExtensionDescription(extensionId)) {
// unknown extension => ignore
return false;
}
await this._activateById(extensionId, reason);
return true;
}
public async $deltaExtensions(toAdd: IExtensionDescription[], toRemove: ExtensionIdentifier[]): Promise<void> {
toAdd.forEach((extension) => (<any>extension).extensionLocation = URI.revive(extension.extensionLocation));
const trie = await this.getExtensionPathIndex();
await Promise.all(toRemove.map(async (extensionId) => {
const extensionDescription = this._registry.getExtensionDescription(extensionId);
if (!extensionDescription) {
return;
}
const realpathValue = await this._hostUtils.realpath(extensionDescription.extensionLocation.fsPath);
trie.delete(URI.file(realpathValue).fsPath);
}));
await Promise.all(toAdd.map(async (extensionDescription) => {
const realpathValue = await this._hostUtils.realpath(extensionDescription.extensionLocation.fsPath);
trie.set(URI.file(realpathValue).fsPath, extensionDescription);
}));
this._registry.deltaExtensions(toAdd, toRemove);
return Promise.resolve(undefined);
}
public async $test_latency(n: number): Promise<number> {
return n;
}
public async $test_up(b: VSBuffer): Promise<number> {
return b.byteLength;
}
public async $test_down(size: number): Promise<VSBuffer> {
let buff = VSBuffer.alloc(size);
let value = Math.random() % 256;
for (let i = 0; i < size; i++) {
buff.writeUInt8(value, i);
}
return buff;
}
public async $updateRemoteConnectionData(connectionData: IRemoteConnectionData): Promise<void> {
this._remoteConnectionData = connectionData;
this._onDidChangeRemoteConnectionData.fire();
}
protected abstract _beforeAlmostReadyToRunExtensions(): Promise<void>;
protected abstract _getEntryPoint(extensionDescription: IExtensionDescription): string | undefined;
protected abstract _loadCommonJSModule<T>(module: URI, activationTimesBuilder: ExtensionActivationTimesBuilder): Promise<T>;
public abstract $setRemoteEnvironment(env: { [key: string]: string | null }): Promise<void>;
}
type TelemetryActivationEvent = {
id: string;
name: string;
extensionVersion: string;
publisherDisplayName: string;
activationEvents: string | null;
isBuiltin: boolean;
reason: string;
reasonId: string;
};
function getTelemetryActivationEvent(extensionDescription: IExtensionDescription, reason: ExtensionActivationReason): TelemetryActivationEvent {
const event = {
id: extensionDescription.identifier.value,
name: extensionDescription.name,
extensionVersion: extensionDescription.version,
publisherDisplayName: extensionDescription.publisher,
activationEvents: extensionDescription.activationEvents ? extensionDescription.activationEvents.join(',') : null,
isBuiltin: extensionDescription.isBuiltin,
reason: reason.activationEvent,
reasonId: reason.extensionId.value,
};
return event;
}
export const IExtHostExtensionService = createDecorator<IExtHostExtensionService>('IExtHostExtensionService');
export interface IExtHostExtensionService extends AbstractExtHostExtensionService {
readonly _serviceBrand: undefined;
initialize(): Promise<void>;
isActivated(extensionId: ExtensionIdentifier): boolean;
activateByIdWithErrors(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<void>;
deactivateAll(): Promise<void>;
getExtensionExports(extensionId: ExtensionIdentifier): IExtensionAPI | null | undefined;
getExtensionRegistry(): Promise<ExtensionDescriptionRegistry>;
getExtensionPathIndex(): Promise<TernarySearchTree<string, IExtensionDescription>>;
registerRemoteAuthorityResolver(authorityPrefix: string, resolver: vscode.RemoteAuthorityResolver): vscode.Disposable;
onDidChangeRemoteConnectionData: Event<void>;
getRemoteConnectionData(): IRemoteConnectionData | null;
}
| src/vs/workbench/api/common/extHostExtensionService.ts | 0 | https://github.com/microsoft/vscode/commit/0fc17285e1f612f63deddaaa206f08162f190ec2 | [
0.00018675743194762617,
0.00017174918320961297,
0.00016325815522577614,
0.00017161636787932366,
0.000003281757471995661
] |
{
"id": 0,
"code_window": [
"### Link to the Strapi Studio\n",
"\n",
"> We advise you to use our Studio to build APIs. To do so, you need to create a Strapi account.\n",
"[Go to the Strapi Studio to signup](http://localhost:1338).\n",
"Studio is dedicated to developers to build applications without writing\n",
"any single line of code thanks to its powerful set of tools.\n",
"\n",
"After creating an account on the Strapi Studio, you are able to link your machine to your\n",
"Strapi Studio account to get access to all features offered by the Strapi ecosystem.\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"[Go to the Strapi Studio to signup](http://studio.strapi.io).\n"
],
"file_path": "README.md",
"type": "replace",
"edit_start_line_idx": 26
} | 'use strict';
/**
* Module dependencies
*/
// Node.js core.
const os = require('os');
// Public node modules.
const _ = require('lodash');
// Local dependencies.
const DEFAULT_HOOKS = require('./hooks/defaultHooks');
/**
* Expose new instance of `Configuration`
*/
module.exports = function (strapi) {
return new Configuration();
function Configuration() {
/**
* Strapi default configuration
*
* @api private
*/
this.defaults = function defaultConfig(appPath) {
// If `appPath` not specified, unfortunately, this is a fatal error,
// since reasonable defaults cannot be assumed.
if (!appPath) {
throw new Error('Error: No `appPath` specified!');
}
// Set up config defaults.
return {
// Core (default) hooks.
hooks: _.reduce(DEFAULT_HOOKS, function (memo, hookBundled, hookIdentity) {
memo[hookIdentity] = require('./hooks/' + hookIdentity);
return memo;
}, {}) || {},
// Save `appPath` in implicit defaults.
// `appPath` is passed from above in case `start` was used.
// This is the directory where this Strapi process is being initiated from.
// Usually this means `process.cwd()`.
appPath: appPath,
// Core settings non provided by hooks.
host: process.env.HOST || process.env.HOSTNAME || strapi.config.host || 'localhost',
port: process.env.PORT || strapi.config.port || 1337,
// Make the environment in config match the server one.
environment: strapi.app.env || process.env.NODE_ENV,
// Default reload config.
reload: {
timeout: 1000,
workers: os.cpus().length
},
// Application is not `dry` by default.
dry: false,
// Default paths.
paths: {
tmp: '.tmp',
config: 'config',
static: 'public',
views: 'views',
api: 'api',
controllers: 'controllers',
services: 'services',
policies: 'policies',
models: 'models',
templates: 'templates'
},
// Add the Studio URL.
studio: {
url: 'http://localhost:1338'
},
// Start off needed empty objects and strings.
routes: {},
frontendUrl: ''
};
};
/**
* Load the configuration modules
*
* @api private
*/
this.load = require('./load')(strapi);
// Bind the context of all instance methods.
_.bindAll(this);
}
};
| lib/configuration/index.js | 1 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.00029880559304729104,
0.00018256035400554538,
0.0001642255374463275,
0.000166542042279616,
0.00003786237721215002
] |
{
"id": 0,
"code_window": [
"### Link to the Strapi Studio\n",
"\n",
"> We advise you to use our Studio to build APIs. To do so, you need to create a Strapi account.\n",
"[Go to the Strapi Studio to signup](http://localhost:1338).\n",
"Studio is dedicated to developers to build applications without writing\n",
"any single line of code thanks to its powerful set of tools.\n",
"\n",
"After creating an account on the Strapi Studio, you are able to link your machine to your\n",
"Strapi Studio account to get access to all features offered by the Strapi ecosystem.\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"[Go to the Strapi Studio to signup](http://studio.strapi.io).\n"
],
"file_path": "README.md",
"type": "replace",
"edit_start_line_idx": 26
} | 'use strict';
const path = require('path');
const request = require('supertest');
const strapi = require('../../..');
const Koa = strapi.server;
describe('assets', function () {
describe('when defer: false', function () {
describe('when root = "."', function () {
it('should serve from cwd', function (done) {
const app = new Koa();
app.use(strapi.middlewares.static('.'));
request(app.listen())
.get('/package.json')
.expect(200, done);
});
});
describe('when path is not a file', function () {
it('should 404', function (done) {
const app = new Koa();
app.use(strapi.middlewares.static(path.resolve(__dirname, 'fixtures')));
request(app.listen())
.get('/something')
.expect(404, done);
});
});
describe('when upstream middleware responds', function () {
it('should respond', function (done) {
const app = new Koa();
app.use(strapi.middlewares.static(path.resolve(__dirname, 'fixtures')));
app.use(function * (next) {
yield next;
this.body = 'hey';
});
request(app.listen())
.get('/hello.txt')
.expect(200)
.expect('world', done);
});
});
describe('the path is valid', function () {
it('should serve the file', function (done) {
const app = new Koa();
app.use(strapi.middlewares.static(path.resolve(__dirname, 'fixtures')));
request(app.listen())
.get('/hello.txt')
.expect(200)
.expect('world', done);
});
});
describe('.index', function () {
describe('when present', function () {
it('should alter the index file supported', function (done) {
const app = new Koa();
app.use(strapi.middlewares.static(path.resolve(__dirname, 'fixtures'), {
index: 'index.txt'
}));
request(app.listen())
.get('/')
.expect(200)
.expect('Content-Type', 'text/plain; charset=utf-8')
.expect('text index', done);
});
});
describe('when omitted', function () {
it('should use index.html', function (done) {
const app = new Koa();
app.use(strapi.middlewares.static(path.resolve(__dirname, 'fixtures')));
request(app.listen())
.get('/world/')
.expect(200)
.expect('Content-Type', 'text/html; charset=utf-8')
.expect('html index', done);
});
});
});
describe('when method is not `GET` or `HEAD`', function () {
it('should 404', function (done) {
const app = new Koa();
app.use(strapi.middlewares.static(path.resolve(__dirname, 'fixtures')));
request(app.listen())
.post('/hello.txt')
.expect(404, done);
});
});
});
describe('when defer: true', function () {
describe('when upstream middleware responds', function () {
it('should do nothing', function (done) {
const app = new Koa();
app.use(strapi.middlewares.static(path.resolve(__dirname, 'fixtures'), {
defer: true
}));
app.use(function * (next) {
yield next;
this.body = 'hey';
});
request(app.listen())
.get('/hello.txt')
.expect(200)
.expect('hey', done);
});
});
describe('the path is valid', function () {
it('should serve the file', function (done) {
const app = new Koa();
app.use(strapi.middlewares.static(path.resolve(__dirname, 'fixtures'), {
defer: true
}));
request(app.listen())
.get('/hello.txt')
.expect(200)
.expect('world', done);
});
});
describe('.index', function () {
describe('when present', function () {
it('should alter the index file supported', function (done) {
const app = new Koa();
app.use(strapi.middlewares.static(path.resolve(__dirname, 'fixtures'), {
defer: true,
index: 'index.txt'
}));
request(app.listen())
.get('/')
.expect(200)
.expect('Content-Type', 'text/plain; charset=utf-8')
.expect('text index', done);
});
});
describe('when omitted', function () {
it('should use index.html', function (done) {
const app = new Koa();
app.use(strapi.middlewares.static(path.resolve(__dirname, 'fixtures'), {
defer: true
}));
request(app.listen())
.get('/world/')
.expect(200)
.expect('Content-Type', 'text/html; charset=utf-8')
.expect('html index', done);
});
});
});
describe('when path is not a file', function () {
it('should 404', function (done) {
const app = new Koa();
app.use(strapi.middlewares.static(path.resolve(__dirname, 'fixtures'), {
defer: true
}));
request(app.listen())
.get('/something')
.expect(404, done);
});
});
describe('it should not handle the request', function () {
it('when status=204', function (done) {
const app = new Koa();
app.use(strapi.middlewares.static(path.resolve(__dirname, 'fixtures'), {
defer: true
}));
app.use(function * () {
this.status = 204;
});
request(app.listen())
.get('/something%%%/')
.expect(204, done);
});
it('when body=""', function (done) {
const app = new Koa();
app.use(strapi.middlewares.static(path.resolve(__dirname, 'fixtures'), {
defer: true
}));
app.use(function * () {
this.body = '';
});
request(app.listen())
.get('/something%%%/')
.expect(200, done);
});
});
describe('when method is not `GET` or `HEAD`', function () {
it('should 404', function (done) {
const app = new Koa();
app.use(strapi.middlewares.static(path.resolve(__dirname, 'fixtures'), {
defer: true
}));
request(app.listen())
.post('/hello.txt')
.expect(404, done);
});
});
});
});
| test/middlewares/static/index.js | 0 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.0001721656008157879,
0.0001667816541157663,
0.00016286912432406098,
0.0001664277515374124,
0.000002381125341344159
] |
{
"id": 0,
"code_window": [
"### Link to the Strapi Studio\n",
"\n",
"> We advise you to use our Studio to build APIs. To do so, you need to create a Strapi account.\n",
"[Go to the Strapi Studio to signup](http://localhost:1338).\n",
"Studio is dedicated to developers to build applications without writing\n",
"any single line of code thanks to its powerful set of tools.\n",
"\n",
"After creating an account on the Strapi Studio, you are able to link your machine to your\n",
"Strapi Studio account to get access to all features offered by the Strapi ecosystem.\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"[Go to the Strapi Studio to signup](http://studio.strapi.io).\n"
],
"file_path": "README.md",
"type": "replace",
"edit_start_line_idx": 26
} | 'use strict';
const assert = require('assert');
const request = require('../helpers/context').request;
describe('req.charset', function () {
describe('with no content-type present', function () {
it('should return ""', function () {
const req = request();
assert(req.charset === '');
});
});
describe('with charset present', function () {
it('should return ""', function () {
const req = request();
req.header['content-type'] = 'text/plain';
assert(req.charset === '');
});
});
describe('with a charset', function () {
it('should return the charset', function () {
const req = request();
req.header['content-type'] = 'text/plain; charset=utf-8';
req.charset.should.equal('utf-8');
});
});
});
| test/request/charset.js | 0 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.00019852141849696636,
0.00017511859186924994,
0.0001655398664297536,
0.0001682065485510975,
0.00001356893790216418
] |
{
"id": 0,
"code_window": [
"### Link to the Strapi Studio\n",
"\n",
"> We advise you to use our Studio to build APIs. To do so, you need to create a Strapi account.\n",
"[Go to the Strapi Studio to signup](http://localhost:1338).\n",
"Studio is dedicated to developers to build applications without writing\n",
"any single line of code thanks to its powerful set of tools.\n",
"\n",
"After creating an account on the Strapi Studio, you are able to link your machine to your\n",
"Strapi Studio account to get access to all features offered by the Strapi ecosystem.\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"[Go to the Strapi Studio to signup](http://studio.strapi.io).\n"
],
"file_path": "README.md",
"type": "replace",
"edit_start_line_idx": 26
} | text index | test/middlewares/send/fixtures/index.txt | 0 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.00016459080507047474,
0.00016459080507047474,
0.00016459080507047474,
0.00016459080507047474,
0
] |
{
"id": 1,
"code_window": [
"The Strapi Studio allows you to easily build and manage your application environment\n",
"thanks to a powerful User Interface.\n",
"\n",
"Log into the Strapi Studio with your user account ([http://localhost:1338](http://localhost:1338))\n",
"and follow the instructions to start the experience.\n",
"\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"Log into the Strapi Studio with your user account ([http://studio.strapi.io](http://studio.strapi.io))\n"
],
"file_path": "README.md",
"type": "replace",
"edit_start_line_idx": 93
} | # Strapi [](https://travis-ci.org/wistityhq/strapi) [](http://slack.strapi.io)
[Website](http://strapi.io/) - [Getting Started](#user-content-getting-started-in-a-minute) - [Documentation](http://strapi.io/documentation/introduction) - [Support](http://strapi.io/support)
Strapi is an open-source Node.js rich framework for building applications and services.
Strapi enables developers to focus on writing reusable application logic instead of spending time
building infrastructure. It is designed for building practical, production-ready Node.js applications
in a matter of hours instead of weeks.
The framework sits on top of [Koa](http://koajs.com/). Its ensemble of small modules work
together to provide simplicity, maintainability, and structural conventions to Node.js applications.
## Getting started in a minute
### Installation
Install the latest stable release with the npm command-line tool:
```bash
$ npm install strapi -g
```
### Link to the Strapi Studio
> We advise you to use our Studio to build APIs. To do so, you need to create a Strapi account.
[Go to the Strapi Studio to signup](http://localhost:1338).
Studio is dedicated to developers to build applications without writing
any single line of code thanks to its powerful set of tools.
After creating an account on the Strapi Studio, you are able to link your machine to your
Strapi Studio account to get access to all features offered by the Strapi ecosystem.
Use your Strapi account credentials.
```bash
$ strapi login
```
### Create your first project
You now are able to use the Strapi CLI. Simply create your first application and start the server:
```bash
$ strapi new <appName>
```
Note that you can generate a dry application using the `dry` option:
```bash
$ strapi new <appName> --dry
```
This will generate a Strapi application without:
- the built-in `user`, `email` and `upload` APIs,
- the `grant` hook,
- the open-source admin panel,
- the Waterline ORM (`waterline` and `blueprints` hooks disabled),
- the Strapi Studio connection (`studio` hook disabled).
This feature allows you to only use Strapi for your HTTP server structure if you want to.
### Start your application
```bash
$ cd <appName>
$ strapi start
```
The default home page is accessible at [http://localhost:1337/](http://localhost:1337/).
### Create your first API
The Strapi ecosystem offers you two possibilities to create a complete RESTful API.
#### Via the CLI
```bash
$ strapi generate api <apiName>
```
For example, you can create a `car` API with a name (`name`), year (`year`) and
the license plate (`license`) with:
```bash
$ strapi generate api car name:string year:integer license:string
```
#### Via the Strapi Studio
The Strapi Studio allows you to easily build and manage your application environment
thanks to a powerful User Interface.
Log into the Strapi Studio with your user account ([http://localhost:1338](http://localhost:1338))
and follow the instructions to start the experience.

*Simply manage your APIs and relations thanks to the Strapi Studio.*
## Manage your data
Strapi comes with a simple but yet powerful dashboard.

*Create, read, update and delete your data.*

*Manage user settings, login, registration, groups and permissions on the fly.*
## Resources
- [Roadmap](ROADMAP.md)
- [Contributing guide](CONTRIBUTING.md)
- [MIT License](LICENSE.md)
## Links
- [Strapi website](http://strapi.io/)
- [Strapi news on Twitter](https://twitter.com/strapijs)
| README.md | 1 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.9322336912155151,
0.08491147309541702,
0.0001644985459279269,
0.0015559351304545999,
0.2561216354370117
] |
{
"id": 1,
"code_window": [
"The Strapi Studio allows you to easily build and manage your application environment\n",
"thanks to a powerful User Interface.\n",
"\n",
"Log into the Strapi Studio with your user account ([http://localhost:1338](http://localhost:1338))\n",
"and follow the instructions to start the experience.\n",
"\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"Log into the Strapi Studio with your user account ([http://studio.strapi.io](http://studio.strapi.io))\n"
],
"file_path": "README.md",
"type": "replace",
"edit_start_line_idx": 93
} | 'use strict';
const assert = require('assert');
const request = require('supertest');
const Koa = require('../..').server;
describe('app', function () {
it('should handle socket errors', function (done) {
const app = new Koa();
app.use(function * () {
this.socket.emit('error', new Error('boom'));
});
app.on('error', function (err) {
err.message.should.equal('boom');
done();
});
request(app.listen())
.get('/')
.end(function () {});
});
it('should not .writeHead when !socket.writable', function (done) {
const app = new Koa();
app.use(function * () {
this.socket.writable = false;
this.status = 204;
this.res.writeHead =
this.res.end = function () {
throw new Error('response sent');
};
});
setImmediate(done);
request(app.listen())
.get('/')
.end(function () {});
});
it('should set development env when NODE_ENV missing', function () {
const NODE_ENV = process.env.NODE_ENV;
process.env.NODE_ENV = '';
const app = new Koa();
process.env.NODE_ENV = NODE_ENV;
assert.equal(app.env, 'development');
});
});
| test/application/index.js | 0 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.00027373916236683726,
0.00018997944425791502,
0.00017172702064272016,
0.00017351476708427072,
0.00003747275331988931
] |
{
"id": 1,
"code_window": [
"The Strapi Studio allows you to easily build and manage your application environment\n",
"thanks to a powerful User Interface.\n",
"\n",
"Log into the Strapi Studio with your user account ([http://localhost:1338](http://localhost:1338))\n",
"and follow the instructions to start the experience.\n",
"\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"Log into the Strapi Studio with your user account ([http://studio.strapi.io](http://studio.strapi.io))\n"
],
"file_path": "README.md",
"type": "replace",
"edit_start_line_idx": 93
} | #!/usr/bin/env node
'use strict';
/**
* Module dependencies
*/
// Public node modules.
const _ = require('lodash');
// Local Strapi dependencies.
const program = require('./_commander');
const packageJSON = require('../package.json');
// Needed.
const NOOP = function () {};
let cmd;
/**
* Normalize version argument
*
* `$ strapi -v`
* `$ strapi -V`
* `$ strapi --version`
* `$ strapi version`
*/
// Expose version.
program.version(packageJSON.version, '-v, --version');
// Make `-v` option case-insensitive.
process.argv = _.map(process.argv, function (arg) {
return (arg === '-V') ? '-v' : arg;
});
// `$ strapi version` (--version synonym)
cmd = program.command('version');
cmd.description('output your version of Strapi');
cmd.action(program.versionInformation);
// `$ strapi new <name>`
cmd = program.command('new');
cmd.unknownOption = NOOP;
cmd.description('create a new application ');
cmd.action(require('./strapi-new'));
cmd.option('-d, --dry', 'naked Strapi application');
// `$ strapi start`
cmd = program.command('start');
cmd.unknownOption = NOOP;
cmd.description('start your Strapi application');
cmd.action(require('./strapi-start'));
// `$ strapi generate <generatorName>`
cmd = program.command('generate');
cmd.unknownOption = NOOP;
cmd.description('generate templates from a generator');
cmd.action(require('./strapi-generate'));
// `$ strapi console`
cmd = program.command('console');
cmd.unknownOption = NOOP;
cmd.description('open the Strapi framework console');
cmd.action(require('./strapi-console'));
// `$ strapi link`
cmd = program.command('link');
cmd.unknownOption = NOOP;
cmd.description('link an existing application to the Strapi Studio');
cmd.action(require('./strapi-link'));
// `$ strapi config`
cmd = program.command('config');
cmd.unknownOption = NOOP;
cmd.description('extend the Strapi framework with custom generators');
cmd.action(require('./strapi-config'));
// `$ strapi update`
cmd = program.command('update');
cmd.unknownOption = NOOP;
cmd.description('pull the latest updates of your custom generators');
cmd.action(require('./strapi-update'));
// `$ strapi login`
cmd = program.command('login');
cmd.unknownOption = NOOP;
cmd.description('connect your account to the Strapi Studio');
cmd.action(require('./strapi-login'));
// `$ strapi logout`
cmd = program.command('logout');
cmd.unknownOption = NOOP;
cmd.description('logout your account from the Strapi Studio');
cmd.action(require('./strapi-logout'));
/**
* Normalize help argument
*/
// `$ strapi help` (--help synonym)
cmd = program.command('help');
cmd.description('output the help');
cmd.action(program.usageMinusWildcard);
// `$ strapi <unrecognized_cmd>`
// Mask the '*' in `help`.
cmd = program.command('*');
cmd.action(program.usageMinusWildcard);
// Don't balk at unknown options.
program.unknownOption = NOOP;
/**
* `$ strapi`
*/
program.parse(process.argv);
const NO_COMMAND_SPECIFIED = program.args.length === 0;
if (NO_COMMAND_SPECIFIED) {
program.usageMinusWildcard();
}
| bin/strapi.js | 0 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.4296450912952423,
0.03414279595017433,
0.00016585476987529546,
0.00046133052092045546,
0.11420033127069473
] |
{
"id": 1,
"code_window": [
"The Strapi Studio allows you to easily build and manage your application environment\n",
"thanks to a powerful User Interface.\n",
"\n",
"Log into the Strapi Studio with your user account ([http://localhost:1338](http://localhost:1338))\n",
"and follow the instructions to start the experience.\n",
"\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"Log into the Strapi Studio with your user account ([http://studio.strapi.io](http://studio.strapi.io))\n"
],
"file_path": "README.md",
"type": "replace",
"edit_start_line_idx": 93
} | 'use strict';
const assert = require('assert');
const request = require('supertest');
const strapi = require('../../..');
const mock = require('./mocks/app');
describe('csrf', function () {
it('method', function () {
assert(typeof strapi.middlewares.lusca.csrf === 'function');
});
it('expects a thrown error if no session object', function (done) {
const app = mock({
csrf: true
}, true);
request(app.listen())
.get('/')
.expect(500, done);
});
it('GETs have a CSRF token', function (done) {
const router = strapi.middlewares.router();
const app = mock({
csrf: true
});
router.get('/csrf', function * () {
this.body = {
token: this.state._csrf
};
});
app.use(router.routes());
app.use(router.allowedMethods());
request(app.listen())
.get('/csrf')
.expect(200)
.end(function (err, res) {
assert(!err);
assert(res.body.token);
done();
});
});
// it('POST (200 OK with token)', function (done) {
// const router = strapi.middlewares.router();
// const app = mock({
// csrf: true
// });
//
// router.get('/csrf', function * () {
// this.body = {
// token: this.state._csrf
// };
// });
//
// router.post('/csrf', function * () {
// this.body = {
// token: this.state._csrf
// };
// });
//
// app.use(router.routes());
// app.use(router.allowedMethods());
//
// request(app.listen())
// .get('/csrf')
// .expect(200, function (err, res) {
// assert(!err);
// request(app.listen())
// .post('/csrf')
// .set('cookie', res.headers['set-cookie'].join(';'))
// .send({
// _csrf: res.body.token
// })
// .expect(200, done);
// });
// });
it('POST (403 Forbidden on no token)', function (done) {
const app = mock({
csrf: true
});
request(app.listen())
.post('/')
.expect(403, done);
});
// it('should allow custom keys (session type: {value})', function (done) {
// const router = strapi.middlewares.router();
// const app = mock({
// csrf: {
// key: 'foobar'
// }
// });
//
// router.all('/csrf', function * () {
// this.body = {
// token: this.state.foobar
// };
// });
//
// app.use(router.routes());
// app.use(router.allowedMethods());
//
// request(app.listen())
// .get('/csrf')
// .expect(200, function (err, res) {
// assert(!err);
// request(app.listen())
// .post('/csrf')
// .set('cookie', res.headers['set-cookie'].join(';'))
// .send({
// foobar: res.body.token
// })
// .expect(200, done);
// });
// });
//
// it('token can be sent through header instead of post body (session type: {value})', function (done) {
// const router = strapi.middlewares.router();
// const app = mock({
// csrf: true
// });
//
// router.all('/csrf', function * () {
// this.body = {
// token: this.state._csrf
// };
// });
//
// app.use(router.routes());
// app.use(router.allowedMethods());
//
// request(app.listen())
// .get('/csrf')
// .expect(200, function (err, res) {
// assert(!err);
// request(app.listen())
// .post('/csrf')
// .set('cookie', res.headers['set-cookie'].join(';'))
// .set('x-csrf-token', res.body.token)
// .send({
// name: 'Test'
// })
// .expect(200, done);
// });
// });
//
// it('should allow custom headers (session type: {value})', function (done) {
// const router = strapi.middlewares.router();
// const app = mock({
// csrf: {
// header: 'x-xsrf-token',
// secret: 'csrfSecret'
// }
// });
//
// router.all('/csrf', function * () {
// this.body = {
// token: this.state._csrf
// };
// });
//
// app.use(router.routes());
// app.use(router.allowedMethods());
//
// request(app.listen())
// .get('/csrf')
// .expect(200, function (err, res) {
// assert(!err);
// request(app.listen())
// .post('/csrf')
// .set('cookie', res.headers['set-cookie'].join(';'))
// .set('x-xsrf-token', res.body.token)
// .send({
// name: 'Test'
// })
// .expect(200, done);
// });
// });
//
// it('should allow custom functions (session type: {value})', function (done) {
// const router = strapi.middlewares.router();
// const myToken = require('./mocks/token');
//
// const mockConfig = {
// csrf: {
// impl: myToken
// }
// };
//
// const app = mock(mockConfig);
//
// router.all('/csrf', function * () {
// this.body = {
// token: this.state._csrf
// };
// });
//
// app.use(router.routes());
// app.use(router.allowedMethods());
//
// request(app.listen())
// .get('/csrf')
// .expect(200, function (err, res) {
// assert(!err);
// assert(myToken.value === res.body.token);
// request(app.listen())
// .post('/csrf')
// .set('cookie', res.headers['set-cookie'].join(';'))
// .send({
// _csrf: res.body.token
// })
// .expect(200, done);
// });
// });
});
| test/middlewares/lusca/csrf.js | 0 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.0006720786332152784,
0.0002148010244127363,
0.0001685923052718863,
0.00017925651627592742,
0.00010497785115148872
] |
{
"id": 2,
"code_window": [
"\n",
" // Read the `.strapirc` configuration file at $HOME.\n",
" fs.readFile(path.resolve(HOME, '.strapirc'), 'utf8', function (noRcFile, config) {\n",
" if (noRcFile) {\n",
" logger.warn('You do not have a `.strapirc` file at `' + HOME + '`.');\n",
" logger.warn('First, you need to create an account on http://localhost:1338/');\n",
" logger.warn('Then, execute `$ strapi login` to start the experience.');\n",
" process.exit(1);\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" logger.warn('First, you need to create an account on http://studio.strapi.io/');\n"
],
"file_path": "bin/strapi-link.js",
"type": "replace",
"edit_start_line_idx": 66
} | #!/usr/bin/env node
'use strict';
/**
* Module dependencies
*/
// Node.js core.
const fs = require('fs');
const path = require('path');
const dns = require('dns');
// Public node modules.
const _ = require('lodash');
const prompt = require('prompt');
const request = require('request');
const winston = require('winston');
// Logger.
const logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({
level: 'debug',
colorize: 'level'
})
]
});
/**
* `$ strapi login`
*
* Connect your account to the Strapi Studio.
*/
module.exports = function () {
// First, check the internet connectivity.
dns.resolve('google.com', function (err) {
if (err) {
logger.error('No internet access...');
process.exit(1);
}
// Then, start the prompt with custom options.
prompt.start();
prompt.colors = false;
prompt.message = 'your Strapi ';
prompt.delimiter = '';
// Get email address and password.
prompt.get({
properties: {
email: {
description: 'email address',
pattern: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
type: 'string',
required: true
},
password: {
description: 'password',
type: 'string',
hidden: true,
required: true
}
}
},
// Callback.
function (err, result) {
// Just in case there is an error.
if (err) {
return err;
}
// Make the request to the Studio with the email and password
// from the prompt.
request({
method: 'POST',
preambleCRLF: true,
postambleCRLF: true,
json: true,
uri: 'http://localhost:1338/auth/local',
body: {
identifier: result.email,
password: result.password
}
},
// Callback.
function (err, res, body) {
const HOME = process.env[process.platform === 'win32' ? 'USERPROFILE' : 'HOME'];
// Stop if there is an error.
if (err && err.code === 'ECONNREFUSED') {
logger.error('Impossible to establish a connection with the Strapi Studio.');
logger.error('Please try again in a few minutes...');
process.exit(1);
} else if (res.statusCode === 400) {
logger.error('Wrong credentials.');
logger.error('You are not logged in.');
process.exit(1);
}
// Try to access the `.strapirc` at $HOME.
fs.access(path.resolve(HOME, '.strapirc'), fs.F_OK | fs.R_OK | fs.W_OK, function (err) {
if (err && err.code === 'ENOENT') {
fs.writeFileSync(path.resolve(HOME, '.strapirc'), JSON.stringify({
email: body.user.email,
token: body.token
}), 'utf8');
logger.info('You are successfully logged in as ' + body.user.email);
process.exit(1);
} else {
const currentJSON = fs.readFileSync(path.resolve(HOME, '.strapirc'), 'utf8');
const newJSON = _.merge(JSON.parse(currentJSON), {
email: body.user.email,
token: body.token
});
fs.writeFileSync(path.resolve(HOME, '.strapirc'), JSON.stringify(newJSON), 'utf8');
logger.info('You are successfully logged in as ' + body.user.email);
process.exit(0);
}
});
});
});
});
};
| bin/strapi-login.js | 1 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.0618429109454155,
0.00616411492228508,
0.00016358787252102047,
0.0008617150597274303,
0.01583637110888958
] |
{
"id": 2,
"code_window": [
"\n",
" // Read the `.strapirc` configuration file at $HOME.\n",
" fs.readFile(path.resolve(HOME, '.strapirc'), 'utf8', function (noRcFile, config) {\n",
" if (noRcFile) {\n",
" logger.warn('You do not have a `.strapirc` file at `' + HOME + '`.');\n",
" logger.warn('First, you need to create an account on http://localhost:1338/');\n",
" logger.warn('Then, execute `$ strapi login` to start the experience.');\n",
" process.exit(1);\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" logger.warn('First, you need to create an account on http://studio.strapi.io/');\n"
],
"file_path": "bin/strapi-link.js",
"type": "replace",
"edit_start_line_idx": 66
} | 'use strict';
const path = require('path');
const request = require('supertest');
const strapi = require('../../..');
const Koa = strapi.server;
describe('proxy', function () {
let server;
before(function () {
const app = new Koa();
app.use(function * (next) {
if (this.path === '/error') {
this.body = '';
this.status = 500;
return;
}
if (this.path === '/postme') {
this.body = this.req;
this.set('content-type', this.request.header['content-type']);
this.status = 200;
return;
}
if (this.querystring) {
this.body = this.querystring;
return;
}
yield * next;
});
app.use(strapi.middlewares.static(path.resolve(__dirname, 'fixtures')));
server = app.listen(1234);
});
after(function () {
server.close();
});
it('should have option url', function (done) {
const app = new Koa();
const router = strapi.middlewares.router();
router.get('/index.js', strapi.middlewares.proxy({
url: 'http://localhost:1234/class.js'
}));
app.use(router.routes());
app.use(router.allowedMethods());
request(app.listen())
.get('/index.js')
.expect(200)
.expect('Content-Type', /javascript/)
.end(function (err, res) {
if (err) {
return done(err);
}
res.text.should.startWith('define("arale/class/1.0.0/class"');
done();
});
});
it('should have option url and host', function (done) {
const app = new Koa();
const router = strapi.middlewares.router();
app.use(strapi.middlewares.proxy({
host: 'http://localhost:1234',
url: 'class.js'
}));
router.get('/index.js', strapi.middlewares.proxy({
host: 'http://localhost:1234',
url: 'class.js'
}));
app.use(router.routes());
app.use(router.allowedMethods());
request(app.listen())
.get('/index.js')
.expect(200)
.expect('Content-Type', /javascript/)
.end(function (err, res) {
if (err) {
return done(err);
}
res.text.should.startWith('define("arale/class/1.0.0/class"');
done();
});
});
it('should have option host', function (done) {
const app = new Koa();
app.use(strapi.middlewares.proxy({
host: 'http://localhost:1234'
}));
request(app.listen())
.get('/class.js')
.expect(200)
.expect('Content-Type', /javascript/)
.end(function (err, res) {
if (err) {
return done(err);
}
res.text.should.startWith('define("arale/class/1.0.0/class"');
done();
});
});
it('should have option host and map', function (done) {
const app = new Koa();
app.use(strapi.middlewares.proxy({
host: 'http://localhost:1234',
map: {
'/index.js': '/class.js'
}
}));
request(app.listen())
.get('/index.js')
.expect(200)
.expect('Content-Type', /javascript/)
.end(function (err, res) {
if (err) {
return done(err);
}
res.text.should.startWith('define("arale/class/1.0.0/class"');
done();
});
});
it('should have option host and match', function (done) {
const app = new Koa();
app.use(strapi.middlewares.proxy({
host: 'http://localhost:1234',
match: /^\/[a-z]+\.js$/
}));
app.use(strapi.middlewares.proxy({
host: 'http://localhost:1234'
}));
request(app.listen())
.get('/class.js')
.expect(200)
.expect('Content-Type', /javascript/)
.end(function (err, res) {
if (err) {
return done(err);
}
res.text.should.startWith('define("arale/class/1.0.0/class"');
done();
});
});
it('url not match for url', function (done) {
const app = new Koa();
app.use(strapi.middlewares.proxy({
url: 'class.js'
}));
app.use(function * () {
this.body = 'next';
});
request(app.listen())
.get('/index.js')
.expect(200)
.expect('Content-Type', 'text/plain; charset=utf-8')
.end(function (err, res) {
if (err) {
return done(err);
}
res.text.should.eql('next');
done();
});
});
it('url not match for map', function (done) {
const app = new Koa();
app.use(strapi.middlewares.proxy({
map: {
'/index.js': '/class.js'
}
}));
app.use(function * () {
this.body = 'next';
});
request(app.listen())
.get('/index.js')
.expect(200)
.expect('Content-Type', 'text/plain; charset=utf-8')
.end(function (err, res) {
if (err) {
return done(err);
}
res.text.should.eql('next');
done();
});
});
it('option exist', function () {
(function () {
strapi.middlewares.proxy();
}).should.throw();
});
it('encoding', function (done) {
const app = new Koa();
app.use(strapi.middlewares.proxy({
url: 'http://localhost:1234/index.html',
encoding: 'gbk'
}));
request(app.listen())
.get('/index.js')
.expect(200)
.expect('Content-Type', 'text/html; charset=utf-8')
.end(function (err, res) {
if (err) {
return done(err);
}
res.text.should.startWith('<div>中国</div>');
done();
});
});
it('pass query', function (done) {
const app = new Koa();
app.use(strapi.middlewares.proxy({
url: 'http://localhost:1234/class.js',
encoding: 'gbk'
}));
request(app.listen())
.get('/index.js?a=1')
.expect(200)
.expect('Content-Type', 'text/plain; charset=utf-8')
.end(function (err, res) {
if (err) {
return done(err);
}
res.text.should.startWith('a=1');
done();
});
});
it('pass request body', function (done) {
const app = new Koa();
app.use(strapi.middlewares.proxy({
host: 'http://localhost:1234'
}));
request(app.listen())
.post('/postme')
.send({
foo: 'bar'
})
.expect(200)
.end(function (err, res) {
if (err) {
return done(err);
}
res.text.should.equal('{"foo":"bar"}');
done();
});
});
it('pass parsed request body', function (done) {
const app = new Koa();
app.use(strapi.middlewares.bodyparser());
app.use(strapi.middlewares.proxy({
host: 'http://localhost:1234'
}));
request(app.listen())
.post('/postme')
.send({
foo: 'bar'
})
.expect(200)
.end(function (err, res) {
if (err) {
return done(err);
}
res.text.should.equal('{"foo":"bar"}');
done();
});
});
it('statusCode', function (done) {
const app = new Koa();
app.use(strapi.middlewares.proxy({
host: 'http://localhost:1234'
}));
request(app.listen())
.get('/error')
.expect(500, done);
});
});
| test/middlewares/proxy/index.js | 0 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.003482333617284894,
0.0002740244672168046,
0.0001627408928470686,
0.00017135636880993843,
0.0005676105502061546
] |
{
"id": 2,
"code_window": [
"\n",
" // Read the `.strapirc` configuration file at $HOME.\n",
" fs.readFile(path.resolve(HOME, '.strapirc'), 'utf8', function (noRcFile, config) {\n",
" if (noRcFile) {\n",
" logger.warn('You do not have a `.strapirc` file at `' + HOME + '`.');\n",
" logger.warn('First, you need to create an account on http://localhost:1338/');\n",
" logger.warn('Then, execute `$ strapi login` to start the experience.');\n",
" process.exit(1);\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" logger.warn('First, you need to create an account on http://studio.strapi.io/');\n"
],
"file_path": "bin/strapi-link.js",
"type": "replace",
"edit_start_line_idx": 66
} | 'use strict';
const assert = require('assert');
const request = require('supertest');
const strapi = require('../../..');
const mock = require('./mocks/app');
describe('hsts', function () {
it('method', function () {
assert(typeof strapi.middlewares.lusca.hsts === 'function');
});
it('assert error when maxAge is not number', function () {
assert.throws(function () {
strapi.middlewares.lusca.hsts();
}, /options\.maxAge should be a number/);
});
it('header (maxAge)', function (done) {
const router = strapi.middlewares.router();
const config = {
hsts: {
maxAge: 31536000
}
};
const app = mock(config);
router.get('/', function * () {
this.body = 'hello';
});
app.use(router.routes());
app.use(router.allowedMethods());
request(app.listen())
.get('/')
.expect('Strict-Transport-Security', 'max-age=' + config.hsts.maxAge)
.expect('hello')
.expect(200, done);
});
it('header (maxAge 0)', function (done) {
const router = strapi.middlewares.router();
const config = {
hsts: {
maxAge: 0
}
};
const app = mock(config);
router.get('/', function * () {
this.body = 'hello';
});
app.use(router.routes());
app.use(router.allowedMethods());
request(app.listen())
.get('/')
.expect('Strict-Transport-Security', 'max-age=0')
.expect('hello')
.expect(200, done);
});
it('hsts = number', function (done) {
const router = strapi.middlewares.router();
const config = {
hsts: 31536000
};
const app = mock(config);
router.get('/', function * () {
this.body = 'hello';
});
app.use(router.routes());
app.use(router.allowedMethods());
request(app.listen())
.get('/')
.expect('Strict-Transport-Security', 'max-age=31536000')
.expect('hello')
.expect(200, done);
});
it('header (maxAge; includeSubDomains)', function (done) {
const router = strapi.middlewares.router();
const config = {
hsts: {
maxAge: 31536000,
includeSubDomains: true
}
};
const app = mock(config);
router.get('/', function * () {
this.body = 'hello';
});
app.use(router.routes());
app.use(router.allowedMethods());
request(app.listen())
.get('/')
.expect('Strict-Transport-Security', 'max-age=' + config.hsts.maxAge + '; includeSubDomains')
.expect('hello')
.expect(200, done);
});
it('header (maxAge; includeSubDomains; preload)', function (done) {
const router = strapi.middlewares.router();
const config = {
hsts: {
maxAge: 31536000,
includeSubDomains: true,
preload: true
}
};
const app = mock(config);
router.get('/', function * () {
this.body = 'hello';
});
app.use(router.routes());
app.use(router.allowedMethods());
request(app.listen())
.get('/')
.expect('Strict-Transport-Security', 'max-age=' + config.hsts.maxAge + '; includeSubDomains; preload')
.expect('hello')
.expect(200, done);
});
it('header (missing maxAge)', function () {
assert.throws(function () {
mock({
hsts: {}
});
}, /options\.maxAge should be a number/);
});
});
| test/middlewares/lusca/hsts.js | 0 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.004511726088821888,
0.0010786132188513875,
0.00016538746422156692,
0.0001731756783556193,
0.0014230574015527964
] |
{
"id": 2,
"code_window": [
"\n",
" // Read the `.strapirc` configuration file at $HOME.\n",
" fs.readFile(path.resolve(HOME, '.strapirc'), 'utf8', function (noRcFile, config) {\n",
" if (noRcFile) {\n",
" logger.warn('You do not have a `.strapirc` file at `' + HOME + '`.');\n",
" logger.warn('First, you need to create an account on http://localhost:1338/');\n",
" logger.warn('Then, execute `$ strapi login` to start the experience.');\n",
" process.exit(1);\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" logger.warn('First, you need to create an account on http://studio.strapi.io/');\n"
],
"file_path": "bin/strapi-link.js",
"type": "replace",
"edit_start_line_idx": 66
} | {
"locales.zh-CN": "簡體中文",
"i18n": "國際化與本地化",
"locales.en": "locales.en"
} | test/middlewares/i18n/fixtures/zh-tw.js | 0 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.00017140310956165195,
0.00017140310956165195,
0.00017140310956165195,
0.00017140310956165195,
0
] |
{
"id": 3,
"code_window": [
" preambleCRLF: true,\n",
" postambleCRLF: true,\n",
" json: true,\n",
" uri: 'http://localhost:1338/app',\n",
" body: {\n",
" name: appPkg.name,\n",
" token: config.token,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" uri: 'http://studio.strapi.io/app',\n"
],
"file_path": "bin/strapi-link.js",
"type": "replace",
"edit_start_line_idx": 87
} | #!/usr/bin/env node
'use strict';
/**
* Module dependencies
*/
// Node.js core.
const fs = require('fs');
const path = require('path');
const dns = require('dns');
// Public node modules.
const _ = require('lodash');
const request = require('request');
const winston = require('winston');
// Master of ceremonies for generators.
const generate = require('strapi-generate');
// Local Strapi dependencies.
const packageJSON = require('../package.json');
// Logger.
const logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({
level: 'debug',
colorize: 'level'
})
]
});
/**
* `$ strapi new`
*
* Generate a new Strapi application.
*/
module.exports = function () {
// Pass the original CLI arguments down to the generator.
const cliArguments = Array.prototype.slice.call(arguments);
// Build initial scope.
const scope = {
rootPath: process.cwd(),
strapiRoot: path.resolve(__dirname, '..'),
generatorType: 'new',
args: cliArguments,
strapiPackageJSON: packageJSON
};
// Save the `dry` option inside the scope.
if (scope.args[1] && scope.args[1].dry) {
scope.dry = true;
} else {
scope.dry = false;
}
// Pass the original CLI arguments down to the generator
// (but first, remove commander's extra argument)
cliArguments.pop();
scope.args = cliArguments;
scope.generatorType = 'new';
// Return the scope and the response (`error` or `success`).
return generate(scope, {
// Log and exit the REPL in case there is an error
// while we were trying to generate the new app.
error: function returnError(err) {
logger.error(err);
process.exit(1);
},
// Log and exit the REPL in case of success
// but first make sure we have an internet access
// and we have all the info we need.
success: function returnSuccess() {
const HOME = process.env[process.platform === 'win32' ? 'USERPROFILE' : 'HOME'];
dns.resolve('google.com', function (noInternetAccess) {
if (noInternetAccess) {
logger.warn('No internet access...');
logger.warn('Your application can not be linked to the Strapi Studio.');
process.exit(1);
}
// Read the `.strapirc` configuration file at $HOME.
fs.readFile(path.resolve(HOME, '.strapirc'), 'utf8', function (noRcFile, config) {
if (noRcFile) {
logger.warn('You do not have a `.strapirc` file at `' + HOME + '`.');
logger.warn('First, you need to create an account on http://localhost:1338/');
logger.warn('Then, execute `$ strapi login` to start the experience.');
process.exit(1);
}
// Parse the config file.
config = JSON.parse(config);
// Create a new application on the Strapi Studio.
request({
method: 'POST',
preambleCRLF: true,
postambleCRLF: true,
json: true,
uri: 'http://localhost:1338/app',
body: {
name: cliArguments[0],
token: config.token
}
},
// Callback.
function (err, res) {
// Log and exit if no internet access.
if (err) {
logger.warn('Impossible to access the Strapi Studio.');
logger.warn('Your application is not linked to the Strapi Studio.');
process.exit(1);
}
// Parse the RC file.
const currentJSON = JSON.parse(fs.readFileSync(path.resolve('config', 'studio.json'), 'utf8'));
const newJSON = JSON.stringify(_.merge(currentJSON, {studio: {appId: res.body.appId}}), null, ' ');
// Write the new `./config/studio.json` with credentials.
fs.writeFile(path.resolve('config', 'studio.json'), newJSON, 'utf8', function (err) {
if (err) {
logger.error('Impossible to write the `appId`.');
process.exit(1);
}
process.exit(0);
});
});
});
});
}
});
};
| bin/strapi-new.js | 1 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.16046394407749176,
0.01118585467338562,
0.00016723634325899184,
0.00017326619126833975,
0.03991292044520378
] |
{
"id": 3,
"code_window": [
" preambleCRLF: true,\n",
" postambleCRLF: true,\n",
" json: true,\n",
" uri: 'http://localhost:1338/app',\n",
" body: {\n",
" name: appPkg.name,\n",
" token: config.token,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" uri: 'http://studio.strapi.io/app',\n"
],
"file_path": "bin/strapi-link.js",
"type": "replace",
"edit_start_line_idx": 87
} | 'use strict';
const context = require('../helpers/context');
describe('ctx.inspect()', function () {
it('should return a json representation', function () {
const ctx = context();
const toJSON = ctx.toJSON(ctx);
toJSON.should.eql(ctx.inspect());
});
});
| test/context/inspect.js | 0 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.00017518458480481058,
0.00017268129158765078,
0.00017017799837049097,
0.00017268129158765078,
0.0000025032932171598077
] |
{
"id": 3,
"code_window": [
" preambleCRLF: true,\n",
" postambleCRLF: true,\n",
" json: true,\n",
" uri: 'http://localhost:1338/app',\n",
" body: {\n",
" name: appPkg.name,\n",
" token: config.token,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" uri: 'http://studio.strapi.io/app',\n"
],
"file_path": "bin/strapi-link.js",
"type": "replace",
"edit_start_line_idx": 87
} | 'use strict';
const assert = require('assert');
const context = require('../helpers/context');
describe('ctx.throw(msg)', function () {
it('should set .status to 500', function (done) {
const ctx = context();
try {
ctx.throw('boom');
} catch (err) {
assert(err.status === 500);
assert(!err.expose);
done();
}
});
});
describe('ctx.throw(err)', function () {
it('should set .status to 500', function (done) {
const ctx = context();
const err = new Error('test');
try {
ctx.throw(err);
} catch (err) {
assert(err.status === 500);
assert(err.message === 'test');
assert(!err.expose);
done();
}
});
});
describe('ctx.throw(err, status)', function () {
it('should throw the error and set .status', function (done) {
const ctx = context();
const error = new Error('test');
try {
ctx.throw(error, 422);
} catch (err) {
assert(err.status === 422);
assert(err.message === 'test');
assert(err.expose === true);
done();
}
});
});
describe('ctx.throw(status, err)', function () {
it('should throw the error and set .status', function (done) {
const ctx = context();
const error = new Error('test');
try {
ctx.throw(422, error);
} catch (err) {
assert(err.status === 422);
assert(err.message === 'test');
assert(err.expose === true);
done();
}
});
});
describe('ctx.throw(msg, status)', function () {
it('should throw an error', function (done) {
const ctx = context();
try {
ctx.throw('name required', 400);
} catch (err) {
assert(err.message === 'name required');
assert(err.status === 400);
assert(err.expose === true);
done();
}
});
});
describe('ctx.throw(status, msg)', function () {
it('should throw an error', function (done) {
const ctx = context();
try {
ctx.throw(400, 'name required');
} catch (err) {
assert(err.message === 'name required');
assert(err.status === 400);
assert(err.expose === true);
done();
}
});
});
describe('ctx.throw(status)', function () {
it('should throw an error', function (done) {
const ctx = context();
try {
ctx.throw(400);
} catch (err) {
assert(err.message === 'Bad Request');
assert(err.status === 400);
assert(err.expose === true);
done();
}
});
describe('when not valid status', function () {
it('should not expose', function (done) {
const ctx = context();
try {
const err = new Error('some error');
err.status = -1;
ctx.throw(err);
} catch (err) {
assert(err.message === 'some error');
assert(!err.expose);
done();
}
});
});
});
describe('ctx.throw(status, msg, props)', function () {
it('should mixin props', function (done) {
const ctx = context();
try {
ctx.throw(400, 'msg', {
prop: true
});
} catch (err) {
assert(err.message === 'msg');
assert(err.status === 400);
assert(err.expose === true);
assert(err.prop === true);
done();
}
});
describe('when props include status', function () {
it('should be ignored', function (done) {
const ctx = context();
try {
ctx.throw(400, 'msg', {
prop: true,
status: -1
});
} catch (err) {
assert(err.message === 'msg');
assert(err.status === 400);
assert(err.expose === true);
assert(err.prop === true);
done();
}
});
});
});
describe('ctx.throw(msg, props)', function () {
it('should mixin props', function (done) {
const ctx = context();
try {
ctx.throw('msg', {
prop: true
});
} catch (err) {
assert(err.message === 'msg');
assert(err.status === 500);
assert(err.expose === false);
assert(err.prop === true);
done();
}
});
});
describe('ctx.throw(status, props)', function () {
it('should mixin props', function (done) {
const ctx = context();
try {
ctx.throw(400, {
prop: true
});
} catch (err) {
assert(err.message === 'Bad Request');
assert(err.status === 400);
assert(err.expose === true);
assert(err.prop === true);
done();
}
});
});
describe('ctx.throw(err, props)', function () {
it('should mixin props', function (done) {
const ctx = context();
try {
ctx.throw(new Error('test'), {
prop: true
});
} catch (err) {
assert(err.message === 'test');
assert(err.status === 500);
assert(err.expose === false);
assert(err.prop === true);
done();
}
});
});
| test/context/throw.js | 0 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.00017578461847733706,
0.00017322621715720743,
0.0001697902916930616,
0.00017325565568171442,
0.0000014307300943983137
] |
{
"id": 3,
"code_window": [
" preambleCRLF: true,\n",
" postambleCRLF: true,\n",
" json: true,\n",
" uri: 'http://localhost:1338/app',\n",
" body: {\n",
" name: appPkg.name,\n",
" token: config.token,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" uri: 'http://studio.strapi.io/app',\n"
],
"file_path": "bin/strapi-link.js",
"type": "replace",
"edit_start_line_idx": 87
} | 'use strict';
const path = require('path');
const request = require('supertest');
const strapi = require('../../..');
const Koa = strapi.server;
describe('proxy', function () {
let server;
before(function () {
const app = new Koa();
app.use(function * (next) {
if (this.path === '/error') {
this.body = '';
this.status = 500;
return;
}
if (this.path === '/postme') {
this.body = this.req;
this.set('content-type', this.request.header['content-type']);
this.status = 200;
return;
}
if (this.querystring) {
this.body = this.querystring;
return;
}
yield * next;
});
app.use(strapi.middlewares.static(path.resolve(__dirname, 'fixtures')));
server = app.listen(1234);
});
after(function () {
server.close();
});
it('should have option url', function (done) {
const app = new Koa();
const router = strapi.middlewares.router();
router.get('/index.js', strapi.middlewares.proxy({
url: 'http://localhost:1234/class.js'
}));
app.use(router.routes());
app.use(router.allowedMethods());
request(app.listen())
.get('/index.js')
.expect(200)
.expect('Content-Type', /javascript/)
.end(function (err, res) {
if (err) {
return done(err);
}
res.text.should.startWith('define("arale/class/1.0.0/class"');
done();
});
});
it('should have option url and host', function (done) {
const app = new Koa();
const router = strapi.middlewares.router();
app.use(strapi.middlewares.proxy({
host: 'http://localhost:1234',
url: 'class.js'
}));
router.get('/index.js', strapi.middlewares.proxy({
host: 'http://localhost:1234',
url: 'class.js'
}));
app.use(router.routes());
app.use(router.allowedMethods());
request(app.listen())
.get('/index.js')
.expect(200)
.expect('Content-Type', /javascript/)
.end(function (err, res) {
if (err) {
return done(err);
}
res.text.should.startWith('define("arale/class/1.0.0/class"');
done();
});
});
it('should have option host', function (done) {
const app = new Koa();
app.use(strapi.middlewares.proxy({
host: 'http://localhost:1234'
}));
request(app.listen())
.get('/class.js')
.expect(200)
.expect('Content-Type', /javascript/)
.end(function (err, res) {
if (err) {
return done(err);
}
res.text.should.startWith('define("arale/class/1.0.0/class"');
done();
});
});
it('should have option host and map', function (done) {
const app = new Koa();
app.use(strapi.middlewares.proxy({
host: 'http://localhost:1234',
map: {
'/index.js': '/class.js'
}
}));
request(app.listen())
.get('/index.js')
.expect(200)
.expect('Content-Type', /javascript/)
.end(function (err, res) {
if (err) {
return done(err);
}
res.text.should.startWith('define("arale/class/1.0.0/class"');
done();
});
});
it('should have option host and match', function (done) {
const app = new Koa();
app.use(strapi.middlewares.proxy({
host: 'http://localhost:1234',
match: /^\/[a-z]+\.js$/
}));
app.use(strapi.middlewares.proxy({
host: 'http://localhost:1234'
}));
request(app.listen())
.get('/class.js')
.expect(200)
.expect('Content-Type', /javascript/)
.end(function (err, res) {
if (err) {
return done(err);
}
res.text.should.startWith('define("arale/class/1.0.0/class"');
done();
});
});
it('url not match for url', function (done) {
const app = new Koa();
app.use(strapi.middlewares.proxy({
url: 'class.js'
}));
app.use(function * () {
this.body = 'next';
});
request(app.listen())
.get('/index.js')
.expect(200)
.expect('Content-Type', 'text/plain; charset=utf-8')
.end(function (err, res) {
if (err) {
return done(err);
}
res.text.should.eql('next');
done();
});
});
it('url not match for map', function (done) {
const app = new Koa();
app.use(strapi.middlewares.proxy({
map: {
'/index.js': '/class.js'
}
}));
app.use(function * () {
this.body = 'next';
});
request(app.listen())
.get('/index.js')
.expect(200)
.expect('Content-Type', 'text/plain; charset=utf-8')
.end(function (err, res) {
if (err) {
return done(err);
}
res.text.should.eql('next');
done();
});
});
it('option exist', function () {
(function () {
strapi.middlewares.proxy();
}).should.throw();
});
it('encoding', function (done) {
const app = new Koa();
app.use(strapi.middlewares.proxy({
url: 'http://localhost:1234/index.html',
encoding: 'gbk'
}));
request(app.listen())
.get('/index.js')
.expect(200)
.expect('Content-Type', 'text/html; charset=utf-8')
.end(function (err, res) {
if (err) {
return done(err);
}
res.text.should.startWith('<div>中国</div>');
done();
});
});
it('pass query', function (done) {
const app = new Koa();
app.use(strapi.middlewares.proxy({
url: 'http://localhost:1234/class.js',
encoding: 'gbk'
}));
request(app.listen())
.get('/index.js?a=1')
.expect(200)
.expect('Content-Type', 'text/plain; charset=utf-8')
.end(function (err, res) {
if (err) {
return done(err);
}
res.text.should.startWith('a=1');
done();
});
});
it('pass request body', function (done) {
const app = new Koa();
app.use(strapi.middlewares.proxy({
host: 'http://localhost:1234'
}));
request(app.listen())
.post('/postme')
.send({
foo: 'bar'
})
.expect(200)
.end(function (err, res) {
if (err) {
return done(err);
}
res.text.should.equal('{"foo":"bar"}');
done();
});
});
it('pass parsed request body', function (done) {
const app = new Koa();
app.use(strapi.middlewares.bodyparser());
app.use(strapi.middlewares.proxy({
host: 'http://localhost:1234'
}));
request(app.listen())
.post('/postme')
.send({
foo: 'bar'
})
.expect(200)
.end(function (err, res) {
if (err) {
return done(err);
}
res.text.should.equal('{"foo":"bar"}');
done();
});
});
it('statusCode', function (done) {
const app = new Koa();
app.use(strapi.middlewares.proxy({
host: 'http://localhost:1234'
}));
request(app.listen())
.get('/error')
.expect(500, done);
});
});
| test/middlewares/proxy/index.js | 0 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.00018943598843179643,
0.0001714197132969275,
0.0001625594450160861,
0.00017071919864974916,
0.0000047050252760527655
] |
{
"id": 4,
"code_window": [
" request({\n",
" method: 'POST',\n",
" preambleCRLF: true,\n",
" postambleCRLF: true,\n",
" json: true,\n",
" uri: 'http://localhost:1338/auth/local',\n",
" body: {\n",
" identifier: result.email,\n",
" password: result.password\n",
" }\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" uri: 'http://studio.strapi.io/auth/local',\n"
],
"file_path": "bin/strapi-login.js",
"type": "replace",
"edit_start_line_idx": 83
} | #!/usr/bin/env node
'use strict';
/**
* Module dependencies
*/
// Node.js core.
const fs = require('fs');
const path = require('path');
const dns = require('dns');
// Public node modules.
const _ = require('lodash');
const request = require('request');
const winston = require('winston');
// Master of ceremonies for generators.
const generate = require('strapi-generate');
// Local Strapi dependencies.
const packageJSON = require('../package.json');
// Logger.
const logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({
level: 'debug',
colorize: 'level'
})
]
});
/**
* `$ strapi new`
*
* Generate a new Strapi application.
*/
module.exports = function () {
// Pass the original CLI arguments down to the generator.
const cliArguments = Array.prototype.slice.call(arguments);
// Build initial scope.
const scope = {
rootPath: process.cwd(),
strapiRoot: path.resolve(__dirname, '..'),
generatorType: 'new',
args: cliArguments,
strapiPackageJSON: packageJSON
};
// Save the `dry` option inside the scope.
if (scope.args[1] && scope.args[1].dry) {
scope.dry = true;
} else {
scope.dry = false;
}
// Pass the original CLI arguments down to the generator
// (but first, remove commander's extra argument)
cliArguments.pop();
scope.args = cliArguments;
scope.generatorType = 'new';
// Return the scope and the response (`error` or `success`).
return generate(scope, {
// Log and exit the REPL in case there is an error
// while we were trying to generate the new app.
error: function returnError(err) {
logger.error(err);
process.exit(1);
},
// Log and exit the REPL in case of success
// but first make sure we have an internet access
// and we have all the info we need.
success: function returnSuccess() {
const HOME = process.env[process.platform === 'win32' ? 'USERPROFILE' : 'HOME'];
dns.resolve('google.com', function (noInternetAccess) {
if (noInternetAccess) {
logger.warn('No internet access...');
logger.warn('Your application can not be linked to the Strapi Studio.');
process.exit(1);
}
// Read the `.strapirc` configuration file at $HOME.
fs.readFile(path.resolve(HOME, '.strapirc'), 'utf8', function (noRcFile, config) {
if (noRcFile) {
logger.warn('You do not have a `.strapirc` file at `' + HOME + '`.');
logger.warn('First, you need to create an account on http://localhost:1338/');
logger.warn('Then, execute `$ strapi login` to start the experience.');
process.exit(1);
}
// Parse the config file.
config = JSON.parse(config);
// Create a new application on the Strapi Studio.
request({
method: 'POST',
preambleCRLF: true,
postambleCRLF: true,
json: true,
uri: 'http://localhost:1338/app',
body: {
name: cliArguments[0],
token: config.token
}
},
// Callback.
function (err, res) {
// Log and exit if no internet access.
if (err) {
logger.warn('Impossible to access the Strapi Studio.');
logger.warn('Your application is not linked to the Strapi Studio.');
process.exit(1);
}
// Parse the RC file.
const currentJSON = JSON.parse(fs.readFileSync(path.resolve('config', 'studio.json'), 'utf8'));
const newJSON = JSON.stringify(_.merge(currentJSON, {studio: {appId: res.body.appId}}), null, ' ');
// Write the new `./config/studio.json` with credentials.
fs.writeFile(path.resolve('config', 'studio.json'), newJSON, 'utf8', function (err) {
if (err) {
logger.error('Impossible to write the `appId`.');
process.exit(1);
}
process.exit(0);
});
});
});
});
}
});
};
| bin/strapi-new.js | 1 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.001891017658635974,
0.00035678796120919287,
0.00016583941760472953,
0.00017019569349940866,
0.0004900396452285349
] |
{
"id": 4,
"code_window": [
" request({\n",
" method: 'POST',\n",
" preambleCRLF: true,\n",
" postambleCRLF: true,\n",
" json: true,\n",
" uri: 'http://localhost:1338/auth/local',\n",
" body: {\n",
" identifier: result.email,\n",
" password: result.password\n",
" }\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" uri: 'http://studio.strapi.io/auth/local',\n"
],
"file_path": "bin/strapi-login.js",
"type": "replace",
"edit_start_line_idx": 83
} | 'use strict';
/**
* Module dependencies
*/
// Node.js core.
const fs = require('fs');
const path = require('path');
// Public node modules.
const _ = require('lodash');
const async = require('async');
// Local utilities.
const dictionary = require('../../../../util/dictionary');
/**
* Async module loader to create a
* dictionary of the user config
*/
module.exports = function (strapi) {
const hook = {
/**
* Initialize the hook
*/
initialize: function (cb) {
async.auto({
// Load common settings from `./config/*.js|json`.
'config/*': function (cb) {
dictionary.aggregate({
dirname: path.resolve(strapi.config.appPath, strapi.config.paths.config),
excludeDirs: /(locales|environments)$/,
filter: /(.+)\.(js|json)$/,
depth: 2
}, cb);
},
// Load locales from `./config/locales/*.json`.
'config/locales/*': function (cb) {
dictionary.optional({
dirname: path.resolve(strapi.config.appPath, strapi.config.paths.config, 'locales'),
filter: /(.+)\.(json)$/,
identity: false,
depth: 1
}, cb);
},
// Load functions config from `./config/functions/*.js`.
'config/functions/*': function (cb) {
dictionary.aggregate({
dirname: path.resolve(strapi.config.appPath, strapi.config.paths.config, 'functions'),
filter: /(.+)\.(js)$/,
depth: 1
}, cb);
},
// Load all environments config from `./config/environments/*/*.js|json`.
// Not really used inside the framework but useful for the Studio.
'config/environments/**': function (cb) {
dictionary.optional({
dirname: path.resolve(strapi.config.appPath, strapi.config.paths.config, 'environments'),
filter: /(.+)\.(js|json)$/,
identity: false,
depth: 4
}, cb);
},
// Load environment-specific config from `./config/environments/**/*.js|json`.
'config/environments/*': function (cb) {
dictionary.aggregate({
dirname: path.resolve(strapi.config.appPath, strapi.config.paths.config, 'environments', strapi.config.environment),
filter: /(.+)\.(js|json)$/,
depth: 1
}, cb);
},
// Load APIs from `./api/**/*.js|json`.
'api/**': function (cb) {
dictionary.optional({
dirname: path.resolve(strapi.config.appPath, strapi.config.paths.api),
excludeDirs: /(public)$/,
filter: /(.+)\.(js|json)$/,
depth: 4
}, cb);
}
},
// Callback.
function (err, config) {
// Just in case there is an error.
if (err) {
return cb(err);
}
// Merge every user config together.
const mergedConfig = _.merge(
config['config/*'],
config['config/environments/*'],
config['config/functions/*']
);
// Remove cache
delete require.cache[path.resolve(strapi.config.appPath, 'package.json')];
// Local `package.json`.
const packageJSON = require(path.resolve(strapi.config.appPath, 'package.json'));
// Merge default config and user loaded config together inside `strapi.config`.
strapi.config = _.merge(strapi.config, mergedConfig, packageJSON);
// Expose user APIs.
strapi.api = config['api/**'];
// Add user locales for the settings of the `i18n` hook
// aiming to load locales automatically.
if (_.isPlainObject(strapi.config.i18n) && !_.isEmpty(strapi.config.i18n)) {
strapi.config.i18n.locales = [];
_.forEach(config['config/locales/*'], function (strings, lang) {
strapi.config.i18n.locales.push(lang);
});
}
// Make sure the ORM config are equals to the databases file
// (aiming to not have issue with adapters when rebuilding the dictionary).
// It's kind of messy, for now, but it works fine. If someone has a better
// solution we'd be glad to accept a Pull Request.
if (!strapi.config.dry) {
const ormConfig = JSON.parse(fs.readFileSync(path.resolve(strapi.config.appPath, strapi.config.paths.config, 'environments', strapi.config.environment, 'databases.json')));
strapi.config.orm = ormConfig.orm;
}
// Save different environments because we need it in the Strapi Studio.
strapi.config.environments = config['config/environments/**'] || {};
// Make the application name in config match the server one.
strapi.app.name = strapi.config.name;
// Initialize empty API objects.
strapi.controllers = {};
strapi.models = {};
strapi.policies = {};
cb();
});
},
/**
* Reload the hook
*/
reload: function () {
hook.initialize(function (err) {
if (err) {
strapi.log.error('Failed to reinitialize the config hook.');
strapi.stop();
} else {
strapi.emit('hook:_config:reloaded');
}
});
}
};
return hook;
};
| lib/configuration/hooks/_config/index.js | 0 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.00017309511895291507,
0.00016974522441159934,
0.00016537010378669947,
0.00016988549032248557,
0.0000022273968625086127
] |
{
"id": 4,
"code_window": [
" request({\n",
" method: 'POST',\n",
" preambleCRLF: true,\n",
" postambleCRLF: true,\n",
" json: true,\n",
" uri: 'http://localhost:1338/auth/local',\n",
" body: {\n",
" identifier: result.email,\n",
" password: result.password\n",
" }\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" uri: 'http://studio.strapi.io/auth/local',\n"
],
"file_path": "bin/strapi-login.js",
"type": "replace",
"edit_start_line_idx": 83
} | 'use strict';
const context = require('../helpers/context');
describe('ctx.remove(name)', function () {
it('should remove a field', function () {
const ctx = context();
ctx.set('x-foo', 'bar');
ctx.remove('x-foo');
ctx.response.header.should.eql({});
});
});
| test/response/remove.js | 0 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.00017071740876417607,
0.00017045257845893502,
0.00017018773360177875,
0.00017045257845893502,
2.648375811986625e-7
] |
{
"id": 4,
"code_window": [
" request({\n",
" method: 'POST',\n",
" preambleCRLF: true,\n",
" postambleCRLF: true,\n",
" json: true,\n",
" uri: 'http://localhost:1338/auth/local',\n",
" body: {\n",
" identifier: result.email,\n",
" password: result.password\n",
" }\n",
" },\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" uri: 'http://studio.strapi.io/auth/local',\n"
],
"file_path": "bin/strapi-login.js",
"type": "replace",
"edit_start_line_idx": 83
} | html index | test/middlewares/static/fixtures/world/index.html | 0 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.00017311261035501957,
0.00017311261035501957,
0.00017311261035501957,
0.00017311261035501957,
0
] |
{
"id": 5,
"code_window": [
" fs.readFile(path.resolve(HOME, '.strapirc'), 'utf8', function (noRcFile, config) {\n",
" if (noRcFile) {\n",
" logger.warn('You do not have a `.strapirc` file at `' + HOME + '`.');\n",
" logger.warn('First, you need to create an account on http://localhost:1338/');\n",
" logger.warn('Then, execute `$ strapi login` to start the experience.');\n",
" process.exit(1);\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" logger.warn('First, you need to create an account on http://studio.strapi.io/');\n"
],
"file_path": "bin/strapi-new.js",
"type": "replace",
"edit_start_line_idx": 94
} | #!/usr/bin/env node
'use strict';
/**
* Module dependencies
*/
// Node.js core.
const fs = require('fs');
const path = require('path');
const dns = require('dns');
// Public node modules.
const _ = require('lodash');
const request = require('request');
const winston = require('winston');
// Master of ceremonies for generators.
const generate = require('strapi-generate');
// Local Strapi dependencies.
const packageJSON = require('../package.json');
// Logger.
const logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({
level: 'debug',
colorize: 'level'
})
]
});
/**
* `$ strapi new`
*
* Generate a new Strapi application.
*/
module.exports = function () {
// Pass the original CLI arguments down to the generator.
const cliArguments = Array.prototype.slice.call(arguments);
// Build initial scope.
const scope = {
rootPath: process.cwd(),
strapiRoot: path.resolve(__dirname, '..'),
generatorType: 'new',
args: cliArguments,
strapiPackageJSON: packageJSON
};
// Save the `dry` option inside the scope.
if (scope.args[1] && scope.args[1].dry) {
scope.dry = true;
} else {
scope.dry = false;
}
// Pass the original CLI arguments down to the generator
// (but first, remove commander's extra argument)
cliArguments.pop();
scope.args = cliArguments;
scope.generatorType = 'new';
// Return the scope and the response (`error` or `success`).
return generate(scope, {
// Log and exit the REPL in case there is an error
// while we were trying to generate the new app.
error: function returnError(err) {
logger.error(err);
process.exit(1);
},
// Log and exit the REPL in case of success
// but first make sure we have an internet access
// and we have all the info we need.
success: function returnSuccess() {
const HOME = process.env[process.platform === 'win32' ? 'USERPROFILE' : 'HOME'];
dns.resolve('google.com', function (noInternetAccess) {
if (noInternetAccess) {
logger.warn('No internet access...');
logger.warn('Your application can not be linked to the Strapi Studio.');
process.exit(1);
}
// Read the `.strapirc` configuration file at $HOME.
fs.readFile(path.resolve(HOME, '.strapirc'), 'utf8', function (noRcFile, config) {
if (noRcFile) {
logger.warn('You do not have a `.strapirc` file at `' + HOME + '`.');
logger.warn('First, you need to create an account on http://localhost:1338/');
logger.warn('Then, execute `$ strapi login` to start the experience.');
process.exit(1);
}
// Parse the config file.
config = JSON.parse(config);
// Create a new application on the Strapi Studio.
request({
method: 'POST',
preambleCRLF: true,
postambleCRLF: true,
json: true,
uri: 'http://localhost:1338/app',
body: {
name: cliArguments[0],
token: config.token
}
},
// Callback.
function (err, res) {
// Log and exit if no internet access.
if (err) {
logger.warn('Impossible to access the Strapi Studio.');
logger.warn('Your application is not linked to the Strapi Studio.');
process.exit(1);
}
// Parse the RC file.
const currentJSON = JSON.parse(fs.readFileSync(path.resolve('config', 'studio.json'), 'utf8'));
const newJSON = JSON.stringify(_.merge(currentJSON, {studio: {appId: res.body.appId}}), null, ' ');
// Write the new `./config/studio.json` with credentials.
fs.writeFile(path.resolve('config', 'studio.json'), newJSON, 'utf8', function (err) {
if (err) {
logger.error('Impossible to write the `appId`.');
process.exit(1);
}
process.exit(0);
});
});
});
});
}
});
};
| bin/strapi-new.js | 1 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.9979478716850281,
0.06777356564998627,
0.0001672503858571872,
0.00023923159460537136,
0.24861153960227966
] |
{
"id": 5,
"code_window": [
" fs.readFile(path.resolve(HOME, '.strapirc'), 'utf8', function (noRcFile, config) {\n",
" if (noRcFile) {\n",
" logger.warn('You do not have a `.strapirc` file at `' + HOME + '`.');\n",
" logger.warn('First, you need to create an account on http://localhost:1338/');\n",
" logger.warn('Then, execute `$ strapi login` to start the experience.');\n",
" process.exit(1);\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" logger.warn('First, you need to create an account on http://studio.strapi.io/');\n"
],
"file_path": "bin/strapi-new.js",
"type": "replace",
"edit_start_line_idx": 94
} | 'use strict';
/**
* Module dependencies
*/
// Public node modules.
const _ = require('lodash');
/**
* Detect HTTP verb in an expression.
*
* @api private
*/
exports.detectRoute = function (endpoint) {
const verbExpr = /^(all|get|post|put|delete|trace|options|connect|patch|head|redirect)\s+/i;
let verb = _.last(endpoint.match(verbExpr) || []) || '';
verb = verb.toLowerCase();
// If a verb was specified, eliminate the verb from the original string.
if (verb) {
endpoint = endpoint.replace(verbExpr, '');
}
// Return the verb and the endpoint.
return {
verb: verb,
endpoint: endpoint
};
};
| util/regex.js | 0 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.00017349020345136523,
0.00016933436563704163,
0.000163109420100227,
0.0001703689049463719,
0.000003841750640276587
] |
{
"id": 5,
"code_window": [
" fs.readFile(path.resolve(HOME, '.strapirc'), 'utf8', function (noRcFile, config) {\n",
" if (noRcFile) {\n",
" logger.warn('You do not have a `.strapirc` file at `' + HOME + '`.');\n",
" logger.warn('First, you need to create an account on http://localhost:1338/');\n",
" logger.warn('Then, execute `$ strapi login` to start the experience.');\n",
" process.exit(1);\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" logger.warn('First, you need to create an account on http://studio.strapi.io/');\n"
],
"file_path": "bin/strapi-new.js",
"type": "replace",
"edit_start_line_idx": 94
} | <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<p>basic:html</p>
</body>
</html>
| test/middlewares/views/fixtures/basic.html | 0 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.00017333724827039987,
0.00017295885481871665,
0.00017258046136703342,
0.00017295885481871665,
3.7839345168322325e-7
] |
{
"id": 5,
"code_window": [
" fs.readFile(path.resolve(HOME, '.strapirc'), 'utf8', function (noRcFile, config) {\n",
" if (noRcFile) {\n",
" logger.warn('You do not have a `.strapirc` file at `' + HOME + '`.');\n",
" logger.warn('First, you need to create an account on http://localhost:1338/');\n",
" logger.warn('Then, execute `$ strapi login` to start the experience.');\n",
" process.exit(1);\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" logger.warn('First, you need to create an account on http://studio.strapi.io/');\n"
],
"file_path": "bin/strapi-new.js",
"type": "replace",
"edit_start_line_idx": 94
} | language: node_js
node_js:
- "4"
sudo: false
script: "make test-travis"
after_script: "npm install coveralls@2 && cat ./coverage/lcov.info | coveralls"
notifications:
slack:
secure: WUmEtUpfbSrt59VsvYhdMHBJgqROaU3Zp5KRo/BpPdExQec00y0YikhJaDRkV2LMiq1I9dOW2kWRBpFSZqMcqIhPMN+poheqiuSs2Cly28UbzpAAb4dA574gfhgCCfEuAAHiAT6m89NWoF5opey7cha/tlKCnGuOTbDvm1S3OjcIhc+Jno4uE4BoMpH+75GBXKyTlICrLhnOT4RvoN2FrjnYA01+x2x283C7cIr77JviHcbh3l5Cy1fSkxB5liL1jyKypxUrELgW0cI+CegR8cJ1CUGurs7sB2I7s45lnNZdmUvl8ZDtt4SQCRTNvnU/hfHuDrK78c2JJu8xKGW7cpoDDROxk8gdiPYwWxh4SndtI04n9ZtdS7vW1uMqEH2ZI+96mcxvjYUxTGbfMouXSPTDqTYhwxm1NWYDiLN6lm1k37Xs/lY34jJqeiAQYtQzxxmxUgDmwxbgo5m0Y7ZMKAdv1+GvC9/DT8/9c779iTVC4rRAZOtsrC3sTJ3vG3gNsxuNk89eLxgd/VqvoVd7hwmr3g7l8n5waRKK0+gTW8jSu3CfZ0rXsOVe1NH48VYhU//efMDhjC8YMLcidrJywCesoRkYZ9gB08MeWuzMNgLRMYpddA0pm6dW9Sav8SH+HzbUDqeTH1+VzxoLUm4JpkFRJw37H18KMqLhVUE1V8c=
| .travis.yml | 0 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.00027222491917200387,
0.00022246738080866635,
0.0001727098278934136,
0.00022246738080866635,
0.00004975754563929513
] |
{
"id": 6,
"code_window": [
" method: 'POST',\n",
" preambleCRLF: true,\n",
" postambleCRLF: true,\n",
" json: true,\n",
" uri: 'http://localhost:1338/app',\n",
" body: {\n",
" name: cliArguments[0],\n",
" token: config.token\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" uri: 'http://studio.strapi.io/app',\n"
],
"file_path": "bin/strapi-new.js",
"type": "replace",
"edit_start_line_idx": 108
} | #!/usr/bin/env node
'use strict';
/**
* Module dependencies
*/
// Node.js core.
const fs = require('fs');
const path = require('path');
const dns = require('dns');
// Public node modules.
const _ = require('lodash');
const request = require('request');
const winston = require('winston');
// Logger.
const logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({
level: 'debug',
colorize: 'level'
})
]
});
/**
* `$ strapi link`
*
* Link an existing application to the Strapi Studio
*/
module.exports = function () {
const HOME = process.env[process.platform === 'win32' ? 'USERPROFILE' : 'HOME'];
const pathToPackageJSON = path.resolve(process.cwd(), 'package.json');
const pathToStudioJSON = path.resolve(process.cwd(), 'config', 'studio.json');
const appPkg = JSON.parse(fs.readFileSync(pathToPackageJSON));
const studioConfig = JSON.parse(fs.readFileSync(pathToStudioJSON));
let invalidPackageJSON;
// First, check if we are in a Strapi project.
try {
require(pathToPackageJSON);
} catch (err) {
invalidPackageJSON = true;
}
if (invalidPackageJSON) {
logger.error('This command can only be used inside an Strapi project.');
process.exit(1);
}
// Check the internet connectivity.
dns.resolve('google.com', function (noInternetAccess) {
if (noInternetAccess) {
logger.warn('No internet access...');
logger.warn('Your application can not be linked to the Strapi Studio.');
process.exit(1);
}
// Read the `.strapirc` configuration file at $HOME.
fs.readFile(path.resolve(HOME, '.strapirc'), 'utf8', function (noRcFile, config) {
if (noRcFile) {
logger.warn('You do not have a `.strapirc` file at `' + HOME + '`.');
logger.warn('First, you need to create an account on http://localhost:1338/');
logger.warn('Then, execute `$ strapi login` to start the experience.');
process.exit(1);
}
// Parse the config file.
config = JSON.parse(config);
// Make sure the developer is logged in.
if (_.isEmpty(config.email) || _.isEmpty(config.token)) {
logger.error('You are not logged in.');
logger.error('Execute `$ strapi login` to start the experience.');
process.exit(1);
}
// Create a new application on the Strapi Studio.
request({
method: 'POST',
preambleCRLF: true,
postambleCRLF: true,
json: true,
uri: 'http://localhost:1338/app',
body: {
name: appPkg.name,
token: config.token,
appToDelete: studioConfig.studio.appId
}
},
// Callback.
function (err, res) {
// Log and exit if no internet access.
if (err) {
logger.warn('Impossible to access the Strapi Studio.');
logger.warn('Your application is not linked to the Strapi Studio.');
process.exit(1);
}
// Parse the RC file.
const currentJSON = JSON.parse(fs.readFileSync(path.resolve('config', 'studio.json'), 'utf8'));
const newJSON = JSON.stringify(_.merge(currentJSON, {studio: {appId: res.body.appId}}), null, ' ');
// Write the new `./config/studio.json` with credentials.
fs.writeFile(path.resolve('config', 'studio.json'), newJSON, 'utf8', function (err) {
if (err) {
logger.error('Impossible to write the `appId`.');
process.exit(1);
} else {
logger.info('Your application has successfully been linked to the Studio.');
}
process.exit(0);
});
});
});
});
};
| bin/strapi-link.js | 1 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.008076226338744164,
0.0010566848795861006,
0.00016192332259379327,
0.00017006704001687467,
0.0021257742773741484
] |
{
"id": 6,
"code_window": [
" method: 'POST',\n",
" preambleCRLF: true,\n",
" postambleCRLF: true,\n",
" json: true,\n",
" uri: 'http://localhost:1338/app',\n",
" body: {\n",
" name: cliArguments[0],\n",
" token: config.token\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" uri: 'http://studio.strapi.io/app',\n"
],
"file_path": "bin/strapi-new.js",
"type": "replace",
"edit_start_line_idx": 108
} | 'use strict';
/**
* X-Response-Time hook
*/
module.exports = function (strapi) {
const hook = {
/**
* Default options
*/
defaults: {
responseTime: true
},
/**
* Initialize the hook
*/
initialize: function (cb) {
if (strapi.config.responseTime === true) {
strapi.app.use(strapi.middlewares.responseTime());
}
cb();
}
};
return hook;
};
| lib/configuration/hooks/responseTime/index.js | 0 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.00017242171452380717,
0.00016788471839390695,
0.0001617344532860443,
0.00016869134560693055,
0.000003867098257614998
] |
{
"id": 6,
"code_window": [
" method: 'POST',\n",
" preambleCRLF: true,\n",
" postambleCRLF: true,\n",
" json: true,\n",
" uri: 'http://localhost:1338/app',\n",
" body: {\n",
" name: cliArguments[0],\n",
" token: config.token\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" uri: 'http://studio.strapi.io/app',\n"
],
"file_path": "bin/strapi-new.js",
"type": "replace",
"edit_start_line_idx": 108
} | ############################
# OS X
############################
.DS_Store
.AppleDouble
.LSOverride
Icon
.Spotlight-V100
.Trashes
._*
############################
# Linux
############################
*~
############################
# Windows
############################
Thumbs.db
ehthumbs.db
Desktop.ini
$RECYCLE.BIN/
*.cab
*.msi
*.msm
*.msp
############################
# Packages
############################
*.7z
*.csv
*.dat
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
*.com
*.class
*.dll
*.exe
*.o
*.seed
*.so
*.swo
*.swp
*.swn
*.swm
*.out
*.pid
############################
# Logs and databases
############################
.tmp
*.log
*.sql
*.sqlite
############################
# Misc.
############################
*#
.idea
nbproject
############################
# Node.js
############################
lib-cov
lcov.info
pids
logs
results
build
node_modules
.node_history
############################
# Tests
############################
testApp
coverage
| .gitignore | 0 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.00017247910727746785,
0.00016822740144561976,
0.00016301953291986138,
0.00016869955288711935,
0.0000027093776679976145
] |
{
"id": 6,
"code_window": [
" method: 'POST',\n",
" preambleCRLF: true,\n",
" postambleCRLF: true,\n",
" json: true,\n",
" uri: 'http://localhost:1338/app',\n",
" body: {\n",
" name: cliArguments[0],\n",
" token: config.token\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" uri: 'http://studio.strapi.io/app',\n"
],
"file_path": "bin/strapi-new.js",
"type": "replace",
"edit_start_line_idx": 108
} | 'use strict';
/**
* `Strapi.prototype.stop()`
*
* The inverse of `start()`, this method
* shuts down all attached servers.
*
* It also unbinds listeners and terminates child processes.
*
* @api public
*/
module.exports = function stop() {
// Flag `this._exiting` as soon as the application has begun to shutdown.
// This may be used by hooks and other parts of core.
this._exiting = true;
// Exit the REPL.
process.exit(0);
// Emit a `stop` event.
this.emit('stop');
};
| lib/stop.js | 0 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.0005852788453921676,
0.000306075147818774,
0.00016405760834459215,
0.00016888898971956223,
0.0001974366750800982
] |
{
"id": 7,
"code_window": [
" templates: 'templates'\n",
" },\n",
"\n",
" // Add the Studio URL.\n",
" studio: {\n",
" url: 'http://localhost:1338'\n",
" },\n",
"\n",
" // Start off needed empty objects and strings.\n",
" routes: {},\n",
" frontendUrl: ''\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" url: 'http://studio.strapi.io'\n"
],
"file_path": "lib/configuration/index.js",
"type": "replace",
"edit_start_line_idx": 85
} | #!/usr/bin/env node
'use strict';
/**
* Module dependencies
*/
// Node.js core.
const fs = require('fs');
const path = require('path');
const dns = require('dns');
// Public node modules.
const _ = require('lodash');
const request = require('request');
const winston = require('winston');
// Logger.
const logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({
level: 'debug',
colorize: 'level'
})
]
});
/**
* `$ strapi link`
*
* Link an existing application to the Strapi Studio
*/
module.exports = function () {
const HOME = process.env[process.platform === 'win32' ? 'USERPROFILE' : 'HOME'];
const pathToPackageJSON = path.resolve(process.cwd(), 'package.json');
const pathToStudioJSON = path.resolve(process.cwd(), 'config', 'studio.json');
const appPkg = JSON.parse(fs.readFileSync(pathToPackageJSON));
const studioConfig = JSON.parse(fs.readFileSync(pathToStudioJSON));
let invalidPackageJSON;
// First, check if we are in a Strapi project.
try {
require(pathToPackageJSON);
} catch (err) {
invalidPackageJSON = true;
}
if (invalidPackageJSON) {
logger.error('This command can only be used inside an Strapi project.');
process.exit(1);
}
// Check the internet connectivity.
dns.resolve('google.com', function (noInternetAccess) {
if (noInternetAccess) {
logger.warn('No internet access...');
logger.warn('Your application can not be linked to the Strapi Studio.');
process.exit(1);
}
// Read the `.strapirc` configuration file at $HOME.
fs.readFile(path.resolve(HOME, '.strapirc'), 'utf8', function (noRcFile, config) {
if (noRcFile) {
logger.warn('You do not have a `.strapirc` file at `' + HOME + '`.');
logger.warn('First, you need to create an account on http://localhost:1338/');
logger.warn('Then, execute `$ strapi login` to start the experience.');
process.exit(1);
}
// Parse the config file.
config = JSON.parse(config);
// Make sure the developer is logged in.
if (_.isEmpty(config.email) || _.isEmpty(config.token)) {
logger.error('You are not logged in.');
logger.error('Execute `$ strapi login` to start the experience.');
process.exit(1);
}
// Create a new application on the Strapi Studio.
request({
method: 'POST',
preambleCRLF: true,
postambleCRLF: true,
json: true,
uri: 'http://localhost:1338/app',
body: {
name: appPkg.name,
token: config.token,
appToDelete: studioConfig.studio.appId
}
},
// Callback.
function (err, res) {
// Log and exit if no internet access.
if (err) {
logger.warn('Impossible to access the Strapi Studio.');
logger.warn('Your application is not linked to the Strapi Studio.');
process.exit(1);
}
// Parse the RC file.
const currentJSON = JSON.parse(fs.readFileSync(path.resolve('config', 'studio.json'), 'utf8'));
const newJSON = JSON.stringify(_.merge(currentJSON, {studio: {appId: res.body.appId}}), null, ' ');
// Write the new `./config/studio.json` with credentials.
fs.writeFile(path.resolve('config', 'studio.json'), newJSON, 'utf8', function (err) {
if (err) {
logger.error('Impossible to write the `appId`.');
process.exit(1);
} else {
logger.info('Your application has successfully been linked to the Studio.');
}
process.exit(0);
});
});
});
});
};
| bin/strapi-link.js | 1 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.01877625845372677,
0.0024054506793618202,
0.00016544329992029816,
0.0001707607152638957,
0.005345168989151716
] |
{
"id": 7,
"code_window": [
" templates: 'templates'\n",
" },\n",
"\n",
" // Add the Studio URL.\n",
" studio: {\n",
" url: 'http://localhost:1338'\n",
" },\n",
"\n",
" // Start off needed empty objects and strings.\n",
" routes: {},\n",
" frontendUrl: ''\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" url: 'http://studio.strapi.io'\n"
],
"file_path": "lib/configuration/index.js",
"type": "replace",
"edit_start_line_idx": 85
} | 'use strict';
const Koa = require('../..').server;
describe('app.inspect()', function () {
it('should work', function () {
const app = new Koa();
const util = require('util');
util.inspect(app);
});
});
| test/application/inspect.js | 0 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.00017370771092828363,
0.00017274603305850178,
0.00017178435518871993,
0.00017274603305850178,
9.616778697818518e-7
] |
{
"id": 7,
"code_window": [
" templates: 'templates'\n",
" },\n",
"\n",
" // Add the Studio URL.\n",
" studio: {\n",
" url: 'http://localhost:1338'\n",
" },\n",
"\n",
" // Start off needed empty objects and strings.\n",
" routes: {},\n",
" frontendUrl: ''\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" url: 'http://studio.strapi.io'\n"
],
"file_path": "lib/configuration/index.js",
"type": "replace",
"edit_start_line_idx": 85
} | 'use strict';
/**
* Module dependencies
*/
// Locale helpers.
const isManyToOneAssociation = require('./isManyToOneAssociation');
const isOneToOneAssociation = require('./isOneToOneAssociation');
const isOneWayAssociation = require('./isOneWayAssociation');
const isOneToManyAssociation = require('./isOneToManyAssociation');
const isManyToManyAssociation = require('./isManyToManyAssociation');
/**
* Helper which returns the association type of the attribute
*
* @param {Object} currentModel
* @param {Object} association
*
* @return {boolean}
*/
module.exports = {
getAssociationType: function (currentModel, association) {
let associationType;
if (association.type === 'model') {
if (isManyToOneAssociation(currentModel, association)) {
associationType = 'manyToOne';
} else if (isOneToOneAssociation(currentModel, association)) {
associationType = 'oneToOne';
} else if (isOneWayAssociation(currentModel, association)) {
associationType = 'oneWay';
} else {
associationType = 'unknown';
}
} else if (association.type === 'collection') {
if (isOneToManyAssociation(currentModel, association)) {
associationType = 'oneToMany';
} else if (isManyToManyAssociation(currentModel, association)) {
associationType = 'manyToMany';
} else {
associationType = 'unknown';
}
}
return associationType;
}
};
| lib/configuration/hooks/waterline/helpers/index.js | 0 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.00017392846348229796,
0.00017083193233702332,
0.00016706340829841793,
0.00017133497749455273,
0.0000023186264570540516
] |
{
"id": 7,
"code_window": [
" templates: 'templates'\n",
" },\n",
"\n",
" // Add the Studio URL.\n",
" studio: {\n",
" url: 'http://localhost:1338'\n",
" },\n",
"\n",
" // Start off needed empty objects and strings.\n",
" routes: {},\n",
" frontendUrl: ''\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" url: 'http://studio.strapi.io'\n"
],
"file_path": "lib/configuration/index.js",
"type": "replace",
"edit_start_line_idx": 85
} | 'use strict';
const context = require('../helpers/context');
describe('req.stale', function () {
it('should be the inverse of req.fresh', function () {
const ctx = context();
ctx.status = 200;
ctx.method = 'GET';
ctx.req.headers['if-none-match'] = '"123"';
ctx.set('ETag', '"123"');
ctx.fresh.should.be.true;
ctx.stale.should.be.false;
});
});
| test/request/stale.js | 0 | https://github.com/strapi/strapi/commit/382cc2428e2e4a1bff1811d28ab13ed421faccf8 | [
0.00017315091099590063,
0.0001726998743833974,
0.00017224883777089417,
0.0001726998743833974,
4.5103661250323057e-7
] |
{
"id": 0,
"code_window": [
"import { StorybookLogo, WithTooltip, TooltipLinkList, Button, Icons } from '@storybook/components';\n",
"\n",
"const BrandArea = styled.div(({ theme }) => ({\n",
" fontSize: theme.typography.size.s2,\n",
" fontWeight: theme.typography.weight.bold,\n",
"}));\n",
"\n",
"const Logo = styled(StorybookLogo)({\n",
" width: 'auto',\n",
" height: 22,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" '> *': {\n",
" maxHeight: 32,\n",
" maxWidth: 200,\n",
" height: 'auto',\n",
" width: 'auto',\n",
" display: 'block',\n",
" },\n"
],
"file_path": "lib/ui/src/components/sidebar/SidebarHeading.js",
"type": "add",
"edit_start_line_idx": 10
} | import React from 'react';
import { themes, ThemeProvider } from '@storybook/theming';
import { action } from '@storybook/addon-actions';
import SidebarHeading from './SidebarHeading';
const { light: theme } = themes;
export default {
component: SidebarHeading,
title: 'UI|Sidebar/SidebarHeading',
};
const menuItems = [
{ title: 'Menu Item 1', onClick: action('onActivateMenuItem') },
{ title: 'Menu Item 2', onClick: action('onActivateMenuItem') },
{ title: 'Menu Item 3', onClick: action('onActivateMenuItem') },
];
export const simple = () => <SidebarHeading menu={menuItems} />;
simple.storyData = { menu: menuItems };
export const menuHighlighted = () => <SidebarHeading menuHighlighted menu={menuItems} />;
export const customBrand = () => (
<ThemeProvider theme={{ ...theme, brand: 'custom brand' }}>
<SidebarHeading menu={menuItems} />
</ThemeProvider>
);
| lib/ui/src/components/sidebar/SidebarHeading.stories.js | 1 | https://github.com/storybookjs/storybook/commit/0cb31964036ecbbf9b99023ab8bb5e03d3d82d2b | [
0.0008628556388430297,
0.0004220836271997541,
0.0001747913338476792,
0.00022860387980472296,
0.0003124461800325662
] |
{
"id": 0,
"code_window": [
"import { StorybookLogo, WithTooltip, TooltipLinkList, Button, Icons } from '@storybook/components';\n",
"\n",
"const BrandArea = styled.div(({ theme }) => ({\n",
" fontSize: theme.typography.size.s2,\n",
" fontWeight: theme.typography.weight.bold,\n",
"}));\n",
"\n",
"const Logo = styled(StorybookLogo)({\n",
" width: 'auto',\n",
" height: 22,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" '> *': {\n",
" maxHeight: 32,\n",
" maxWidth: 200,\n",
" height: 'auto',\n",
" width: 'auto',\n",
" display: 'block',\n",
" },\n"
],
"file_path": "lib/ui/src/components/sidebar/SidebarHeading.js",
"type": "add",
"edit_start_line_idx": 10
} | import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import Panel from './panel';
export const panels = {
test1: {
title: 'Test 1',
// eslint-disable-next-line react/prop-types
render: ({ active, key }) =>
active ? (
<div id="test1" key={key}>
TEST 1
</div>
) : null,
},
test2: {
title: 'Test 2',
// eslint-disable-next-line react/prop-types
render: ({ active, key }) =>
active ? (
<div id="test2" key={key}>
TEST 2
</div>
) : null,
},
};
const onSelect = action('onSelect');
const toggleVisibility = action('toggleVisibility');
const togglePosition = action('togglePosition');
storiesOf('UI|Panel', module)
.addDecorator(storyFn => (
<div
style={{
position: 'relative',
width: '800px',
height: '300px',
margin: '1rem auto',
padding: '20px',
background: 'papayawhip',
}}
>
{storyFn()}
</div>
))
.add('default', () => (
<Panel
panels={panels}
actions={{ onSelect, toggleVisibility, togglePosition }}
selectedPanel="test2"
/>
))
.add('no panels', () => (
<Panel panels={{}} actions={{ onSelect, toggleVisibility, togglePosition }} />
));
| lib/ui/src/components/panel/panel.stories.js | 0 | https://github.com/storybookjs/storybook/commit/0cb31964036ecbbf9b99023ab8bb5e03d3d82d2b | [
0.00017751258565112948,
0.00017226923955604434,
0.0001662128634052351,
0.00017296031001023948,
0.000004325042027630843
] |
{
"id": 0,
"code_window": [
"import { StorybookLogo, WithTooltip, TooltipLinkList, Button, Icons } from '@storybook/components';\n",
"\n",
"const BrandArea = styled.div(({ theme }) => ({\n",
" fontSize: theme.typography.size.s2,\n",
" fontWeight: theme.typography.weight.bold,\n",
"}));\n",
"\n",
"const Logo = styled(StorybookLogo)({\n",
" width: 'auto',\n",
" height: 22,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" '> *': {\n",
" maxHeight: 32,\n",
" maxWidth: 200,\n",
" height: 'auto',\n",
" width: 'auto',\n",
" display: 'block',\n",
" },\n"
],
"file_path": "lib/ui/src/components/sidebar/SidebarHeading.js",
"type": "add",
"edit_start_line_idx": 10
} | {
"name": "ember-example",
"version": "5.0.0-beta.1",
"private": true,
"scripts": {
"build": "ember build",
"build-storybook": "yarn build && cp -r public/* dist && build-storybook -s dist",
"dev": "ember serve",
"storybook": "yarn build && start-storybook -p 9009 -s dist",
"storybook:dev": "yarn dev & start-storybook -p 9009 -s dist"
},
"dependencies": {
"ember-template-compiler": "^1.9.0-alpha"
},
"devDependencies": {
"@babel/core": "^7.2.2",
"@storybook/addon-a11y": "5.0.0-beta.1",
"@storybook/addon-actions": "5.0.0-beta.1",
"@storybook/addon-backgrounds": "5.0.0-beta.1",
"@storybook/addon-centered": "5.0.0-beta.1",
"@storybook/addon-knobs": "5.0.0-beta.1",
"@storybook/addon-links": "5.0.0-beta.1",
"@storybook/addon-notes": "5.0.0-beta.1",
"@storybook/addon-options": "5.0.0-beta.1",
"@storybook/addon-storysource": "5.0.0-beta.1",
"@storybook/addon-viewport": "5.0.0-beta.1",
"@storybook/addons": "5.0.0-beta.1",
"@storybook/ember": "5.0.0-beta.1",
"babel-loader": "^8",
"broccoli-asset-rev": "^3.0.0",
"cross-env": "^5.2.0",
"ember-ajax": "^4.0.2",
"ember-cli": "~3.7.1",
"ember-cli-app-version": "^3.0.0",
"ember-cli-babel": "^7.4.1",
"ember-cli-htmlbars": "^3.0.1",
"ember-cli-htmlbars-inline-precompile": "^2.1.0",
"ember-cli-inject-live-reload": "^2.0.1",
"ember-cli-shims": "^1.2.0",
"ember-cli-sri": "^2.1.0",
"ember-cli-storybook": "^0.0.1",
"ember-cli-uglify": "^2.0.0",
"ember-load-initializers": "^2.0.0",
"ember-resolver": "^5.0.1",
"ember-source": "~3.7.3",
"loader.js": "^4.2.3",
"webpack": "^4.29.0",
"webpack-cli": "^3.2.3"
},
"engines": {
"node": "^4.5 || 6.* || >= 7.*"
}
}
| examples/ember-cli/package.json | 0 | https://github.com/storybookjs/storybook/commit/0cb31964036ecbbf9b99023ab8bb5e03d3d82d2b | [
0.00017331923299934715,
0.0001723104069242254,
0.00017182316514663398,
0.00017213843239005655,
5.064018750999821e-7
] |
{
"id": 0,
"code_window": [
"import { StorybookLogo, WithTooltip, TooltipLinkList, Button, Icons } from '@storybook/components';\n",
"\n",
"const BrandArea = styled.div(({ theme }) => ({\n",
" fontSize: theme.typography.size.s2,\n",
" fontWeight: theme.typography.weight.bold,\n",
"}));\n",
"\n",
"const Logo = styled(StorybookLogo)({\n",
" width: 'auto',\n",
" height: 22,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" '> *': {\n",
" maxHeight: 32,\n",
" maxWidth: 200,\n",
" height: 'auto',\n",
" width: 'auto',\n",
" display: 'block',\n",
" },\n"
],
"file_path": "lib/ui/src/components/sidebar/SidebarHeading.js",
"type": "add",
"edit_start_line_idx": 10
} | package OpenSourceProjects_Storybook.vcsRoots
import jetbrains.buildServer.configs.kotlin.v2017_2.*
import jetbrains.buildServer.configs.kotlin.v2017_2.vcs.GitVcsRoot
object OpenSourceProjects_Storybook_HttpsGithubComStorybooksStorybookRefsHeadsMaster : GitVcsRoot({
uuid = "cec03c4b-d52c-42a0-8e9e-53bde85d6b33"
id = "OpenSourceProjects_Storybook_HttpsGithubComStorybooksStorybookRefsHeadsMaster"
name = "Main root"
url = "[email protected]:storybooks/storybook.git"
branch = "refs/heads/next"
branchSpec = """
+:refs/(pull/*)/head
+:refs/heads/*
""".trimIndent()
authMethod = uploadedKey {
userName = "git"
uploadedKey = "Storybook bot"
}
})
| .teamcity/OpenSourceProjects_Storybook/vcsRoots/OpenSourceProjects_Storybook_HttpsGithubComStorybooksStorybookRefsHeadsMaster.kt | 0 | https://github.com/storybookjs/storybook/commit/0cb31964036ecbbf9b99023ab8bb5e03d3d82d2b | [
0.0001706562179606408,
0.00016969686839729548,
0.0001686870091361925,
0.00016974739264696836,
8.047193773563777e-7
] |
{
"id": 1,
"code_window": [
"\n",
"import SidebarHeading from './SidebarHeading';\n",
"\n",
"const { light: theme } = themes;\n",
"\n",
"export default {\n",
" component: SidebarHeading,\n",
" title: 'UI|Sidebar/SidebarHeading',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"const customizedBrand = `\n",
"<svg width=\"64px\" height=\"64px\" viewBox=\"0 0 64 64\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n",
" <a xlink:href=\"https://storybook.js.org\">\n",
" <g id=\"Artboard\" stroke=\"none\" stroke-width=\"1\" fill=\"none\" fill-rule=\"evenodd\">\n",
" <path d=\"M8.04798541,58.7875918 L6.07908839,6.32540407 C6.01406344,4.5927838 7.34257463,3.12440831 9.07303814,3.01625434 L53.6958037,0.227331489 C55.457209,0.117243658 56.974354,1.45590096 57.0844418,3.21730626 C57.0885895,3.28366922 57.0906648,3.35014546 57.0906648,3.41663791 L57.0906648,60.5834697 C57.0906648,62.3483119 55.6599776,63.7789992 53.8951354,63.7789992 C53.847325,63.7789992 53.7995207,63.7779262 53.7517585,63.775781 L11.0978899,61.8600599 C9.43669044,61.7854501 8.11034889,60.4492961 8.04798541,58.7875918 Z\" id=\"path-1\" fill=\"#FF4785\" fill-rule=\"nonzero\"></path>\n",
" <path d=\"M35.9095005,24.1768792 C35.9095005,25.420127 44.2838488,24.8242707 45.4080313,23.9509748 C45.4080313,15.4847538 40.8652557,11.0358878 32.5466666,11.0358878 C24.2280775,11.0358878 19.5673077,15.553972 19.5673077,22.3311017 C19.5673077,34.1346028 35.4965208,34.3605071 35.4965208,40.7987804 C35.4965208,42.606015 34.6115646,43.6790606 32.6646607,43.6790606 C30.127786,43.6790606 29.1248356,42.3834613 29.2428298,37.9783269 C29.2428298,37.0226907 19.5673077,36.7247626 19.2723223,37.9783269 C18.5211693,48.6535354 25.1720308,51.7326752 32.7826549,51.7326752 C40.1572906,51.7326752 45.939005,47.8018145 45.939005,40.6858282 C45.939005,28.035186 29.7738035,28.3740425 29.7738035,22.1051974 C29.7738035,19.5637737 31.6617103,19.2249173 32.7826549,19.2249173 C33.9625966,19.2249173 36.0864917,19.4328883 35.9095005,24.1768792 Z\" id=\"path9_fill-path\" fill=\"#FFFFFF\" fill-rule=\"nonzero\"></path>\n",
" <path d=\"M44.0461638,0.830433986 L50.1874092,0.446606143 L50.443532,7.7810017 C50.4527198,8.04410717 50.2468789,8.26484453 49.9837734,8.27403237 C49.871115,8.27796649 49.7607078,8.24184808 49.6721567,8.17209069 L47.3089847,6.3104681 L44.5110468,8.43287463 C44.3012992,8.591981 44.0022839,8.55092814 43.8431776,8.34118051 C43.7762017,8.25288717 43.742082,8.14401677 43.7466857,8.03329059 L44.0461638,0.830433986 Z\" id=\"Path\" fill=\"#FFFFFF\"></path>\n",
" </g>\n",
" </a>\n",
"</svg>\n",
"`;\n",
"\n"
],
"file_path": "lib/ui/src/components/sidebar/SidebarHeading.stories.js",
"type": "add",
"edit_start_line_idx": 8
} | import React from 'react';
import { themes, ThemeProvider } from '@storybook/theming';
import { action } from '@storybook/addon-actions';
import SidebarHeading from './SidebarHeading';
const { light: theme } = themes;
export default {
component: SidebarHeading,
title: 'UI|Sidebar/SidebarHeading',
};
const menuItems = [
{ title: 'Menu Item 1', onClick: action('onActivateMenuItem') },
{ title: 'Menu Item 2', onClick: action('onActivateMenuItem') },
{ title: 'Menu Item 3', onClick: action('onActivateMenuItem') },
];
export const simple = () => <SidebarHeading menu={menuItems} />;
simple.storyData = { menu: menuItems };
export const menuHighlighted = () => <SidebarHeading menuHighlighted menu={menuItems} />;
export const customBrand = () => (
<ThemeProvider theme={{ ...theme, brand: 'custom brand' }}>
<SidebarHeading menu={menuItems} />
</ThemeProvider>
);
| lib/ui/src/components/sidebar/SidebarHeading.stories.js | 1 | https://github.com/storybookjs/storybook/commit/0cb31964036ecbbf9b99023ab8bb5e03d3d82d2b | [
0.9979152083396912,
0.6574130654335022,
0.0026931301690638065,
0.971630871295929,
0.4630812704563141
] |
{
"id": 1,
"code_window": [
"\n",
"import SidebarHeading from './SidebarHeading';\n",
"\n",
"const { light: theme } = themes;\n",
"\n",
"export default {\n",
" component: SidebarHeading,\n",
" title: 'UI|Sidebar/SidebarHeading',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"const customizedBrand = `\n",
"<svg width=\"64px\" height=\"64px\" viewBox=\"0 0 64 64\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n",
" <a xlink:href=\"https://storybook.js.org\">\n",
" <g id=\"Artboard\" stroke=\"none\" stroke-width=\"1\" fill=\"none\" fill-rule=\"evenodd\">\n",
" <path d=\"M8.04798541,58.7875918 L6.07908839,6.32540407 C6.01406344,4.5927838 7.34257463,3.12440831 9.07303814,3.01625434 L53.6958037,0.227331489 C55.457209,0.117243658 56.974354,1.45590096 57.0844418,3.21730626 C57.0885895,3.28366922 57.0906648,3.35014546 57.0906648,3.41663791 L57.0906648,60.5834697 C57.0906648,62.3483119 55.6599776,63.7789992 53.8951354,63.7789992 C53.847325,63.7789992 53.7995207,63.7779262 53.7517585,63.775781 L11.0978899,61.8600599 C9.43669044,61.7854501 8.11034889,60.4492961 8.04798541,58.7875918 Z\" id=\"path-1\" fill=\"#FF4785\" fill-rule=\"nonzero\"></path>\n",
" <path d=\"M35.9095005,24.1768792 C35.9095005,25.420127 44.2838488,24.8242707 45.4080313,23.9509748 C45.4080313,15.4847538 40.8652557,11.0358878 32.5466666,11.0358878 C24.2280775,11.0358878 19.5673077,15.553972 19.5673077,22.3311017 C19.5673077,34.1346028 35.4965208,34.3605071 35.4965208,40.7987804 C35.4965208,42.606015 34.6115646,43.6790606 32.6646607,43.6790606 C30.127786,43.6790606 29.1248356,42.3834613 29.2428298,37.9783269 C29.2428298,37.0226907 19.5673077,36.7247626 19.2723223,37.9783269 C18.5211693,48.6535354 25.1720308,51.7326752 32.7826549,51.7326752 C40.1572906,51.7326752 45.939005,47.8018145 45.939005,40.6858282 C45.939005,28.035186 29.7738035,28.3740425 29.7738035,22.1051974 C29.7738035,19.5637737 31.6617103,19.2249173 32.7826549,19.2249173 C33.9625966,19.2249173 36.0864917,19.4328883 35.9095005,24.1768792 Z\" id=\"path9_fill-path\" fill=\"#FFFFFF\" fill-rule=\"nonzero\"></path>\n",
" <path d=\"M44.0461638,0.830433986 L50.1874092,0.446606143 L50.443532,7.7810017 C50.4527198,8.04410717 50.2468789,8.26484453 49.9837734,8.27403237 C49.871115,8.27796649 49.7607078,8.24184808 49.6721567,8.17209069 L47.3089847,6.3104681 L44.5110468,8.43287463 C44.3012992,8.591981 44.0022839,8.55092814 43.8431776,8.34118051 C43.7762017,8.25288717 43.742082,8.14401677 43.7466857,8.03329059 L44.0461638,0.830433986 Z\" id=\"Path\" fill=\"#FFFFFF\"></path>\n",
" </g>\n",
" </a>\n",
"</svg>\n",
"`;\n",
"\n"
],
"file_path": "lib/ui/src/components/sidebar/SidebarHeading.stories.js",
"type": "add",
"edit_start_line_idx": 8
} | import { configure } from '@kadira/storybook';
function loadStories() {
require('../stories');
}
configure(loadStories, module);
| lib/cli/test/fixtures/update_package_organisations/.storybook/config.js | 0 | https://github.com/storybookjs/storybook/commit/0cb31964036ecbbf9b99023ab8bb5e03d3d82d2b | [
0.00017429121362511069,
0.00017429121362511069,
0.00017429121362511069,
0.00017429121362511069,
0
] |
{
"id": 1,
"code_window": [
"\n",
"import SidebarHeading from './SidebarHeading';\n",
"\n",
"const { light: theme } = themes;\n",
"\n",
"export default {\n",
" component: SidebarHeading,\n",
" title: 'UI|Sidebar/SidebarHeading',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"const customizedBrand = `\n",
"<svg width=\"64px\" height=\"64px\" viewBox=\"0 0 64 64\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n",
" <a xlink:href=\"https://storybook.js.org\">\n",
" <g id=\"Artboard\" stroke=\"none\" stroke-width=\"1\" fill=\"none\" fill-rule=\"evenodd\">\n",
" <path d=\"M8.04798541,58.7875918 L6.07908839,6.32540407 C6.01406344,4.5927838 7.34257463,3.12440831 9.07303814,3.01625434 L53.6958037,0.227331489 C55.457209,0.117243658 56.974354,1.45590096 57.0844418,3.21730626 C57.0885895,3.28366922 57.0906648,3.35014546 57.0906648,3.41663791 L57.0906648,60.5834697 C57.0906648,62.3483119 55.6599776,63.7789992 53.8951354,63.7789992 C53.847325,63.7789992 53.7995207,63.7779262 53.7517585,63.775781 L11.0978899,61.8600599 C9.43669044,61.7854501 8.11034889,60.4492961 8.04798541,58.7875918 Z\" id=\"path-1\" fill=\"#FF4785\" fill-rule=\"nonzero\"></path>\n",
" <path d=\"M35.9095005,24.1768792 C35.9095005,25.420127 44.2838488,24.8242707 45.4080313,23.9509748 C45.4080313,15.4847538 40.8652557,11.0358878 32.5466666,11.0358878 C24.2280775,11.0358878 19.5673077,15.553972 19.5673077,22.3311017 C19.5673077,34.1346028 35.4965208,34.3605071 35.4965208,40.7987804 C35.4965208,42.606015 34.6115646,43.6790606 32.6646607,43.6790606 C30.127786,43.6790606 29.1248356,42.3834613 29.2428298,37.9783269 C29.2428298,37.0226907 19.5673077,36.7247626 19.2723223,37.9783269 C18.5211693,48.6535354 25.1720308,51.7326752 32.7826549,51.7326752 C40.1572906,51.7326752 45.939005,47.8018145 45.939005,40.6858282 C45.939005,28.035186 29.7738035,28.3740425 29.7738035,22.1051974 C29.7738035,19.5637737 31.6617103,19.2249173 32.7826549,19.2249173 C33.9625966,19.2249173 36.0864917,19.4328883 35.9095005,24.1768792 Z\" id=\"path9_fill-path\" fill=\"#FFFFFF\" fill-rule=\"nonzero\"></path>\n",
" <path d=\"M44.0461638,0.830433986 L50.1874092,0.446606143 L50.443532,7.7810017 C50.4527198,8.04410717 50.2468789,8.26484453 49.9837734,8.27403237 C49.871115,8.27796649 49.7607078,8.24184808 49.6721567,8.17209069 L47.3089847,6.3104681 L44.5110468,8.43287463 C44.3012992,8.591981 44.0022839,8.55092814 43.8431776,8.34118051 C43.7762017,8.25288717 43.742082,8.14401677 43.7466857,8.03329059 L44.0461638,0.830433986 Z\" id=\"Path\" fill=\"#FFFFFF\"></path>\n",
" </g>\n",
" </a>\n",
"</svg>\n",
"`;\n",
"\n"
],
"file_path": "lib/ui/src/components/sidebar/SidebarHeading.stories.js",
"type": "add",
"edit_start_line_idx": 8
} | import { precompile } from 'ember-source/dist/ember-template-compiler';
export function babel(config) {
const babelConfigPlugins = config.plugins || [];
const extraPlugins = [
[require.resolve('babel-plugin-htmlbars-inline-precompile'), { precompile }],
[require.resolve('babel-plugin-ember-modules-api-polyfill')],
];
return {
...config,
plugins: [].concat(babelConfigPlugins, extraPlugins),
};
}
| app/ember/src/server/framework-preset-babel-ember.js | 0 | https://github.com/storybookjs/storybook/commit/0cb31964036ecbbf9b99023ab8bb5e03d3d82d2b | [
0.00017384093371219933,
0.00017318609752692282,
0.00017253126134164631,
0.00017318609752692282,
6.548361852765083e-7
] |
{
"id": 1,
"code_window": [
"\n",
"import SidebarHeading from './SidebarHeading';\n",
"\n",
"const { light: theme } = themes;\n",
"\n",
"export default {\n",
" component: SidebarHeading,\n",
" title: 'UI|Sidebar/SidebarHeading',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"const customizedBrand = `\n",
"<svg width=\"64px\" height=\"64px\" viewBox=\"0 0 64 64\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n",
" <a xlink:href=\"https://storybook.js.org\">\n",
" <g id=\"Artboard\" stroke=\"none\" stroke-width=\"1\" fill=\"none\" fill-rule=\"evenodd\">\n",
" <path d=\"M8.04798541,58.7875918 L6.07908839,6.32540407 C6.01406344,4.5927838 7.34257463,3.12440831 9.07303814,3.01625434 L53.6958037,0.227331489 C55.457209,0.117243658 56.974354,1.45590096 57.0844418,3.21730626 C57.0885895,3.28366922 57.0906648,3.35014546 57.0906648,3.41663791 L57.0906648,60.5834697 C57.0906648,62.3483119 55.6599776,63.7789992 53.8951354,63.7789992 C53.847325,63.7789992 53.7995207,63.7779262 53.7517585,63.775781 L11.0978899,61.8600599 C9.43669044,61.7854501 8.11034889,60.4492961 8.04798541,58.7875918 Z\" id=\"path-1\" fill=\"#FF4785\" fill-rule=\"nonzero\"></path>\n",
" <path d=\"M35.9095005,24.1768792 C35.9095005,25.420127 44.2838488,24.8242707 45.4080313,23.9509748 C45.4080313,15.4847538 40.8652557,11.0358878 32.5466666,11.0358878 C24.2280775,11.0358878 19.5673077,15.553972 19.5673077,22.3311017 C19.5673077,34.1346028 35.4965208,34.3605071 35.4965208,40.7987804 C35.4965208,42.606015 34.6115646,43.6790606 32.6646607,43.6790606 C30.127786,43.6790606 29.1248356,42.3834613 29.2428298,37.9783269 C29.2428298,37.0226907 19.5673077,36.7247626 19.2723223,37.9783269 C18.5211693,48.6535354 25.1720308,51.7326752 32.7826549,51.7326752 C40.1572906,51.7326752 45.939005,47.8018145 45.939005,40.6858282 C45.939005,28.035186 29.7738035,28.3740425 29.7738035,22.1051974 C29.7738035,19.5637737 31.6617103,19.2249173 32.7826549,19.2249173 C33.9625966,19.2249173 36.0864917,19.4328883 35.9095005,24.1768792 Z\" id=\"path9_fill-path\" fill=\"#FFFFFF\" fill-rule=\"nonzero\"></path>\n",
" <path d=\"M44.0461638,0.830433986 L50.1874092,0.446606143 L50.443532,7.7810017 C50.4527198,8.04410717 50.2468789,8.26484453 49.9837734,8.27403237 C49.871115,8.27796649 49.7607078,8.24184808 49.6721567,8.17209069 L47.3089847,6.3104681 L44.5110468,8.43287463 C44.3012992,8.591981 44.0022839,8.55092814 43.8431776,8.34118051 C43.7762017,8.25288717 43.742082,8.14401677 43.7466857,8.03329059 L44.0461638,0.830433986 Z\" id=\"Path\" fill=\"#FFFFFF\"></path>\n",
" </g>\n",
" </a>\n",
"</svg>\n",
"`;\n",
"\n"
],
"file_path": "lib/ui/src/components/sidebar/SidebarHeading.stories.js",
"type": "add",
"edit_start_line_idx": 8
} | server
browser
| lib/cli/test/fixtures/meteor/.meteor/platforms | 0 | https://github.com/storybookjs/storybook/commit/0cb31964036ecbbf9b99023ab8bb5e03d3d82d2b | [
0.00017652921087574214,
0.00017652921087574214,
0.00017652921087574214,
0.00017652921087574214,
0
] |
{
"id": 2,
"code_window": [
"simple.storyData = { menu: menuItems };\n",
"\n",
"export const menuHighlighted = () => <SidebarHeading menuHighlighted menu={menuItems} />;\n",
"\n",
"export const customBrand = () => (\n",
" <ThemeProvider theme={{ ...theme, brand: 'custom brand' }}>\n",
" <SidebarHeading menu={menuItems} />\n",
" </ThemeProvider>\n",
");"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" <ThemeProvider theme={{ ...theme, brand: customizedBrand }}>\n"
],
"file_path": "lib/ui/src/components/sidebar/SidebarHeading.stories.js",
"type": "replace",
"edit_start_line_idx": 24
} | import React from 'react';
import PropTypes from 'prop-types';
import { withState } from 'recompose';
import { styled, withTheme } from '@storybook/theming';
import { StorybookLogo, WithTooltip, TooltipLinkList, Button, Icons } from '@storybook/components';
const BrandArea = styled.div(({ theme }) => ({
fontSize: theme.typography.size.s2,
fontWeight: theme.typography.weight.bold,
}));
const Logo = styled(StorybookLogo)({
width: 'auto',
height: 22,
display: 'block',
});
const LogoLink = styled.a(
{
display: 'block',
color: 'inherit',
textDecoration: 'none',
},
({ theme }) => theme.animation.hoverable
);
const MenuButton = styled(Button)(props => ({
position: 'relative',
overflow: 'visible',
...(props.highlighted && {
'&:after': {
content: '""',
position: 'absolute',
top: 0,
right: 0,
width: 8,
height: 8,
borderRadius: 8,
background: `${props.theme.color.positive}`,
},
}),
}));
const Head = styled.div({
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
});
const Brand = withTheme(({ theme: { brand } }) =>
brand ? (
<BrandArea dangerouslySetInnerHTML={{ __html: brand }} />
) : (
<BrandArea>
<LogoLink href="./">
<Logo />
</LogoLink>
</BrandArea>
)
);
const SidebarHeading = withState('tooltipShown', 'onVisibilityChange', false)(
({ menuHighlighted, menu, tooltipShown, onVisibilityChange, ...props }) => (
<Head {...props}>
<Brand />
<WithTooltip
placement="top"
trigger="click"
tooltipShown={tooltipShown}
onVisibilityChange={onVisibilityChange}
tooltip={
<TooltipLinkList
links={menu.map(i => ({
...i,
onClick: (...args) => onVisibilityChange(false) || i.onClick(...args),
}))}
/>
}
closeOnClick
>
<MenuButton outline small containsIcon highlighted={menuHighlighted}>
<Icons icon="ellipsis" />
</MenuButton>
</WithTooltip>
</Head>
)
);
SidebarHeading.propTypes = {
menuHighlighted: PropTypes.bool,
menu: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
};
SidebarHeading.defaultProps = {
menuHighlighted: false,
};
export { SidebarHeading as default };
| lib/ui/src/components/sidebar/SidebarHeading.js | 1 | https://github.com/storybookjs/storybook/commit/0cb31964036ecbbf9b99023ab8bb5e03d3d82d2b | [
0.9990457892417908,
0.2999647259712219,
0.00017332914285361767,
0.0002247740630991757,
0.45688605308532715
] |
{
"id": 2,
"code_window": [
"simple.storyData = { menu: menuItems };\n",
"\n",
"export const menuHighlighted = () => <SidebarHeading menuHighlighted menu={menuItems} />;\n",
"\n",
"export const customBrand = () => (\n",
" <ThemeProvider theme={{ ...theme, brand: 'custom brand' }}>\n",
" <SidebarHeading menu={menuItems} />\n",
" </ThemeProvider>\n",
");"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" <ThemeProvider theme={{ ...theme, brand: customizedBrand }}>\n"
],
"file_path": "lib/ui/src/components/sidebar/SidebarHeading.stories.js",
"type": "replace",
"edit_start_line_idx": 24
} | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Storyshots App App 1`] = `
<div
id="app"
>
<img
src="./logo.png"
/>
<h1 />
<h2>
Essential Links
</h2>
<ul>
<li>
<a
href="https://vuejs.org"
target="_blank"
>
Core Docs
</a>
</li>
<li>
<a
href="https://forum.vuejs.org"
target="_blank"
>
Forum
</a>
</li>
<li>
<a
href="https://gitter.im/vuejs/vue"
target="_blank"
>
Gitter Chat
</a>
</li>
<li>
<a
href="https://twitter.com/vuejs"
target="_blank"
>
Twitter
</a>
</li>
</ul>
<h2>
Ecosystem
</h2>
<ul>
<li>
<a
href="http://router.vuejs.org/"
target="_blank"
>
vue-router
</a>
</li>
<li>
<a
href="http://vuex.vuejs.org/"
target="_blank"
>
vuex
</a>
</li>
<li>
<a
href="http://vue-loader.vuejs.org/"
target="_blank"
>
vue-loader
</a>
</li>
<li>
<a
href="https://github.com/vuejs/awesome-vue"
target="_blank"
>
awesome-vue
</a>
</li>
</ul>
</div>
`;
exports[`Storyshots Button rounded 1`] = `
<button
class="button rounded"
style="color: rgb(66, 185, 131); border-color: #42b983;"
>
A Button with rounded edges!
</button>
`;
exports[`Storyshots Button square 1`] = `
<button
class="button"
style="color: rgb(66, 185, 131); border-color: #42b983;"
>
A Button with square edges!
</button>
`;
exports[`Storyshots Welcome Welcome 1`] = `
<div
class="main"
>
<h1>
Welcome to Storybook for Vue
</h1>
<p>
This is a UI component dev environment for your vue app.
</p>
<p>
We've added some basic stories inside the
<code
class="code"
>
src/stories
</code>
directory.
<br />
A story is a single state of one or more UI components.
You can have as many stories as you want.
<br />
(Basically a story is like a visual test case.)
</p>
<p>
See these sample
<a
class="link"
>
stories
</a>
for a component called
<code
class="code"
>
Button
</code>
.
</p>
<p
style="text-align: center;"
>
<img
src="../logo.png"
/>
</p>
<p>
Just like that, you can add your own components as stories.
<br />
You can also edit those components and see changes right away.
<br />
(Try editing the
<code
class="code"
>
Button
</code>
component
located at
<code
class="code"
>
src/stories/Button.js
</code>
.)
</p>
<p>
Usually we create stories with smaller UI components in the app.
<br />
Have a look at the
<a
class="link"
href="https://storybook.js.org/basics/writing-stories"
target="_blank"
>
Writing Stories
</a>
section in our documentation.
</p>
<p
class="note"
>
<b>
NOTE:
</b>
<br />
Have a look at the
<code
class="code"
>
.storybook/webpack.config.js
</code>
to add webpack
loaders and plugins you are using in this project.
</p>
</div>
`;
| examples/vue-kitchen-sink/src/stories/__snapshots__/index.storyshot | 0 | https://github.com/storybookjs/storybook/commit/0cb31964036ecbbf9b99023ab8bb5e03d3d82d2b | [
0.0001781073515303433,
0.0001732329255901277,
0.00016465751104988158,
0.00017404925893060863,
0.0000037313520806492306
] |
{
"id": 2,
"code_window": [
"simple.storyData = { menu: menuItems };\n",
"\n",
"export const menuHighlighted = () => <SidebarHeading menuHighlighted menu={menuItems} />;\n",
"\n",
"export const customBrand = () => (\n",
" <ThemeProvider theme={{ ...theme, brand: 'custom brand' }}>\n",
" <SidebarHeading menu={menuItems} />\n",
" </ThemeProvider>\n",
");"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" <ThemeProvider theme={{ ...theme, brand: customizedBrand }}>\n"
],
"file_path": "lib/ui/src/components/sidebar/SidebarHeading.stories.js",
"type": "replace",
"edit_start_line_idx": 24
} | import addons, { makeDecorator } from '@storybook/addons';
import CoreEvents from '@storybook/core-events';
import deprecate from 'util-deprecate';
import Events from './constants';
let prevBackgrounds;
const subscription = () => () => {
prevBackgrounds = null;
addons.getChannel().emit(Events.UNSET);
};
export const withBackgrounds = makeDecorator({
name: 'withBackgrounds',
parameterName: 'backgrounds',
skipIfNoParametersOrOptions: true,
allowDeprecatedUsage: true,
wrapper: (getStory, context, { options, parameters }) => {
const data = parameters || options || [];
const backgrounds = Array.isArray(data) ? data : Object.values(data);
if (backgrounds.length === 0) {
return getStory(context);
}
if (prevBackgrounds !== backgrounds) {
addons.getChannel().emit(Events.SET, backgrounds);
prevBackgrounds = backgrounds;
}
addons.getChannel().emit(CoreEvents.REGISTER_SUBSCRIPTION, subscription);
return getStory(context);
},
});
export default deprecate(
withBackgrounds,
'The default export of @storybook/addon-backgrounds is deprecated, please `import { withBackgrounds }` instead'
);
if (module && module.hot && module.hot.decline) {
module.hot.decline();
}
| addons/backgrounds/src/index.js | 0 | https://github.com/storybookjs/storybook/commit/0cb31964036ecbbf9b99023ab8bb5e03d3d82d2b | [
0.0001769544032867998,
0.0001720857253530994,
0.0001656709355302155,
0.0001724572357488796,
0.0000036876324429613305
] |
{
"id": 2,
"code_window": [
"simple.storyData = { menu: menuItems };\n",
"\n",
"export const menuHighlighted = () => <SidebarHeading menuHighlighted menu={menuItems} />;\n",
"\n",
"export const customBrand = () => (\n",
" <ThemeProvider theme={{ ...theme, brand: 'custom brand' }}>\n",
" <SidebarHeading menu={menuItems} />\n",
" </ThemeProvider>\n",
");"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" <ThemeProvider theme={{ ...theme, brand: customizedBrand }}>\n"
],
"file_path": "lib/ui/src/components/sidebar/SidebarHeading.stories.js",
"type": "replace",
"edit_start_line_idx": 24
} | import path from 'path';
import fs from 'fs';
import { sync as spawnSync } from 'cross-spawn';
import hasYarn from './has_yarn';
import latestVersion from './latest_version';
import { commandLog, getPackageJson } from './helpers';
const logger = console;
export const storybookAddonScope = '@storybook/addon-';
const isAddon = async (name, npmOptions) => {
try {
await latestVersion(npmOptions, name);
return true;
} catch (e) {
return false;
}
};
const isStorybookAddon = async (name, npmOptions) =>
isAddon(`${storybookAddonScope}${name}`, npmOptions);
export const getPackageName = (addonName, isOfficialAddon) =>
isOfficialAddon ? storybookAddonScope + addonName : addonName;
export const getInstalledStorybookVersion = packageJson =>
packageJson.devDependencies[
// This only considers the first occurrence.
Object.keys(packageJson.devDependencies).find(devDep => /@storybook/.test(devDep))
] || false;
export const getPackageArg = (addonName, isOfficialAddon, packageJson) => {
if (isOfficialAddon) {
const addonNameNoTag = addonName.split('@')[0];
const installedStorybookVersion = getInstalledStorybookVersion(packageJson);
return installedStorybookVersion
? `${addonNameNoTag}@${getInstalledStorybookVersion(packageJson)}`
: addonName;
}
return addonName;
};
const installAddon = (addonName, npmOptions, isOfficialAddon) => {
const prepareDone = commandLog(`Preparing to install the ${addonName} Storybook addon`);
prepareDone();
logger.log();
let result;
const packageArg = getPackageArg(addonName, isOfficialAddon, getPackageJson());
if (npmOptions.useYarn) {
result = spawnSync('yarn', ['add', packageArg, '--dev'], {
stdio: 'inherit',
});
} else {
result = spawnSync('npm', ['install', packageArg, '--save-dev'], {
stdio: 'inherit',
});
}
logger.log();
const installDone = commandLog(`Installing the ${addonName} Storybook addon`);
if (result.status !== 0) {
installDone(
`Something went wrong installing the addon: "${getPackageName(addonName, isOfficialAddon)}"`
);
logger.log();
process.exit(1);
}
installDone();
};
export const addStorybookAddonToFile = (addonName, addonsFile, isOfficialAddon) => {
const addonNameNoTag = addonName.split('@')[0];
const alreadyRegistered = addonsFile.find(line => line.includes(`${addonNameNoTag}/register`));
if (alreadyRegistered) {
return addonsFile;
}
const latestImportIndex = addonsFile.reduce(
(prev, curr, currIndex) =>
curr.startsWith('import') && curr.includes('register') ? currIndex : prev,
-1
);
return [
...addonsFile.slice(0, latestImportIndex + 1),
`import '${getPackageName(addonNameNoTag, isOfficialAddon)}/register';`,
...addonsFile.slice(latestImportIndex + 1),
];
};
const registerAddon = (addonName, isOfficialAddon) => {
const registerDone = commandLog(`Registering the ${addonName} Storybook addon`);
const addonsFilePath = path.resolve('.storybook/addons.js');
const addonsFile = fs
.readFileSync(addonsFilePath)
.toString()
.split('\n');
fs.writeFileSync(
addonsFilePath,
addStorybookAddonToFile(addonName, addonsFile, isOfficialAddon).join('\n')
);
registerDone();
};
export default async function add(addonName, options) {
const useYarn = Boolean(options.useNpm !== true) && hasYarn();
const npmOptions = {
useYarn,
};
const addonCheckDone = commandLog(`Verifying that ${addonName} is an addon`);
const isOfficialAddon = await isStorybookAddon(addonName, npmOptions);
if (!isOfficialAddon) {
if (!(await isAddon(addonName, npmOptions))) {
addonCheckDone(`The provided package was not a Storybook addon: ${addonName}.`);
return;
}
}
addonCheckDone();
installAddon(addonName, npmOptions, isOfficialAddon);
registerAddon(addonName, isOfficialAddon);
}
| lib/cli/lib/add.js | 0 | https://github.com/storybookjs/storybook/commit/0cb31964036ecbbf9b99023ab8bb5e03d3d82d2b | [
0.00017855215992312878,
0.0001734507823130116,
0.00016676849918439984,
0.0001741012092679739,
0.0000041549592424416915
] |
{
"id": 0,
"code_window": [
" onChange={(cookies) =>\n",
" onSettingsChange({ jsonData: { ...dataSourceConfig.jsonData, keepCookies: cookies } })\n",
" }\n",
" width={20}\n",
" />\n",
" </div>\n",
" )}\n",
" </div>\n",
" </>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/grafana-ui/src/components/DataSourceSettings/DataSourceHttpSettings.tsx",
"type": "replace",
"edit_start_line_idx": 162
} | import React, { ChangeEvent, KeyboardEvent, PureComponent } from 'react';
import { css, cx } from 'emotion';
import { stylesFactory } from '../../themes/stylesFactory';
import { Button } from '../Button';
import { Input } from '../Forms/Legacy/Input/Input';
import { TagItem } from './TagItem';
interface Props {
tags?: string[];
width?: number;
onChange: (tags: string[]) => void;
}
interface State {
newTag: string;
tags: string[];
}
export class TagsInput extends PureComponent<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
newTag: '',
tags: this.props.tags || [],
};
}
onNameChange = (event: ChangeEvent<HTMLInputElement>) => {
this.setState({
newTag: event.target.value,
});
};
onRemove = (tagToRemove: string) => {
this.setState(
(prevState: State) => ({
...prevState,
tags: prevState.tags.filter((tag) => tagToRemove !== tag),
}),
() => this.onChange()
);
};
// Using React.MouseEvent to avoid tslint error
onAdd = (event: React.MouseEvent) => {
event.preventDefault();
if (this.state.newTag !== '') {
this.setNewTags();
}
};
onKeyboardAdd = (event: KeyboardEvent) => {
event.preventDefault();
if (event.key === 'Enter' && this.state.newTag !== '') {
this.setNewTags();
}
};
setNewTags = () => {
// We don't want to duplicate tags, clearing the input if
// the user is trying to add the same tag.
if (!this.state.tags.includes(this.state.newTag)) {
this.setState(
(prevState: State) => ({
...prevState,
tags: [...prevState.tags, prevState.newTag],
newTag: '',
}),
() => this.onChange()
);
} else {
this.setState({ newTag: '' });
}
};
onChange = () => {
this.props.onChange(this.state.tags);
};
render() {
const { tags, newTag } = this.state;
const getStyles = stylesFactory(() => ({
tagsCloudStyle: css`
display: flex;
justify-content: flex-start;
flex-wrap: wrap;
`,
addButtonStyle: css`
margin-left: 8px;
`,
}));
return (
<div className="width-20">
<div
className={cx(
['gf-form-inline'],
css`
margin-bottom: 4px;
`
)}
>
<Input placeholder="Add Name" onChange={this.onNameChange} value={newTag} onKeyUp={this.onKeyboardAdd} />
<Button className={getStyles().addButtonStyle} onClick={this.onAdd} variant="secondary" size="md">
Add
</Button>
</div>
<div className={getStyles().tagsCloudStyle}>
{tags &&
tags.map((tag: string, index: number) => {
return <TagItem key={`${tag}-${index}`} name={tag} onRemove={this.onRemove} />;
})}
</div>
</div>
);
}
}
| packages/grafana-ui/src/components/TagsInput/TagsInput.tsx | 1 | https://github.com/grafana/grafana/commit/7d4c51459f4abce8cc23b1dcfb24757e65b18120 | [
0.002649709116667509,
0.0006285440176725388,
0.00016287456674035639,
0.00020756878075189888,
0.0008557343971915543
] |
{
"id": 0,
"code_window": [
" onChange={(cookies) =>\n",
" onSettingsChange({ jsonData: { ...dataSourceConfig.jsonData, keepCookies: cookies } })\n",
" }\n",
" width={20}\n",
" />\n",
" </div>\n",
" )}\n",
" </div>\n",
" </>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/grafana-ui/src/components/DataSourceSettings/DataSourceHttpSettings.tsx",
"type": "replace",
"edit_start_line_idx": 162
} | <svg xmlns="http://www.w3.org/2000/svg" width="400" height="81" viewBox="0 0 400 81"><path d="M136.223 42.913c-.463 11.743-9.719 20.884-21.231 20.884-12.149 0-21.174-9.835-21.174-21.694 0-11.975 9.777-21.81 21.694-21.81 5.38 0 10.645 2.314 15.099 6.479l-3.471 4.281c-3.413-2.951-7.521-4.975-11.628-4.975-8.735 0-15.909 7.173-15.909 16.024 0 8.967 6.768 15.909 15.388 15.909 7.752 0 13.826-5.669 15.041-12.959h-17.586v-5.149h23.777v3.01zm20.187-2.834h-3.24a6.48 6.48 0 0 0-6.479 6.479V63.45h-5.785V34.525h4.744v2.43c1.562-1.562 4.05-2.43 6.826-2.43h6.248l-2.314 5.554zm31.526 23.371h-4.917v-3.645c-3.804 3.717-9.803 5.496-15.874 2.83-4.506-1.979-7.854-6.084-8.745-10.924-1.723-9.355 5.472-17.649 14.669-17.649 3.876 0 7.347 1.562 9.892 4.107v-3.644h4.975V63.45zm-5.917-12.382c1.365-5.879-3.086-11.221-8.892-11.221-5.033 0-9.082 4.107-9.082 9.083 0 5.627 4.947 9.982 10.701 9.002 3.545-.604 6.46-3.361 7.273-6.864zm17.578-18.163v1.62h9.198v5.091h-9.198V63.45h-5.727V33.079c0-6.364 4.57-10.124 10.297-10.124h6.942l-2.314 5.438h-4.628c-2.546 0-4.57 2.024-4.57 4.512zm39.857 30.545h-4.917v-3.645c-3.804 3.717-9.803 5.496-15.874 2.83-4.506-1.979-7.854-6.084-8.745-10.924-1.723-9.355 5.472-17.649 14.669-17.649 3.876 0 7.347 1.562 9.892 4.107v-3.644h4.975V63.45zm-5.917-12.382c1.365-5.879-3.086-11.221-8.892-11.221-5.033 0-9.082 4.107-9.082 9.083 0 5.627 4.947 9.982 10.701 9.002 3.545-.604 6.459-3.361 7.273-6.864zm36.818-4.742V63.45h-5.785V46.326c0-3.587-2.951-6.48-6.48-6.48-3.644 0-6.537 2.893-6.537 6.48V63.45h-5.785V34.525h4.801v2.487a11.743 11.743 0 0 1 7.752-2.95c6.712 0 12.034 5.496 12.034 12.264zm34.014 17.124h-4.917v-3.645c-3.804 3.717-9.803 5.496-15.874 2.83-4.506-1.979-7.854-6.084-8.745-10.924-1.723-9.355 5.472-17.649 14.669-17.649 3.876 0 7.347 1.562 9.892 4.107v-3.644h4.975V63.45zm-5.917-12.382c1.365-5.879-3.086-11.221-8.892-11.221-5.033 0-9.082 4.107-9.082 9.083 0 5.627 4.947 9.982 10.701 9.002 3.545-.604 6.46-3.361 7.273-6.864z" fill="#e6e7e8"/><linearGradient id="a" gradientUnits="userSpaceOnUse" x1="312.934" y1="89.824" x2="312.934" y2="23.688"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M315.624 60.907c0 1.43-1.27 2.793-3.09 2.581-.912-.106-1.738-.711-2.085-1.561-.788-1.934.834-3.739 2.456-3.739 1.62.001 2.719 1.215 2.719 2.719z" fill="url(#a)"/><linearGradient id="b" gradientUnits="userSpaceOnUse" x1="333.545" y1="89.824" x2="333.545" y2="23.688"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M345.636 46.484V63.51h-4.05V46.407c0-3.823-2.554-7.316-6.294-8.108-5.224-1.105-9.788 2.897-9.788 7.856V63.51h-4.049V34.585h3.587v3.066c2.861-2.86 7.191-4.251 11.589-3.153 5.387 1.345 9.005 6.432 9.005 11.986z" fill="url(#b)"/><linearGradient id="c" gradientUnits="userSpaceOnUse" x1="365.193" y1="89.824" x2="365.193" y2="23.688"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M354.924 50.379c.868 5.669 5.323 9.487 10.587 9.487 4.049 0 7.462-2.256 9.545-4.512l2.487 3.066c-3.355 3.876-7.868 5.554-12.033 5.554-8.793 0-14.868-7.347-14.868-15.446 0-8.331 6.421-14.405 14.463-14.405 8.33 0 14.636 6.595 14.636 16.256h-24.817zm20.422-3.414c-.81-5.091-5.149-8.967-10.24-8.967-4.686 0-9.314 3.297-10.182 8.967h20.422z" fill="url(#c)"/><linearGradient id="d" gradientUnits="userSpaceOnUse" x1="392.334" y1="89.824" x2="392.334" y2="23.688"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M398.843 63.511h-4.744c-5.38 0-9.43-3.992-9.43-9.43V25.387h4.05v9.199H400l-1.157 3.587h-10.124v15.909c0 2.959 2.421 5.38 5.38 5.38h4.744v4.049z" fill="url(#d)"/><linearGradient id="e" gradientUnits="userSpaceOnUse" x1="38.25" y1="77.691" x2="38.25" y2="-.557"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M36.916 72.962l-6.517 6.517a40.175 40.175 0 0 0 7.756 1.152l7.947-7.947a31.371 31.371 0 0 1-9.186.278z" fill="url(#e)"/><linearGradient id="f" gradientUnits="userSpaceOnUse" x1="28.542" y1="77.691" x2="28.542" y2="-.557"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M28.02 70.598l-5.832 5.833a40.003 40.003 0 0 0 6.368 2.539l6.341-6.341a32.435 32.435 0 0 1-6.877-2.031z" fill="url(#f)"/><linearGradient id="g" gradientUnits="userSpaceOnUse" x1="20.867" y1="77.691" x2="20.867" y2="-.557"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M20.914 66.444l-5.608 5.608a40.166 40.166 0 0 0 5.341 3.566l5.781-5.781a33.48 33.48 0 0 1-5.514-3.393z" fill="url(#g)"/><linearGradient id="h" gradientUnits="userSpaceOnUse" x1="14.578" y1="77.691" x2="14.578" y2="-.557"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M17.316 63.358a32.616 32.616 0 0 1-2.171-2.404l-5.574 5.574a40.37 40.37 0 0 0 4.446 4.462l5.569-5.569a33.777 33.777 0 0 1-2.27-2.063z" fill="url(#h)"/><linearGradient id="i" gradientUnits="userSpaceOnUse" x1="25.441" y1="77.691" x2="25.441" y2="-.557"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M23.322 23.401c-3.03 3.03-5.048 6.702-6.09 10.594L33.65 17.577c-3.97 1.084-7.448 2.944-10.328 5.824z" fill="url(#i)"/><linearGradient id="j" gradientUnits="userSpaceOnUse" x1="44.531" y1="77.691" x2="44.531" y2="-.557"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M58.977 28.382l-31.88 31.879a24.264 24.264 0 0 0 5.937 2.97l28.93-28.93a23.934 23.934 0 0 0-2.987-5.919z" fill="url(#j)"/><linearGradient id="k" gradientUnits="userSpaceOnUse" x1="30.273" y1="77.691" x2="30.273" y2="-.557"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M34.762 41.337L21.329 54.77a24.154 24.154 0 0 0 2.116 2.459 25.933 25.933 0 0 0 2.308 2.024L39.216 45.79l-4.454-4.453z" fill="url(#k)"/><linearGradient id="l" gradientUnits="userSpaceOnUse" x1="19.821" y1="77.691" x2="19.821" y2="-.557"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M17.193 17.272c3.561-3.561 8.031-6.117 13.111-7.609L39.642.325c-3.607.047-7.097.57-10.415 1.508L1.508 29.552A40.196 40.196 0 0 0 0 39.967l9.128-9.128a32.032 32.032 0 0 1 8.065-13.567z" fill="url(#l)"/><linearGradient id="m" gradientUnits="userSpaceOnUse" x1="9.554" y1="77.691" x2="9.554" y2="-.557"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M10.831 54.008l-5.866 5.866a40.231 40.231 0 0 0 3.549 5.358l5.628-5.628a32.395 32.395 0 0 1-3.311-5.596z" fill="url(#m)"/><linearGradient id="n" gradientUnits="userSpaceOnUse" x1="5.875" y1="77.691" x2="5.875" y2="-.557"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M8.205 45.374l-6.558 6.558a39.87 39.87 0 0 0 2.512 6.396l5.942-5.942c-.903-2.271-1.518-4.625-1.896-7.012z" fill="url(#n)"/><linearGradient id="o" gradientUnits="userSpaceOnUse" x1="41.198" y1="77.691" x2="41.198" y2="-.557"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M20.337 53.41l44.57-44.57a40.296 40.296 0 0 0-5.358-3.549l-42.06 42.06a23.847 23.847 0 0 0 2.848 6.059z" fill="url(#o)"/><linearGradient id="p" gradientUnits="userSpaceOnUse" x1="4.198" y1="77.691" x2="4.198" y2="-.557"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M8.364 33.956L.033 42.287c.117 2.675.499 5.28 1.114 7.794l6.768-6.768a33.036 33.036 0 0 1 .449-9.357z" fill="url(#p)"/><linearGradient id="q" gradientUnits="userSpaceOnUse" x1="41.589" y1="77.691" x2="41.589" y2="-.557"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M40.052 8.141l.02 3.015 9.684-9.684A40.155 40.155 0 0 0 41.962.358l-8.539 8.539a40.655 40.655 0 0 1 6.629-.756z" fill="url(#q)"/><linearGradient id="r" gradientUnits="userSpaceOnUse" x1="75.867" y1="77.691" x2="75.867" y2="-.557"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M71.428 47.357l8.877-8.877a40.175 40.175 0 0 0-1.152-7.756l-7.404 7.404a31.82 31.82 0 0 1-.321 9.229z" fill="url(#r)"/><linearGradient id="s" gradientUnits="userSpaceOnUse" x1="74.039" y1="77.691" x2="74.039" y2="-.557"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M71.471 36.055l7.174-7.173a39.864 39.864 0 0 0-2.539-6.369l-6.672 6.672a32.636 32.636 0 0 1 2.037 6.87z" fill="url(#s)"/><linearGradient id="t" gradientUnits="userSpaceOnUse" x1="65.308" y1="77.691" x2="65.308" y2="-.557"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M63.096 19.295c.425.46.8.946 1.195 1.422l6.374-6.374a40.545 40.545 0 0 0-4.462-4.446L59.95 16.15l3.146 3.145z" fill="url(#t)"/><linearGradient id="u" gradientUnits="userSpaceOnUse" x1="70.32" y1="77.691" x2="70.32" y2="-.557"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M68.714 27.552l6.579-6.579a40.264 40.264 0 0 0-3.566-5.341l-6.38 6.38a33.41 33.41 0 0 1 3.367 5.54z" fill="url(#u)"/><linearGradient id="v" gradientUnits="userSpaceOnUse" x1="66.036" y1="77.691" x2="66.036" y2="-.557"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M77.809 54.588L54.262 78.135a40.295 40.295 0 0 0 23.547-23.547z" fill="url(#v)"/><linearGradient id="w" gradientUnits="userSpaceOnUse" x1="37.212" y1="77.691" x2="37.212" y2="-.557"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M40.107 16.495c-1.188.086-2.33.241-3.451.429L16.648 36.932a24.133 24.133 0 0 0 .355 8.553l41-41a39.927 39.927 0 0 0-6.396-2.512l-11.52 11.519.02 3.003z" fill="url(#w)"/><linearGradient id="x" gradientUnits="userSpaceOnUse" x1="49.038" y1="77.691" x2="49.038" y2="-.557"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M62.504 36.114L34.855 63.763c2.759.696 5.587.878 8.363.545l19.849-19.849a23.081 23.081 0 0 0-.563-8.345z" fill="url(#x)"/><linearGradient id="y" gradientUnits="userSpaceOnUse" x1="54.332" y1="77.691" x2="54.332" y2="-.557"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M62.558 47.32l-16.45 16.45a22.72 22.72 0 0 0 10.493-5.989c3.036-3.037 5.002-6.654 5.957-10.461z" fill="url(#y)"/><linearGradient id="z" gradientUnits="userSpaceOnUse" x1="60.406" y1="77.691" x2="60.406" y2="-.557"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M80.348 40.789l-9.641 9.641a31.326 31.326 0 0 1-7.98 13.479c-3.981 3.981-8.644 6.641-13.555 8.055l-8.71 8.71a40.205 40.205 0 0 0 10.329-1.422l28.133-28.133a40.089 40.089 0 0 0 1.424-10.33z" fill="url(#z)"/><linearGradient id="A" gradientUnits="userSpaceOnUse" x1="14.191" y1="77.691" x2="14.191" y2="-.557"><stop offset="0" stop-color="#fff200"/><stop offset="1" stop-color="#f15a29"/></linearGradient><path d="M2.684 26.025L25.699 3.01A40.292 40.292 0 0 0 2.684 26.025z" fill="url(#A)"/></svg> | public/img/grafana_net_logo.svg | 0 | https://github.com/grafana/grafana/commit/7d4c51459f4abce8cc23b1dcfb24757e65b18120 | [
0.0004348907677922398,
0.0004348907677922398,
0.0004348907677922398,
0.0004348907677922398,
0
] |
{
"id": 0,
"code_window": [
" onChange={(cookies) =>\n",
" onSettingsChange({ jsonData: { ...dataSourceConfig.jsonData, keepCookies: cookies } })\n",
" }\n",
" width={20}\n",
" />\n",
" </div>\n",
" )}\n",
" </div>\n",
" </>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/grafana-ui/src/components/DataSourceSettings/DataSourceHttpSettings.tsx",
"type": "replace",
"edit_start_line_idx": 162
} | import React, { FC } from 'react';
import { css } from 'emotion';
import { FixedSizeList } from 'react-window';
import AutoSizer from 'react-virtualized-auto-sizer';
import { GrafanaTheme } from '@grafana/data';
import { stylesFactory, useTheme, Spinner } from '@grafana/ui';
import { selectors } from '@grafana/e2e-selectors';
import { DashboardSection, OnToggleChecked, SearchLayout } from '../types';
import { SEARCH_ITEM_HEIGHT, SEARCH_ITEM_MARGIN } from '../constants';
import { SearchItem } from './SearchItem';
import { SectionHeader } from './SectionHeader';
export interface Props {
editable?: boolean;
loading?: boolean;
onTagSelected: (name: string) => any;
onToggleChecked?: OnToggleChecked;
onToggleSection: (section: DashboardSection) => void;
results: DashboardSection[];
layout?: string;
}
const { section: sectionLabel, items: itemsLabel } = selectors.components.Search;
export const SearchResults: FC<Props> = ({
editable,
loading,
onTagSelected,
onToggleChecked,
onToggleSection,
results,
layout,
}) => {
const theme = useTheme();
const styles = getSectionStyles(theme);
const itemProps = { editable, onToggleChecked, onTagSelected };
const renderFolders = () => {
return (
<div className={styles.wrapper}>
{results.map((section) => {
return (
<div aria-label={sectionLabel} className={styles.section} key={section.id || section.title}>
<SectionHeader onSectionClick={onToggleSection} {...{ onToggleChecked, editable, section }} />
{section.expanded && (
<div aria-label={itemsLabel} className={styles.sectionItems}>
{section.items.map((item) => (
<SearchItem key={item.id} {...itemProps} item={item} />
))}
</div>
)}
</div>
);
})}
</div>
);
};
const renderDashboards = () => {
const items = results[0]?.items;
return (
<div className={styles.listModeWrapper}>
<AutoSizer disableWidth>
{({ height }) => (
<FixedSizeList
aria-label="Search items"
className={styles.wrapper}
innerElementType="ul"
itemSize={SEARCH_ITEM_HEIGHT + SEARCH_ITEM_MARGIN}
height={height}
itemCount={items.length}
width="100%"
>
{({ index, style }) => {
const item = items[index];
// The wrapper div is needed as the inner SearchItem has margin-bottom spacing
// And without this wrapper there is no room for that margin
return (
<div style={style}>
<SearchItem key={item.id} {...itemProps} item={item} />
</div>
);
}}
</FixedSizeList>
)}
</AutoSizer>
</div>
);
};
if (loading) {
return <Spinner className={styles.spinner} />;
} else if (!results || !results.length) {
return <div className={styles.noResults}>No dashboards matching your query were found.</div>;
}
return (
<div className={styles.resultsContainer}>
{layout === SearchLayout.Folders ? renderFolders() : renderDashboards()}
</div>
);
};
const getSectionStyles = stylesFactory((theme: GrafanaTheme) => {
const { md } = theme.spacing;
return {
wrapper: css`
display: flex;
flex-direction: column;
`,
section: css`
display: flex;
flex-direction: column;
background: ${theme.colors.panelBg};
border-bottom: solid 1px ${theme.colors.border2};
`,
sectionItems: css`
margin: 0 24px 0 32px;
`,
spinner: css`
display: flex;
justify-content: center;
align-items: center;
min-height: 100px;
`,
resultsContainer: css`
position: relative;
flex-grow: 10;
margin-bottom: ${md};
background: ${theme.colors.bg1};
border: 1px solid ${theme.colors.border1};
border-radius: 3px;
height: 100%;
`,
noResults: css`
padding: ${md};
background: ${theme.colors.bg2};
font-style: italic;
margin-top: ${theme.spacing.md};
`,
listModeWrapper: css`
position: relative;
height: 100%;
padding: ${md};
`,
};
});
| public/app/features/search/components/SearchResults.tsx | 0 | https://github.com/grafana/grafana/commit/7d4c51459f4abce8cc23b1dcfb24757e65b18120 | [
0.000723853416275233,
0.0002365313412155956,
0.00016645838331896812,
0.00017255263810511678,
0.00015973663539625704
] |
{
"id": 0,
"code_window": [
" onChange={(cookies) =>\n",
" onSettingsChange({ jsonData: { ...dataSourceConfig.jsonData, keepCookies: cookies } })\n",
" }\n",
" width={20}\n",
" />\n",
" </div>\n",
" )}\n",
" </div>\n",
" </>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/grafana-ui/src/components/DataSourceSettings/DataSourceHttpSettings.tsx",
"type": "replace",
"edit_start_line_idx": 162
} | import React, { HTMLProps } from 'react';
import { cx } from 'emotion';
import _ from 'lodash';
import { SelectableValue } from '@grafana/data';
import { SegmentSelect, useExpandableLabel, SegmentProps } from './';
import { getSegmentStyles } from './styles';
import { InlineLabel } from '../Forms/InlineLabel';
import { useStyles } from '../../themes';
export interface SegmentSyncProps<T> extends SegmentProps<T>, Omit<HTMLProps<HTMLDivElement>, 'value' | 'onChange'> {
value?: T | SelectableValue<T>;
onChange: (item: SelectableValue<T>) => void;
options: Array<SelectableValue<T>>;
}
export function Segment<T>({
options,
value,
onChange,
Component,
className,
allowCustomValue,
placeholder,
disabled,
...rest
}: React.PropsWithChildren<SegmentSyncProps<T>>) {
const [Label, width, expanded, setExpanded] = useExpandableLabel(false);
const styles = useStyles(getSegmentStyles);
if (!expanded) {
const label = _.isObject(value) ? value.label : value;
return (
<Label
disabled={disabled}
Component={
Component || (
<InlineLabel
className={cx(
styles.segment,
{
[styles.queryPlaceholder]: placeholder !== undefined && !value,
[styles.disabled]: disabled,
},
className
)}
>
{label || placeholder}
</InlineLabel>
)
}
/>
);
}
return (
<SegmentSelect
{...rest}
value={value && !_.isObject(value) ? { value } : value}
options={options}
width={width}
onClickOutside={() => setExpanded(false)}
allowCustomValue={allowCustomValue}
onChange={(item) => {
setExpanded(false);
onChange(item);
}}
/>
);
}
| packages/grafana-ui/src/components/Segment/Segment.tsx | 0 | https://github.com/grafana/grafana/commit/7d4c51459f4abce8cc23b1dcfb24757e65b18120 | [
0.005583273246884346,
0.0008503993158228695,
0.00016129891446325928,
0.0001665118325036019,
0.0017889725277200341
] |
{
"id": 1,
"code_window": [
"<Meta title=\"MDX|TagsInput\" component={TagsInput} />\n",
"\n",
"# TagsInput\n",
"\n",
"A set of an input field and a button next to it that allows the user to add new tags. The added tags are previewed under the input and can be removed there by clicking the \"X\" icon. You can customize the width of the input.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"### Props\n",
"<Props of={TagsInput} />"
],
"file_path": "packages/grafana-ui/src/components/TagsInput/TagsInput.mdx",
"type": "add",
"edit_start_line_idx": 8
} | import React, { ChangeEvent, KeyboardEvent, PureComponent } from 'react';
import { css, cx } from 'emotion';
import { stylesFactory } from '../../themes/stylesFactory';
import { Button } from '../Button';
import { Input } from '../Forms/Legacy/Input/Input';
import { TagItem } from './TagItem';
interface Props {
tags?: string[];
width?: number;
onChange: (tags: string[]) => void;
}
interface State {
newTag: string;
tags: string[];
}
export class TagsInput extends PureComponent<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
newTag: '',
tags: this.props.tags || [],
};
}
onNameChange = (event: ChangeEvent<HTMLInputElement>) => {
this.setState({
newTag: event.target.value,
});
};
onRemove = (tagToRemove: string) => {
this.setState(
(prevState: State) => ({
...prevState,
tags: prevState.tags.filter((tag) => tagToRemove !== tag),
}),
() => this.onChange()
);
};
// Using React.MouseEvent to avoid tslint error
onAdd = (event: React.MouseEvent) => {
event.preventDefault();
if (this.state.newTag !== '') {
this.setNewTags();
}
};
onKeyboardAdd = (event: KeyboardEvent) => {
event.preventDefault();
if (event.key === 'Enter' && this.state.newTag !== '') {
this.setNewTags();
}
};
setNewTags = () => {
// We don't want to duplicate tags, clearing the input if
// the user is trying to add the same tag.
if (!this.state.tags.includes(this.state.newTag)) {
this.setState(
(prevState: State) => ({
...prevState,
tags: [...prevState.tags, prevState.newTag],
newTag: '',
}),
() => this.onChange()
);
} else {
this.setState({ newTag: '' });
}
};
onChange = () => {
this.props.onChange(this.state.tags);
};
render() {
const { tags, newTag } = this.state;
const getStyles = stylesFactory(() => ({
tagsCloudStyle: css`
display: flex;
justify-content: flex-start;
flex-wrap: wrap;
`,
addButtonStyle: css`
margin-left: 8px;
`,
}));
return (
<div className="width-20">
<div
className={cx(
['gf-form-inline'],
css`
margin-bottom: 4px;
`
)}
>
<Input placeholder="Add Name" onChange={this.onNameChange} value={newTag} onKeyUp={this.onKeyboardAdd} />
<Button className={getStyles().addButtonStyle} onClick={this.onAdd} variant="secondary" size="md">
Add
</Button>
</div>
<div className={getStyles().tagsCloudStyle}>
{tags &&
tags.map((tag: string, index: number) => {
return <TagItem key={`${tag}-${index}`} name={tag} onRemove={this.onRemove} />;
})}
</div>
</div>
);
}
}
| packages/grafana-ui/src/components/TagsInput/TagsInput.tsx | 1 | https://github.com/grafana/grafana/commit/7d4c51459f4abce8cc23b1dcfb24757e65b18120 | [
0.005456980783492327,
0.001097609056159854,
0.00017242517787963152,
0.0006259988294914365,
0.0013929849956184626
] |
{
"id": 1,
"code_window": [
"<Meta title=\"MDX|TagsInput\" component={TagsInput} />\n",
"\n",
"# TagsInput\n",
"\n",
"A set of an input field and a button next to it that allows the user to add new tags. The added tags are previewed under the input and can be removed there by clicking the \"X\" icon. You can customize the width of the input.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"### Props\n",
"<Props of={TagsInput} />"
],
"file_path": "packages/grafana-ui/src/components/TagsInput/TagsInput.mdx",
"type": "add",
"edit_start_line_idx": 8
} | package tsdb
import (
"strconv"
"testing"
"time"
. "github.com/smartystreets/goconvey/convey"
)
func TestTimeRange(t *testing.T) {
Convey("Time range", t, func() {
now := time.Now()
Convey("Can parse 5m, now", func() {
tr := TimeRange{
From: "5m",
To: "now",
now: now,
}
Convey("5m ago ", func() {
fiveMinAgo, err := time.ParseDuration("-5m")
So(err, ShouldBeNil)
expected := now.Add(fiveMinAgo)
res, err := tr.ParseFrom()
So(err, ShouldBeNil)
So(res.Unix(), ShouldEqual, expected.Unix())
})
Convey("now ", func() {
res, err := tr.ParseTo()
So(err, ShouldBeNil)
So(res.Unix(), ShouldEqual, now.Unix())
})
})
Convey("Can parse 5h, now-10m", func() {
tr := TimeRange{
From: "5h",
To: "now-10m",
now: now,
}
Convey("5h ago ", func() {
fiveHourAgo, err := time.ParseDuration("-5h")
So(err, ShouldBeNil)
expected := now.Add(fiveHourAgo)
res, err := tr.ParseFrom()
So(err, ShouldBeNil)
So(res.Unix(), ShouldEqual, expected.Unix())
})
Convey("now-10m ", func() {
tenMinAgo, err := time.ParseDuration("-10m")
So(err, ShouldBeNil)
expected := now.Add(tenMinAgo)
res, err := tr.ParseTo()
So(err, ShouldBeNil)
So(res.Unix(), ShouldEqual, expected.Unix())
})
})
now, err := time.Parse(time.RFC3339Nano, "2020-03-26T15:12:56.000Z")
So(err, ShouldBeNil)
Convey("Can parse now-1M/M, now-1M/M", func() {
tr := TimeRange{
From: "now-1M/M",
To: "now-1M/M",
now: now,
}
Convey("from now-1M/M ", func() {
expected, err := time.Parse(time.RFC3339Nano, "2020-02-01T00:00:00.000Z")
So(err, ShouldBeNil)
res, err := tr.ParseFrom()
So(err, ShouldBeNil)
So(res, ShouldEqual, expected)
})
Convey("to now-1M/M ", func() {
expected, err := time.Parse(time.RFC3339Nano, "2020-02-29T23:59:59.999Z")
So(err, ShouldBeNil)
res, err := tr.ParseTo()
So(err, ShouldBeNil)
So(res, ShouldEqual, expected)
})
})
Convey("Can parse now-3d, now+3w", func() {
tr := TimeRange{
From: "now-3d",
To: "now+3w",
now: now,
}
Convey("now-3d ", func() {
expected, err := time.Parse(time.RFC3339Nano, "2020-03-23T15:12:56.000Z")
So(err, ShouldBeNil)
res, err := tr.ParseFrom()
So(err, ShouldBeNil)
So(res, ShouldEqual, expected)
})
Convey("now+3w ", func() {
expected, err := time.Parse(time.RFC3339Nano, "2020-04-16T15:12:56.000Z")
So(err, ShouldBeNil)
res, err := tr.ParseTo()
So(err, ShouldBeNil)
So(res, ShouldEqual, expected)
})
})
Convey("Can parse 1960-02-01T07:00:00.000Z, 1965-02-03T08:00:00.000Z", func() {
tr := TimeRange{
From: "1960-02-01T07:00:00.000Z",
To: "1965-02-03T08:00:00.000Z",
now: now,
}
Convey("1960-02-01T07:00:00.000Z ", func() {
expected, err := time.Parse(time.RFC3339Nano, "1960-02-01T07:00:00.000Z")
So(err, ShouldBeNil)
res, err := tr.ParseFrom()
So(err, ShouldBeNil)
So(res, ShouldEqual, expected)
})
Convey("1965-02-03T08:00:00.000Z ", func() {
expected, err := time.Parse(time.RFC3339Nano, "1965-02-03T08:00:00.000Z")
So(err, ShouldBeNil)
res, err := tr.ParseTo()
So(err, ShouldBeNil)
So(res, ShouldEqual, expected)
})
})
Convey("Can parse negative unix epochs", func() {
from := time.Date(1960, 2, 1, 7, 0, 0, 0, time.UTC)
to := time.Date(1965, 2, 3, 8, 0, 0, 0, time.UTC)
tr := NewTimeRange(strconv.FormatInt(from.UnixNano()/int64(time.Millisecond), 10), strconv.FormatInt(to.UnixNano()/int64(time.Millisecond), 10))
res, err := tr.ParseFrom()
So(err, ShouldBeNil)
So(res, ShouldEqual, from)
res, err = tr.ParseTo()
So(err, ShouldBeNil)
So(res, ShouldEqual, to)
})
Convey("can parse unix epochs", func() {
var err error
tr := TimeRange{
From: "1474973725473",
To: "1474975757930",
now: now,
}
res, err := tr.ParseFrom()
So(err, ShouldBeNil)
So(res.UnixNano()/int64(time.Millisecond), ShouldEqual, int64(1474973725473))
res, err = tr.ParseTo()
So(err, ShouldBeNil)
So(res.UnixNano()/int64(time.Millisecond), ShouldEqual, int64(1474975757930))
})
Convey("Cannot parse asdf", func() {
var err error
tr := TimeRange{
From: "asdf",
To: "asdf",
now: now,
}
_, err = tr.ParseFrom()
So(err, ShouldNotBeNil)
_, err = tr.ParseTo()
So(err, ShouldNotBeNil)
})
now, err = time.Parse(time.RFC3339Nano, "2020-07-26T15:12:56.000Z")
So(err, ShouldBeNil)
Convey("Can parse now-1M/M, now-1M/M with America/Chicago timezone", func() {
tr := TimeRange{
From: "now-1M/M",
To: "now-1M/M",
now: now,
}
location, err := time.LoadLocation("America/Chicago")
So(err, ShouldBeNil)
Convey("from now-1M/M ", func() {
expected, err := time.Parse(time.RFC3339Nano, "2020-06-01T00:00:00.000-05:00")
So(err, ShouldBeNil)
res, err := tr.ParseFromWithLocation(location)
So(err, ShouldBeNil)
So(res, ShouldEqual, expected)
})
Convey("to now-1M/M ", func() {
expected, err := time.Parse(time.RFC3339Nano, "2020-06-30T23:59:59.999-05:00")
So(err, ShouldBeNil)
res, err := tr.ParseToWithLocation(location)
So(err, ShouldBeNil)
So(res, ShouldEqual, expected)
})
})
Convey("Can parse now-3h, now+2h with America/Chicago timezone", func() {
tr := TimeRange{
From: "now-3h",
To: "now+2h",
now: now,
}
location, err := time.LoadLocation("America/Chicago")
So(err, ShouldBeNil)
Convey("now-3h ", func() {
expected, err := time.Parse(time.RFC3339Nano, "2020-07-26T07:12:56.000-05:00")
So(err, ShouldBeNil)
res, err := tr.ParseFromWithLocation(location)
So(err, ShouldBeNil)
So(res, ShouldEqual, expected)
})
Convey("now+2h ", func() {
expected, err := time.Parse(time.RFC3339Nano, "2020-07-26T12:12:56.000-05:00")
So(err, ShouldBeNil)
res, err := tr.ParseToWithLocation(location)
So(err, ShouldBeNil)
So(res, ShouldEqual, expected)
})
})
})
}
| pkg/tsdb/time_range_test.go | 0 | https://github.com/grafana/grafana/commit/7d4c51459f4abce8cc23b1dcfb24757e65b18120 | [
0.00017473050684202462,
0.00016875789151526988,
0.00016679584223311394,
0.00016860532923601568,
0.0000015183636605797801
] |
{
"id": 1,
"code_window": [
"<Meta title=\"MDX|TagsInput\" component={TagsInput} />\n",
"\n",
"# TagsInput\n",
"\n",
"A set of an input field and a button next to it that allows the user to add new tags. The added tags are previewed under the input and can be removed there by clicking the \"X\" icon. You can customize the width of the input.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"### Props\n",
"<Props of={TagsInput} />"
],
"file_path": "packages/grafana-ui/src/components/TagsInput/TagsInput.mdx",
"type": "add",
"edit_start_line_idx": 8
} | package cloudwatch
import (
"errors"
"math"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/tsdb"
)
// Parses the json queries and returns a requestQuery. The requestQuery has a 1 to 1 mapping to a query editor row
func (e *cloudWatchExecutor) parseQueries(queryContext *tsdb.TsdbQuery, startTime time.Time, endTime time.Time) (map[string][]*requestQuery, error) {
requestQueries := make(map[string][]*requestQuery)
for i, query := range queryContext.Queries {
queryType := query.Model.Get("type").MustString()
if queryType != "timeSeriesQuery" && queryType != "" {
continue
}
refID := query.RefId
query, err := parseRequestQuery(queryContext.Queries[i].Model, refID, startTime, endTime)
if err != nil {
return nil, &queryError{err: err, RefID: refID}
}
if _, exist := requestQueries[query.Region]; !exist {
requestQueries[query.Region] = make([]*requestQuery, 0)
}
requestQueries[query.Region] = append(requestQueries[query.Region], query)
}
return requestQueries, nil
}
func parseRequestQuery(model *simplejson.Json, refId string, startTime time.Time, endTime time.Time) (*requestQuery, error) {
plog.Debug("Parsing request query", "query", model)
reNumber := regexp.MustCompile(`^\d+$`)
region, err := model.Get("region").String()
if err != nil {
return nil, err
}
namespace, err := model.Get("namespace").String()
if err != nil {
return nil, err
}
metricName, err := model.Get("metricName").String()
if err != nil {
return nil, err
}
dimensions, err := parseDimensions(model)
if err != nil {
return nil, err
}
statistics, err := parseStatistics(model)
if err != nil {
return nil, err
}
p := model.Get("period").MustString("")
var period int
if strings.ToLower(p) == "auto" || p == "" {
deltaInSeconds := endTime.Sub(startTime).Seconds()
periods := []int{60, 300, 900, 3600, 21600, 86400}
datapoints := int(math.Ceil(deltaInSeconds / 2000))
period = periods[len(periods)-1]
for _, value := range periods {
if datapoints <= value {
period = value
break
}
}
} else {
if reNumber.Match([]byte(p)) {
period, err = strconv.Atoi(p)
if err != nil {
return nil, err
}
} else {
d, err := time.ParseDuration(p)
if err != nil {
return nil, err
}
period = int(d.Seconds())
}
}
id := model.Get("id").MustString("")
expression := model.Get("expression").MustString("")
alias := model.Get("alias").MustString()
returnData := !model.Get("hide").MustBool(false)
queryType := model.Get("type").MustString()
if queryType == "" {
// If no type is provided we assume we are called by alerting service, which requires to return data!
// Note, this is sort of a hack, but the official Grafana interfaces do not carry the information
// who (which service) called the TsdbQueryEndpoint.Query(...) function.
returnData = true
}
matchExact := model.Get("matchExact").MustBool(true)
return &requestQuery{
RefId: refId,
Region: region,
Namespace: namespace,
MetricName: metricName,
Dimensions: dimensions,
Statistics: aws.StringSlice(statistics),
Period: period,
Alias: alias,
Id: id,
Expression: expression,
ReturnData: returnData,
MatchExact: matchExact,
}, nil
}
func parseStatistics(model *simplejson.Json) ([]string, error) {
var statistics []string
for _, s := range model.Get("statistics").MustArray() {
statistics = append(statistics, s.(string))
}
return statistics, nil
}
func parseDimensions(model *simplejson.Json) (map[string][]string, error) {
parsedDimensions := make(map[string][]string)
for k, v := range model.Get("dimensions").MustMap() {
// This is for backwards compatibility. Before 6.5 dimensions values were stored as strings and not arrays
if value, ok := v.(string); ok {
parsedDimensions[k] = []string{value}
} else if values, ok := v.([]interface{}); ok {
for _, value := range values {
parsedDimensions[k] = append(parsedDimensions[k], value.(string))
}
} else {
return nil, errors.New("failed to parse dimensions")
}
}
sortedDimensions := sortDimensions(parsedDimensions)
return sortedDimensions, nil
}
func sortDimensions(dimensions map[string][]string) map[string][]string {
sortedDimensions := make(map[string][]string)
var keys []string
for k := range dimensions {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
sortedDimensions[k] = dimensions[k]
}
return sortedDimensions
}
| pkg/tsdb/cloudwatch/request_parser.go | 0 | https://github.com/grafana/grafana/commit/7d4c51459f4abce8cc23b1dcfb24757e65b18120 | [
0.00017225902411155403,
0.0001693660015007481,
0.00016689050244167447,
0.00016911701823119074,
0.0000015993508668543654
] |
{
"id": 1,
"code_window": [
"<Meta title=\"MDX|TagsInput\" component={TagsInput} />\n",
"\n",
"# TagsInput\n",
"\n",
"A set of an input field and a button next to it that allows the user to add new tags. The added tags are previewed under the input and can be removed there by clicking the \"X\" icon. You can customize the width of the input.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"### Props\n",
"<Props of={TagsInput} />"
],
"file_path": "packages/grafana-ui/src/components/TagsInput/TagsInput.mdx",
"type": "add",
"edit_start_line_idx": 8
} | import React, { FC } from 'react';
import { Button, Tooltip, Icon, Form, Input, Field, FieldSet } from '@grafana/ui';
import { User } from 'app/types';
import config from 'app/core/config';
import { ProfileUpdateFields } from 'app/core/utils/UserProvider';
export interface Props {
user: User;
isSavingUser: boolean;
updateProfile: (payload: ProfileUpdateFields) => void;
}
const { disableLoginForm } = config;
export const UserProfileEditForm: FC<Props> = ({ user, isSavingUser, updateProfile }) => {
const onSubmitProfileUpdate = (data: ProfileUpdateFields) => {
updateProfile(data);
};
return (
<Form onSubmit={onSubmitProfileUpdate} validateOn="onBlur">
{({ register, errors }) => {
return (
<FieldSet label="Edit Profile">
<Field label="Name" invalid={!!errors.name} error="Name is required">
<Input name="name" ref={register({ required: true })} placeholder="Name" defaultValue={user.name} />
</Field>
<Field label="Email" invalid={!!errors.email} error="Email is required" disabled={disableLoginForm}>
<Input
name="email"
ref={register({ required: true })}
placeholder="Email"
defaultValue={user.email}
suffix={<InputSuffix />}
/>
</Field>
<Field label="Username" disabled={disableLoginForm}>
<Input
name="login"
ref={register}
defaultValue={user.login}
placeholder="Username"
suffix={<InputSuffix />}
/>
</Field>
<div className="gf-form-button-row">
<Button variant="primary" disabled={isSavingUser}>
Save
</Button>
</div>
</FieldSet>
);
}}
</Form>
);
};
export default UserProfileEditForm;
const InputSuffix: FC = () => {
return disableLoginForm ? (
<Tooltip content="Login Details Locked - managed in another system.">
<Icon name="lock" />
</Tooltip>
) : null;
};
| public/app/features/profile/UserProfileEditForm.tsx | 0 | https://github.com/grafana/grafana/commit/7d4c51459f4abce8cc23b1dcfb24757e65b18120 | [
0.0010546020930632949,
0.00047670636558905244,
0.00016727893671486527,
0.00027266936376690865,
0.0003436226979829371
] |
{
"id": 2,
"code_window": [
"import { TagItem } from './TagItem';\n",
"\n",
"interface Props {\n",
" tags?: string[];\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" placeholder?: string;\n"
],
"file_path": "packages/grafana-ui/src/components/TagsInput/TagsInput.tsx",
"type": "add",
"edit_start_line_idx": 8
} | import React, { ChangeEvent, KeyboardEvent, PureComponent } from 'react';
import { css, cx } from 'emotion';
import { stylesFactory } from '../../themes/stylesFactory';
import { Button } from '../Button';
import { Input } from '../Forms/Legacy/Input/Input';
import { TagItem } from './TagItem';
interface Props {
tags?: string[];
width?: number;
onChange: (tags: string[]) => void;
}
interface State {
newTag: string;
tags: string[];
}
export class TagsInput extends PureComponent<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
newTag: '',
tags: this.props.tags || [],
};
}
onNameChange = (event: ChangeEvent<HTMLInputElement>) => {
this.setState({
newTag: event.target.value,
});
};
onRemove = (tagToRemove: string) => {
this.setState(
(prevState: State) => ({
...prevState,
tags: prevState.tags.filter((tag) => tagToRemove !== tag),
}),
() => this.onChange()
);
};
// Using React.MouseEvent to avoid tslint error
onAdd = (event: React.MouseEvent) => {
event.preventDefault();
if (this.state.newTag !== '') {
this.setNewTags();
}
};
onKeyboardAdd = (event: KeyboardEvent) => {
event.preventDefault();
if (event.key === 'Enter' && this.state.newTag !== '') {
this.setNewTags();
}
};
setNewTags = () => {
// We don't want to duplicate tags, clearing the input if
// the user is trying to add the same tag.
if (!this.state.tags.includes(this.state.newTag)) {
this.setState(
(prevState: State) => ({
...prevState,
tags: [...prevState.tags, prevState.newTag],
newTag: '',
}),
() => this.onChange()
);
} else {
this.setState({ newTag: '' });
}
};
onChange = () => {
this.props.onChange(this.state.tags);
};
render() {
const { tags, newTag } = this.state;
const getStyles = stylesFactory(() => ({
tagsCloudStyle: css`
display: flex;
justify-content: flex-start;
flex-wrap: wrap;
`,
addButtonStyle: css`
margin-left: 8px;
`,
}));
return (
<div className="width-20">
<div
className={cx(
['gf-form-inline'],
css`
margin-bottom: 4px;
`
)}
>
<Input placeholder="Add Name" onChange={this.onNameChange} value={newTag} onKeyUp={this.onKeyboardAdd} />
<Button className={getStyles().addButtonStyle} onClick={this.onAdd} variant="secondary" size="md">
Add
</Button>
</div>
<div className={getStyles().tagsCloudStyle}>
{tags &&
tags.map((tag: string, index: number) => {
return <TagItem key={`${tag}-${index}`} name={tag} onRemove={this.onRemove} />;
})}
</div>
</div>
);
}
}
| packages/grafana-ui/src/components/TagsInput/TagsInput.tsx | 1 | https://github.com/grafana/grafana/commit/7d4c51459f4abce8cc23b1dcfb24757e65b18120 | [
0.9991922974586487,
0.30675917863845825,
0.0001653133804211393,
0.0002543362497817725,
0.45910921692848206
] |
{
"id": 2,
"code_window": [
"import { TagItem } from './TagItem';\n",
"\n",
"interface Props {\n",
" tags?: string[];\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" placeholder?: string;\n"
],
"file_path": "packages/grafana-ui/src/components/TagsInput/TagsInput.tsx",
"type": "add",
"edit_start_line_idx": 8
} | import React, { useState, useEffect } from 'react';
import { Project, VisualMetricQueryEditor, AliasBy } from '.';
import { MetricQuery, MetricDescriptor, EditorMode } from '../types';
import { getAlignmentPickerData } from '../functions';
import CloudMonitoringDatasource from '../datasource';
import { SelectableValue } from '@grafana/data';
import { MQLQueryEditor } from './MQLQueryEditor';
export interface Props {
refId: string;
usedAlignmentPeriod?: number;
variableOptionGroup: SelectableValue<string>;
onChange: (query: MetricQuery) => void;
onRunQuery: () => void;
query: MetricQuery;
datasource: CloudMonitoringDatasource;
}
interface State {
labels: any;
[key: string]: any;
}
export const defaultState: State = {
labels: {},
};
export const defaultQuery: (dataSource: CloudMonitoringDatasource) => MetricQuery = (dataSource) => ({
editorMode: EditorMode.Visual,
projectName: dataSource.getDefaultProject(),
metricType: '',
metricKind: '',
valueType: '',
unit: '',
crossSeriesReducer: 'REDUCE_MEAN',
alignmentPeriod: 'cloud-monitoring-auto',
perSeriesAligner: 'ALIGN_MEAN',
groupBys: [],
filters: [],
aliasBy: '',
query: '',
});
function Editor({
refId,
query,
datasource,
onChange: onQueryChange,
onRunQuery,
usedAlignmentPeriod,
variableOptionGroup,
}: React.PropsWithChildren<Props>) {
const [state, setState] = useState<State>(defaultState);
useEffect(() => {
if (query && query.projectName && query.metricType) {
datasource
.getLabels(query.metricType, refId, query.projectName, query.groupBys)
.then((labels) => setState({ ...state, labels }));
}
}, [query.projectName, query.groupBys, query.metricType]);
const onChange = (metricQuery: MetricQuery) => {
onQueryChange({ ...query, ...metricQuery });
onRunQuery();
};
const onMetricTypeChange = async ({ valueType, metricKind, type, unit }: MetricDescriptor) => {
const { perSeriesAligner, alignOptions } = getAlignmentPickerData(
{ valueType, metricKind, perSeriesAligner: state.perSeriesAligner },
datasource.templateSrv
);
setState({
...state,
alignOptions,
});
onChange({ ...query, perSeriesAligner, metricType: type, unit, valueType, metricKind });
};
return (
<>
<Project
templateVariableOptions={variableOptionGroup.options}
projectName={query.projectName}
datasource={datasource}
onChange={(projectName) => {
onChange({ ...query, projectName });
}}
/>
{query.editorMode === EditorMode.Visual && (
<VisualMetricQueryEditor
labels={state.labels}
variableOptionGroup={variableOptionGroup}
usedAlignmentPeriod={usedAlignmentPeriod}
onMetricTypeChange={onMetricTypeChange}
onChange={onChange}
datasource={datasource}
query={query}
/>
)}
{query.editorMode === EditorMode.MQL && (
<MQLQueryEditor
onChange={(q: string) => onQueryChange({ ...query, query: q })}
onRunQuery={onRunQuery}
query={query.query}
></MQLQueryEditor>
)}
<AliasBy
value={query.aliasBy}
onChange={(aliasBy) => {
onChange({ ...query, aliasBy });
}}
/>
</>
);
}
export const MetricQueryEditor = React.memo(Editor);
| public/app/plugins/datasource/cloud-monitoring/components/MetricQueryEditor.tsx | 0 | https://github.com/grafana/grafana/commit/7d4c51459f4abce8cc23b1dcfb24757e65b18120 | [
0.9901959300041199,
0.1524074375629425,
0.0001672001526458189,
0.00017492020560894161,
0.35701999068260193
] |
{
"id": 2,
"code_window": [
"import { TagItem } from './TagItem';\n",
"\n",
"interface Props {\n",
" tags?: string[];\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" placeholder?: string;\n"
],
"file_path": "packages/grafana-ui/src/components/TagsInput/TagsInput.tsx",
"type": "add",
"edit_start_line_idx": 8
} | import React, { FC } from 'react';
import _ from 'lodash';
import DropDownChild from './DropDownChild';
import { NavModelItem } from '@grafana/data';
interface Props {
link: NavModelItem;
onHeaderClick?: () => void;
}
const SideMenuDropDown: FC<Props> = (props) => {
const { link, onHeaderClick } = props;
let childrenLinks: NavModelItem[] = [];
if (link.children) {
childrenLinks = _.filter(link.children, (item) => !item.hideFromMenu);
}
return (
<ul className="dropdown-menu dropdown-menu--sidemenu" role="menu">
<li className="side-menu-header">
<a className="side-menu-header-link" href={link.url} onClick={onHeaderClick}>
<span className="sidemenu-item-text">{link.text}</span>
</a>
</li>
{childrenLinks.map((child, index) => {
return <DropDownChild child={child} key={`${child.url}-${index}`} />;
})}
</ul>
);
};
export default SideMenuDropDown;
| public/app/core/components/sidemenu/SideMenuDropDown.tsx | 0 | https://github.com/grafana/grafana/commit/7d4c51459f4abce8cc23b1dcfb24757e65b18120 | [
0.9985910058021545,
0.4959968030452728,
0.00017306063091382384,
0.49261152744293213,
0.4958445727825165
] |
{
"id": 2,
"code_window": [
"import { TagItem } from './TagItem';\n",
"\n",
"interface Props {\n",
" tags?: string[];\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" placeholder?: string;\n"
],
"file_path": "packages/grafana-ui/src/components/TagsInput/TagsInput.tsx",
"type": "add",
"edit_start_line_idx": 8
} | +++
title = "cURL examples"
description = "cURL examples"
keywords = ["grafana", "http", "documentation", "api", "curl"]
+++
# cURL examples
This page provides examples of calls to the Grafana API using cURL.
The most basic example for a dashboard for which there is no authentication. You can test the following on your local machine, assuming a default installation and anonymous access enabled, required:
```
curl http://localhost:3000/api/search
```
Here’s a cURL command that works for getting the home dashboard when you are running Grafana locally with [basic authentication]({{< relref "../auth/#basic-auth" >}}) enabled using the default admin credentials:
```
curl http://admin:admin@localhost:3000/api/search
``` | docs/sources/http_api/curl-examples.md | 0 | https://github.com/grafana/grafana/commit/7d4c51459f4abce8cc23b1dcfb24757e65b18120 | [
0.0001828053209464997,
0.0001747875357978046,
0.00016986235277727246,
0.00017169493366964161,
0.000005718580723623745
] |
{
"id": 3,
"code_window": [
" tags?: string[];\n",
" width?: number;\n",
"\n",
" onChange: (tags: string[]) => void;\n",
"}\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/grafana-ui/src/components/TagsInput/TagsInput.tsx",
"type": "replace",
"edit_start_line_idx": 9
} | import React, { ChangeEvent, KeyboardEvent, PureComponent } from 'react';
import { css, cx } from 'emotion';
import { stylesFactory } from '../../themes/stylesFactory';
import { Button } from '../Button';
import { Input } from '../Forms/Legacy/Input/Input';
import { TagItem } from './TagItem';
interface Props {
tags?: string[];
width?: number;
onChange: (tags: string[]) => void;
}
interface State {
newTag: string;
tags: string[];
}
export class TagsInput extends PureComponent<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
newTag: '',
tags: this.props.tags || [],
};
}
onNameChange = (event: ChangeEvent<HTMLInputElement>) => {
this.setState({
newTag: event.target.value,
});
};
onRemove = (tagToRemove: string) => {
this.setState(
(prevState: State) => ({
...prevState,
tags: prevState.tags.filter((tag) => tagToRemove !== tag),
}),
() => this.onChange()
);
};
// Using React.MouseEvent to avoid tslint error
onAdd = (event: React.MouseEvent) => {
event.preventDefault();
if (this.state.newTag !== '') {
this.setNewTags();
}
};
onKeyboardAdd = (event: KeyboardEvent) => {
event.preventDefault();
if (event.key === 'Enter' && this.state.newTag !== '') {
this.setNewTags();
}
};
setNewTags = () => {
// We don't want to duplicate tags, clearing the input if
// the user is trying to add the same tag.
if (!this.state.tags.includes(this.state.newTag)) {
this.setState(
(prevState: State) => ({
...prevState,
tags: [...prevState.tags, prevState.newTag],
newTag: '',
}),
() => this.onChange()
);
} else {
this.setState({ newTag: '' });
}
};
onChange = () => {
this.props.onChange(this.state.tags);
};
render() {
const { tags, newTag } = this.state;
const getStyles = stylesFactory(() => ({
tagsCloudStyle: css`
display: flex;
justify-content: flex-start;
flex-wrap: wrap;
`,
addButtonStyle: css`
margin-left: 8px;
`,
}));
return (
<div className="width-20">
<div
className={cx(
['gf-form-inline'],
css`
margin-bottom: 4px;
`
)}
>
<Input placeholder="Add Name" onChange={this.onNameChange} value={newTag} onKeyUp={this.onKeyboardAdd} />
<Button className={getStyles().addButtonStyle} onClick={this.onAdd} variant="secondary" size="md">
Add
</Button>
</div>
<div className={getStyles().tagsCloudStyle}>
{tags &&
tags.map((tag: string, index: number) => {
return <TagItem key={`${tag}-${index}`} name={tag} onRemove={this.onRemove} />;
})}
</div>
</div>
);
}
}
| packages/grafana-ui/src/components/TagsInput/TagsInput.tsx | 1 | https://github.com/grafana/grafana/commit/7d4c51459f4abce8cc23b1dcfb24757e65b18120 | [
0.9964988231658936,
0.09599519520998001,
0.00017517506785225123,
0.003389195306226611,
0.26240992546081543
] |
{
"id": 3,
"code_window": [
" tags?: string[];\n",
" width?: number;\n",
"\n",
" onChange: (tags: string[]) => void;\n",
"}\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/grafana-ui/src/components/TagsInput/TagsInput.tsx",
"type": "replace",
"edit_start_line_idx": 9
} | import {
FieldConfigSource,
GrafanaPlugin,
PanelEditorProps,
PanelMigrationHandler,
PanelOptionEditorsRegistry,
PanelPluginMeta,
PanelProps,
PanelTypeChangedHandler,
FieldConfigProperty,
} from '../types';
import { FieldConfigEditorBuilder, PanelOptionsEditorBuilder } from '../utils/OptionsUIBuilders';
import { ComponentClass, ComponentType } from 'react';
import set from 'lodash/set';
import { deprecationWarning } from '../utils';
import { FieldConfigOptionsRegistry } from '../field';
import { createFieldConfigRegistry } from './registryFactories';
/** @beta */
export type StandardOptionConfig = {
defaultValue?: any;
settings?: any;
};
/** @beta */
export interface SetFieldConfigOptionsArgs<TFieldConfigOptions = any> {
/**
* Configuration object of the standard field config properites
*
* @example
* ```typescript
* {
* standardOptions: {
* [FieldConfigProperty.Decimals]: {
* defaultValue: 3
* }
* }
* }
* ```
*/
standardOptions?: Partial<Record<FieldConfigProperty, StandardOptionConfig>>;
/**
* Array of standard field config properties that should not be available in the panel
* @example
* ```typescript
* {
* disableStandardOptions: [FieldConfigProperty.Min, FieldConfigProperty.Max, FieldConfigProperty.Unit]
* }
* ```
*/
disableStandardOptions?: FieldConfigProperty[];
/**
* Function that allows custom field config properties definition.
*
* @param builder
*
* @example
* ```typescript
* useCustomConfig: builder => {
* builder
* .addNumberInput({
* id: 'shapeBorderWidth',
* name: 'Border width',
* description: 'Border width of the shape',
* settings: {
* min: 1,
* max: 5,
* },
* })
* .addSelect({
* id: 'displayMode',
* name: 'Display mode',
* description: 'How the shape shout be rendered'
* settings: {
* options: [{value: 'fill', label: 'Fill' }, {value: 'transparent', label: 'Transparent }]
* },
* })
* }
* ```
*/
useCustomConfig?: (builder: FieldConfigEditorBuilder<TFieldConfigOptions>) => void;
}
export class PanelPlugin<
TOptions = any,
TFieldConfigOptions extends object = any
> extends GrafanaPlugin<PanelPluginMeta> {
private _defaults?: TOptions;
private _fieldConfigDefaults: FieldConfigSource<TFieldConfigOptions> = {
defaults: {},
overrides: [],
};
private _fieldConfigRegistry?: FieldConfigOptionsRegistry;
private _initConfigRegistry = () => {
return new FieldConfigOptionsRegistry();
};
private _optionEditors?: PanelOptionEditorsRegistry;
private registerOptionEditors?: (builder: PanelOptionsEditorBuilder<TOptions>) => void;
panel: ComponentType<PanelProps<TOptions>> | null;
editor?: ComponentClass<PanelEditorProps<TOptions>>;
onPanelMigration?: PanelMigrationHandler<TOptions>;
onPanelTypeChanged?: PanelTypeChangedHandler<TOptions>;
noPadding?: boolean;
/**
* Legacy angular ctrl. If this exists it will be used instead of the panel
*/
angularPanelCtrl?: any;
constructor(panel: ComponentType<PanelProps<TOptions>> | null) {
super();
this.panel = panel;
}
get defaults() {
let result = this._defaults || {};
if (!this._defaults) {
const editors = this.optionEditors;
if (!editors || editors.list().length === 0) {
return null;
}
for (const editor of editors.list()) {
set(result, editor.id, editor.defaultValue);
}
}
return result;
}
get fieldConfigDefaults(): FieldConfigSource<TFieldConfigOptions> {
const configDefaults = this._fieldConfigDefaults.defaults;
configDefaults.custom = {} as TFieldConfigOptions;
for (const option of this.fieldConfigRegistry.list()) {
if (option.defaultValue === undefined) {
continue;
}
set(configDefaults, option.id, option.defaultValue);
}
return {
defaults: {
...configDefaults,
},
overrides: this._fieldConfigDefaults.overrides,
};
}
/**
* @deprecated setDefaults is deprecated in favor of setPanelOptions
*/
setDefaults(defaults: TOptions) {
deprecationWarning('PanelPlugin', 'setDefaults', 'setPanelOptions');
this._defaults = defaults;
return this;
}
get fieldConfigRegistry() {
if (!this._fieldConfigRegistry) {
this._fieldConfigRegistry = this._initConfigRegistry();
}
return this._fieldConfigRegistry;
}
get optionEditors(): PanelOptionEditorsRegistry {
if (!this._optionEditors) {
const builder = new PanelOptionsEditorBuilder<TOptions>();
this._optionEditors = builder.getRegistry();
if (this.registerOptionEditors) {
this.registerOptionEditors(builder);
}
}
return this._optionEditors;
}
/**
* @deprecated setEditor is deprecated in favor of setPanelOptions
*/
setEditor(editor: ComponentClass<PanelEditorProps<TOptions>>) {
deprecationWarning('PanelPlugin', 'setEditor', 'setPanelOptions');
this.editor = editor;
return this;
}
setNoPadding() {
this.noPadding = true;
return this;
}
/**
* This function is called before the panel first loads if
* the current version is different than the version that was saved.
*
* This is a good place to support any changes to the options model
*/
setMigrationHandler(handler: PanelMigrationHandler<TOptions>) {
this.onPanelMigration = handler;
return this;
}
/**
* This function is called when the visualization was changed. This
* passes in the panel model for previous visualisation options inspection
* and panel model updates.
*
* This is useful for supporting PanelModel API updates when changing
* between Angular and React panels.
*/
setPanelChangeHandler(handler: PanelTypeChangedHandler) {
this.onPanelTypeChanged = handler;
return this;
}
/**
* Enables panel options editor creation
*
* @example
* ```typescript
*
* import { ShapePanel } from './ShapePanel';
*
* interface ShapePanelOptions {}
*
* export const plugin = new PanelPlugin<ShapePanelOptions>(ShapePanel)
* .setPanelOptions(builder => {
* builder
* .addSelect({
* id: 'shape',
* name: 'Shape',
* description: 'Select shape to render'
* settings: {
* options: [
* {value: 'circle', label: 'Circle' },
* {value: 'square', label: 'Square },
* {value: 'triangle', label: 'Triangle }
* ]
* },
* })
* })
* ```
*
* @public
**/
setPanelOptions(builder: (builder: PanelOptionsEditorBuilder<TOptions>) => void) {
// builder is applied lazily when options UI is created
this.registerOptionEditors = builder;
return this;
}
/**
* Allows specifying which standard field config options panel should use and defining default values
*
* @example
* ```typescript
*
* import { ShapePanel } from './ShapePanel';
*
* interface ShapePanelOptions {}
*
* // when plugin should use all standard options
* export const plugin = new PanelPlugin<ShapePanelOptions>(ShapePanel)
* .useFieldConfig();
*
* // when plugin should only display specific standard options
* // note, that options will be displayed in the order they are provided
* export const plugin = new PanelPlugin<ShapePanelOptions>(ShapePanel)
* .useFieldConfig({
* standardOptions: [FieldConfigProperty.Min, FieldConfigProperty.Max]
* });
*
* // when standard option's default value needs to be provided
* export const plugin = new PanelPlugin<ShapePanelOptions>(ShapePanel)
* .useFieldConfig({
* standardOptions: [FieldConfigProperty.Min, FieldConfigProperty.Max],
* standardOptionsDefaults: {
* [FieldConfigProperty.Min]: 20,
* [FieldConfigProperty.Max]: 100
* }
* });
*
* // when custom field config options needs to be provided
* export const plugin = new PanelPlugin<ShapePanelOptions>(ShapePanel)
* .useFieldConfig({
* useCustomConfig: builder => {
* builder
* .addNumberInput({
* id: 'shapeBorderWidth',
* name: 'Border width',
* description: 'Border width of the shape',
* settings: {
* min: 1,
* max: 5,
* },
* })
* .addSelect({
* id: 'displayMode',
* name: 'Display mode',
* description: 'How the shape shout be rendered'
* settings: {
* options: [{value: 'fill', label: 'Fill' }, {value: 'transparent', label: 'Transparent }]
* },
* })
* },
* });
*
* ```
*
* @public
*/
useFieldConfig(config: SetFieldConfigOptionsArgs<TFieldConfigOptions> = {}) {
// builder is applied lazily when custom field configs are accessed
this._initConfigRegistry = () => createFieldConfigRegistry(config, this.meta.name);
return this;
}
}
| packages/grafana-data/src/panel/PanelPlugin.ts | 0 | https://github.com/grafana/grafana/commit/7d4c51459f4abce8cc23b1dcfb24757e65b18120 | [
0.0003311623877380043,
0.00018212896247860044,
0.000166843572515063,
0.00016986040282063186,
0.00003300561002106406
] |
{
"id": 3,
"code_window": [
" tags?: string[];\n",
" width?: number;\n",
"\n",
" onChange: (tags: string[]) => void;\n",
"}\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/grafana-ui/src/components/TagsInput/TagsInput.tsx",
"type": "replace",
"edit_start_line_idx": 9
} | <?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 19.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="64px" height="64px" viewBox="-479 353 64 64" style="enable-background:new -479 353 64 64;" xml:space="preserve">
<style type="text/css">
.st0{fill:#E2E2E2;}
</style>
<path class="st0" d="M-415.1,384c-0.4-0.7-9.5-16.6-31.6-16.6c0,0-0.1,0-0.1,0c0,0,0,0,0,0c0,0-0.1,0-0.1,0
c-22,0.1-31.3,15.9-31.6,16.6c-0.3,0.6-0.3,1.3,0,1.9c0.4,0.7,9.6,16.5,31.6,16.6c0,0,0.1,0,0.1,0c0,0,0,0,0,0c0,0,0.1,0,0.1,0
c22.2,0,31.2-16,31.6-16.6C-414.8,385.3-414.8,384.6-415.1,384z M-446.9,399.3c-7.9,0-14.3-6.4-14.3-14.3c0-7.9,6.4-14.3,14.3-14.3
c7.9,0,14.3,6.4,14.3,14.3C-432.6,392.9-439,399.3-446.9,399.3z"/>
<g>
<path class="st0" d="M-446.9,378.3c-0.9,0-1.8,0.2-2.6,0.5c1.2,0.4,2,1.5,2,2.9c0,1.7-1.4,3-3,3c-1.2,0-2.2-0.7-2.7-1.7
c-0.2,0.6-0.3,1.3-0.3,2c0,3.7,3,6.7,6.7,6.7c3.7,0,6.7-3,6.7-6.7S-443.2,378.3-446.9,378.3z"/>
</g>
</svg>
| public/img/icons_dark_theme/icon_viewer.svg | 0 | https://github.com/grafana/grafana/commit/7d4c51459f4abce8cc23b1dcfb24757e65b18120 | [
0.00016640998364891857,
0.0001662468712311238,
0.00016608375881332904,
0.0001662468712311238,
1.6311241779476404e-7
] |
{
"id": 3,
"code_window": [
" tags?: string[];\n",
" width?: number;\n",
"\n",
" onChange: (tags: string[]) => void;\n",
"}\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/grafana-ui/src/components/TagsInput/TagsInput.tsx",
"type": "replace",
"edit_start_line_idx": 9
} | import React, { HTMLAttributes } from 'react';
import { Label } from './Label';
import { stylesFactory, useTheme } from '../../themes';
import { css, cx } from 'emotion';
import { GrafanaTheme } from '@grafana/data';
import { FieldValidationMessage } from './FieldValidationMessage';
export interface FieldProps extends HTMLAttributes<HTMLDivElement> {
/** Form input element, i.e Input or Switch */
children: React.ReactElement;
/** Label for the field */
label?: React.ReactNode;
/** Description of the field */
description?: string;
/** Indicates if field is in invalid state */
invalid?: boolean;
/** Indicates if field is in loading state */
loading?: boolean;
/** Indicates if field is disabled */
disabled?: boolean;
/** Indicates if field is required */
required?: boolean;
/** Error message to display */
error?: string;
/** Indicates horizontal layout of the field */
horizontal?: boolean;
className?: string;
}
export const getFieldStyles = stylesFactory((theme: GrafanaTheme) => {
return {
field: css`
display: flex;
flex-direction: column;
margin-bottom: ${theme.spacing.formInputMargin};
`,
fieldHorizontal: css`
flex-direction: row;
justify-content: space-between;
flex-wrap: wrap;
`,
fieldValidationWrapper: css`
margin-top: ${theme.spacing.formSpacingBase / 2}px;
`,
fieldValidationWrapperHorizontal: css`
flex: 1 1 100%;
`,
};
});
export const Field: React.FC<FieldProps> = ({
label,
description,
horizontal,
invalid,
loading,
disabled,
required,
error,
children,
className,
...otherProps
}) => {
const theme = useTheme();
let inputId;
const styles = getFieldStyles(theme);
// Get the first, and only, child to retrieve form input's id
const child = React.Children.map(children, (c) => c)[0];
if (child) {
// Retrieve input's id to apply on the label for correct click interaction
inputId = (child as React.ReactElement<{ id?: string }>).props.id;
}
const labelElement =
typeof label === 'string' ? (
<Label htmlFor={inputId} description={description}>
{`${label}${required ? ' *' : ''}`}
</Label>
) : (
label
);
return (
<div className={cx(styles.field, horizontal && styles.fieldHorizontal, className)} {...otherProps}>
{labelElement}
<div>
{React.cloneElement(children, { invalid, disabled, loading })}
{invalid && error && !horizontal && (
<div className={styles.fieldValidationWrapper}>
<FieldValidationMessage>{error}</FieldValidationMessage>
</div>
)}
</div>
{invalid && error && horizontal && (
<div className={cx(styles.fieldValidationWrapper, styles.fieldValidationWrapperHorizontal)}>
<FieldValidationMessage>{error}</FieldValidationMessage>
</div>
)}
</div>
);
};
| packages/grafana-ui/src/components/Forms/Field.tsx | 0 | https://github.com/grafana/grafana/commit/7d4c51459f4abce8cc23b1dcfb24757e65b18120 | [
0.0007273219525814056,
0.00023379568301606923,
0.00016780818987172097,
0.00017104443395510316,
0.00016022915951907635
] |
{
"id": 4,
"code_window": [
" };\n",
"\n",
" render() {\n",
" const { tags, newTag } = this.state;\n",
"\n",
" const getStyles = stylesFactory(() => ({\n",
" tagsCloudStyle: css`\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { placeholder = 'Add name' } = this.props;\n"
],
"file_path": "packages/grafana-ui/src/components/TagsInput/TagsInput.tsx",
"type": "add",
"edit_start_line_idx": 82
} | import React, { ChangeEvent, KeyboardEvent, PureComponent } from 'react';
import { css, cx } from 'emotion';
import { stylesFactory } from '../../themes/stylesFactory';
import { Button } from '../Button';
import { Input } from '../Forms/Legacy/Input/Input';
import { TagItem } from './TagItem';
interface Props {
tags?: string[];
width?: number;
onChange: (tags: string[]) => void;
}
interface State {
newTag: string;
tags: string[];
}
export class TagsInput extends PureComponent<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
newTag: '',
tags: this.props.tags || [],
};
}
onNameChange = (event: ChangeEvent<HTMLInputElement>) => {
this.setState({
newTag: event.target.value,
});
};
onRemove = (tagToRemove: string) => {
this.setState(
(prevState: State) => ({
...prevState,
tags: prevState.tags.filter((tag) => tagToRemove !== tag),
}),
() => this.onChange()
);
};
// Using React.MouseEvent to avoid tslint error
onAdd = (event: React.MouseEvent) => {
event.preventDefault();
if (this.state.newTag !== '') {
this.setNewTags();
}
};
onKeyboardAdd = (event: KeyboardEvent) => {
event.preventDefault();
if (event.key === 'Enter' && this.state.newTag !== '') {
this.setNewTags();
}
};
setNewTags = () => {
// We don't want to duplicate tags, clearing the input if
// the user is trying to add the same tag.
if (!this.state.tags.includes(this.state.newTag)) {
this.setState(
(prevState: State) => ({
...prevState,
tags: [...prevState.tags, prevState.newTag],
newTag: '',
}),
() => this.onChange()
);
} else {
this.setState({ newTag: '' });
}
};
onChange = () => {
this.props.onChange(this.state.tags);
};
render() {
const { tags, newTag } = this.state;
const getStyles = stylesFactory(() => ({
tagsCloudStyle: css`
display: flex;
justify-content: flex-start;
flex-wrap: wrap;
`,
addButtonStyle: css`
margin-left: 8px;
`,
}));
return (
<div className="width-20">
<div
className={cx(
['gf-form-inline'],
css`
margin-bottom: 4px;
`
)}
>
<Input placeholder="Add Name" onChange={this.onNameChange} value={newTag} onKeyUp={this.onKeyboardAdd} />
<Button className={getStyles().addButtonStyle} onClick={this.onAdd} variant="secondary" size="md">
Add
</Button>
</div>
<div className={getStyles().tagsCloudStyle}>
{tags &&
tags.map((tag: string, index: number) => {
return <TagItem key={`${tag}-${index}`} name={tag} onRemove={this.onRemove} />;
})}
</div>
</div>
);
}
}
| packages/grafana-ui/src/components/TagsInput/TagsInput.tsx | 1 | https://github.com/grafana/grafana/commit/7d4c51459f4abce8cc23b1dcfb24757e65b18120 | [
0.9989601373672485,
0.5323256254196167,
0.00017570301133673638,
0.950712263584137,
0.48909443616867065
] |
{
"id": 4,
"code_window": [
" };\n",
"\n",
" render() {\n",
" const { tags, newTag } = this.state;\n",
"\n",
" const getStyles = stylesFactory(() => ({\n",
" tagsCloudStyle: css`\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { placeholder = 'Add name' } = this.props;\n"
],
"file_path": "packages/grafana-ui/src/components/TagsInput/TagsInput.tsx",
"type": "add",
"edit_start_line_idx": 82
} | import {
addToRichHistory,
updateStarredInRichHistory,
updateCommentInRichHistory,
mapNumbertoTimeInSlider,
createDateStringFromTs,
createQueryHeading,
deleteAllFromRichHistory,
deleteQueryInRichHistory,
filterAndSortQueries,
} from './richHistory';
import store from 'app/core/store';
import { SortOrder } from './richHistory';
import { dateTime, DataQuery } from '@grafana/data';
const mock: any = {
storedHistory: [
{
comment: '',
datasourceId: 'datasource historyId',
datasourceName: 'datasource history name',
queries: [
{ expr: 'query1', maxLines: null, refId: '1' },
{ expr: 'query2', refId: '2' },
],
sessionName: '',
starred: true,
ts: 1,
},
],
testComment: '',
testDatasourceId: 'datasourceId',
testDatasourceName: 'datasourceName',
testQueries: [
{ expr: 'query3', refId: 'B' },
{ expr: 'query4', refId: 'C' },
],
testSessionName: '',
testStarred: false,
};
const key = 'grafana.explore.richHistory';
describe('addToRichHistory', () => {
beforeEach(() => {
deleteAllFromRichHistory();
expect(store.exists(key)).toBeFalsy();
});
const expectedResult = [
{
comment: mock.testComment,
datasourceId: mock.testDatasourceId,
datasourceName: mock.testDatasourceName,
queries: mock.testQueries,
sessionName: mock.testSessionName,
starred: mock.testStarred,
ts: 2,
},
mock.storedHistory[0],
];
it('should append query to query history', () => {
Date.now = jest.fn(() => 2);
const newHistory = addToRichHistory(
mock.storedHistory,
mock.testDatasourceId,
mock.testDatasourceName,
mock.testQueries,
mock.testStarred,
mock.testComment,
mock.testSessionName
);
expect(newHistory).toEqual(expectedResult);
});
it('should save query history to localStorage', () => {
Date.now = jest.fn(() => 2);
addToRichHistory(
mock.storedHistory,
mock.testDatasourceId,
mock.testDatasourceName,
mock.testQueries,
mock.testStarred,
mock.testComment,
mock.testSessionName
);
expect(store.exists(key)).toBeTruthy();
expect(store.getObject(key)).toMatchObject(expectedResult);
});
it('should not append duplicated query to query history', () => {
Date.now = jest.fn(() => 2);
const newHistory = addToRichHistory(
mock.storedHistory,
mock.storedHistory[0].datasourceId,
mock.storedHistory[0].datasourceName,
[{ expr: 'query1', maxLines: null, refId: 'A' } as DataQuery, { expr: 'query2', refId: 'B' } as DataQuery],
mock.testStarred,
mock.testComment,
mock.testSessionName
);
expect(newHistory).toEqual([mock.storedHistory[0]]);
});
it('should not save duplicated query to localStorage', () => {
Date.now = jest.fn(() => 2);
addToRichHistory(
mock.storedHistory,
mock.storedHistory[0].datasourceId,
mock.storedHistory[0].datasourceName,
[{ expr: 'query1', maxLines: null, refId: 'A' } as DataQuery, { expr: 'query2', refId: 'B' } as DataQuery],
mock.testStarred,
mock.testComment,
mock.testSessionName
);
expect(store.exists(key)).toBeFalsy();
});
});
describe('updateStarredInRichHistory', () => {
it('should update starred in query in history', () => {
const updatedStarred = updateStarredInRichHistory(mock.storedHistory, 1);
expect(updatedStarred[0].starred).toEqual(false);
});
it('should update starred in localStorage', () => {
updateStarredInRichHistory(mock.storedHistory, 1);
expect(store.exists(key)).toBeTruthy();
expect(store.getObject(key)[0].starred).toEqual(false);
});
});
describe('updateCommentInRichHistory', () => {
it('should update comment in query in history', () => {
const updatedComment = updateCommentInRichHistory(mock.storedHistory, 1, 'new comment');
expect(updatedComment[0].comment).toEqual('new comment');
});
it('should update comment in localStorage', () => {
updateCommentInRichHistory(mock.storedHistory, 1, 'new comment');
expect(store.exists(key)).toBeTruthy();
expect(store.getObject(key)[0].comment).toEqual('new comment');
});
});
describe('deleteQueryInRichHistory', () => {
it('should delete query in query in history', () => {
const deletedHistory = deleteQueryInRichHistory(mock.storedHistory, 1);
expect(deletedHistory).toEqual([]);
});
it('should delete query in localStorage', () => {
deleteQueryInRichHistory(mock.storedHistory, 1);
expect(store.exists(key)).toBeTruthy();
expect(store.getObject(key)).toEqual([]);
});
});
describe('mapNumbertoTimeInSlider', () => {
it('should correctly map number to value', () => {
const value = mapNumbertoTimeInSlider(25);
expect(value).toEqual('25 days ago');
});
});
describe('createDateStringFromTs', () => {
it('should correctly create string value from timestamp', () => {
const value = createDateStringFromTs(1583932327000);
expect(value).toEqual('March 11');
});
});
describe('filterQueries', () => {
it('should filter out queries based on data source filter', () => {
const filteredQueries = filterAndSortQueries(
mock.storedHistory,
SortOrder.Ascending,
['not provided data source'],
''
);
expect(filteredQueries).toHaveLength(0);
});
it('should keep queries based on data source filter', () => {
const filteredQueries = filterAndSortQueries(
mock.storedHistory,
SortOrder.Ascending,
['datasource history name'],
''
);
expect(filteredQueries).toHaveLength(1);
});
it('should filter out all queries based on search filter', () => {
const filteredQueries = filterAndSortQueries(
mock.storedHistory,
SortOrder.Ascending,
[],
'i do not exist in query'
);
expect(filteredQueries).toHaveLength(0);
});
it('should include queries based on search filter', () => {
const filteredQueries = filterAndSortQueries(mock.storedHistory, SortOrder.Ascending, [], 'query1');
expect(filteredQueries).toHaveLength(1);
});
});
describe('createQueryHeading', () => {
it('should correctly create heading for queries when sort order is ascending ', () => {
// Have to offset the timezone of a 1 microsecond epoch, and then reverse the changes
mock.storedHistory[0].ts = 1 + -1 * dateTime().utcOffset() * 60 * 1000;
const heading = createQueryHeading(mock.storedHistory[0], SortOrder.Ascending);
expect(heading).toEqual('January 1');
});
it('should correctly create heading for queries when sort order is datasourceAZ ', () => {
const heading = createQueryHeading(mock.storedHistory[0], SortOrder.DatasourceAZ);
expect(heading).toEqual(mock.storedHistory[0].datasourceName);
});
});
| public/app/core/utils/richHistory.test.ts | 0 | https://github.com/grafana/grafana/commit/7d4c51459f4abce8cc23b1dcfb24757e65b18120 | [
0.00017399464559275657,
0.00017032191681209952,
0.00016626676369924098,
0.0001699489075690508,
0.0000020223387764417566
] |
{
"id": 4,
"code_window": [
" };\n",
"\n",
" render() {\n",
" const { tags, newTag } = this.state;\n",
"\n",
" const getStyles = stylesFactory(() => ({\n",
" tagsCloudStyle: css`\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { placeholder = 'Add name' } = this.props;\n"
],
"file_path": "packages/grafana-ui/src/components/TagsInput/TagsInput.tsx",
"type": "add",
"edit_start_line_idx": 82
} | // Base classes
.label,
.badge {
display: inline-block;
padding: 2px 4px;
font-size: $font-size-base * 0.846;
font-weight: $font-weight-semi-bold;
line-height: 14px; // ensure proper line-height if floated
color: $white;
vertical-align: baseline;
white-space: nowrap;
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
background-color: $gray-1;
}
// Labels & Badges
.label-tag {
background-color: $purple;
color: darken($white, 5%);
white-space: nowrap;
border-radius: 3px;
text-shadow: none;
font-size: 12px;
padding: 0px 6px;
line-height: 20px;
height: 20px;
svg {
margin-bottom: 0;
}
.icon-tag {
position: relative;
top: 1px;
padding-right: 4px;
}
&.muted {
opacity: 0.85;
background-color: darken($purple, 10%);
color: $text-muted;
}
&:hover {
opacity: 0.85;
background-color: darken($purple, 10%);
}
&--gray {
opacity: 0.85;
background-color: $gray-1;
border-color: $gray-2;
&:hover {
background-color: $gray-1;
}
}
}
| public/sass/components/_tags.scss | 0 | https://github.com/grafana/grafana/commit/7d4c51459f4abce8cc23b1dcfb24757e65b18120 | [
0.00017039004887919873,
0.00016913835133891553,
0.00016787317872513086,
0.00016935874009504914,
8.800993782642763e-7
] |
{
"id": 4,
"code_window": [
" };\n",
"\n",
" render() {\n",
" const { tags, newTag } = this.state;\n",
"\n",
" const getStyles = stylesFactory(() => ({\n",
" tagsCloudStyle: css`\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { placeholder = 'Add name' } = this.props;\n"
],
"file_path": "packages/grafana-ui/src/components/TagsInput/TagsInput.tsx",
"type": "add",
"edit_start_line_idx": 82
} | import TimeGrainConverter from './time_grain_converter';
describe('TimeGrainConverter', () => {
describe('with duration of PT1H', () => {
it('should convert it to text', () => {
expect(TimeGrainConverter.createTimeGrainFromISO8601Duration('PT1H')).toEqual('1 hour');
});
it('should convert it to kbn', () => {
expect(TimeGrainConverter.createKbnUnitFromISO8601Duration('PT1H')).toEqual('1h');
});
});
describe('with duration of P1D', () => {
it('should convert it to text', () => {
expect(TimeGrainConverter.createTimeGrainFromISO8601Duration('P1D')).toEqual('1 day');
});
it('should convert it to kbn', () => {
expect(TimeGrainConverter.createKbnUnitFromISO8601Duration('P1D')).toEqual('1d');
});
});
});
| public/app/plugins/datasource/grafana-azure-monitor-datasource/time_grain_converter.test.ts | 0 | https://github.com/grafana/grafana/commit/7d4c51459f4abce8cc23b1dcfb24757e65b18120 | [
0.00016973298625089228,
0.0001683135487837717,
0.00016584747936576605,
0.00016936019528657198,
0.0000017504066818219144
] |
{
"id": 5,
"code_window": [
" margin-bottom: 4px;\n",
" `\n",
" )}\n",
" >\n",
" <Input placeholder=\"Add Name\" onChange={this.onNameChange} value={newTag} onKeyUp={this.onKeyboardAdd} />\n",
" <Button className={getStyles().addButtonStyle} onClick={this.onAdd} variant=\"secondary\" size=\"md\">\n",
" Add\n",
" </Button>\n",
" </div>\n",
" <div className={getStyles().tagsCloudStyle}>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Input placeholder={placeholder} onChange={this.onNameChange} value={newTag} onKeyUp={this.onKeyboardAdd} />\n"
],
"file_path": "packages/grafana-ui/src/components/TagsInput/TagsInput.tsx",
"type": "replace",
"edit_start_line_idx": 106
} | import React, { ChangeEvent, KeyboardEvent, PureComponent } from 'react';
import { css, cx } from 'emotion';
import { stylesFactory } from '../../themes/stylesFactory';
import { Button } from '../Button';
import { Input } from '../Forms/Legacy/Input/Input';
import { TagItem } from './TagItem';
interface Props {
tags?: string[];
width?: number;
onChange: (tags: string[]) => void;
}
interface State {
newTag: string;
tags: string[];
}
export class TagsInput extends PureComponent<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
newTag: '',
tags: this.props.tags || [],
};
}
onNameChange = (event: ChangeEvent<HTMLInputElement>) => {
this.setState({
newTag: event.target.value,
});
};
onRemove = (tagToRemove: string) => {
this.setState(
(prevState: State) => ({
...prevState,
tags: prevState.tags.filter((tag) => tagToRemove !== tag),
}),
() => this.onChange()
);
};
// Using React.MouseEvent to avoid tslint error
onAdd = (event: React.MouseEvent) => {
event.preventDefault();
if (this.state.newTag !== '') {
this.setNewTags();
}
};
onKeyboardAdd = (event: KeyboardEvent) => {
event.preventDefault();
if (event.key === 'Enter' && this.state.newTag !== '') {
this.setNewTags();
}
};
setNewTags = () => {
// We don't want to duplicate tags, clearing the input if
// the user is trying to add the same tag.
if (!this.state.tags.includes(this.state.newTag)) {
this.setState(
(prevState: State) => ({
...prevState,
tags: [...prevState.tags, prevState.newTag],
newTag: '',
}),
() => this.onChange()
);
} else {
this.setState({ newTag: '' });
}
};
onChange = () => {
this.props.onChange(this.state.tags);
};
render() {
const { tags, newTag } = this.state;
const getStyles = stylesFactory(() => ({
tagsCloudStyle: css`
display: flex;
justify-content: flex-start;
flex-wrap: wrap;
`,
addButtonStyle: css`
margin-left: 8px;
`,
}));
return (
<div className="width-20">
<div
className={cx(
['gf-form-inline'],
css`
margin-bottom: 4px;
`
)}
>
<Input placeholder="Add Name" onChange={this.onNameChange} value={newTag} onKeyUp={this.onKeyboardAdd} />
<Button className={getStyles().addButtonStyle} onClick={this.onAdd} variant="secondary" size="md">
Add
</Button>
</div>
<div className={getStyles().tagsCloudStyle}>
{tags &&
tags.map((tag: string, index: number) => {
return <TagItem key={`${tag}-${index}`} name={tag} onRemove={this.onRemove} />;
})}
</div>
</div>
);
}
}
| packages/grafana-ui/src/components/TagsInput/TagsInput.tsx | 1 | https://github.com/grafana/grafana/commit/7d4c51459f4abce8cc23b1dcfb24757e65b18120 | [
0.9944666028022766,
0.08558918535709381,
0.00016459080507047474,
0.0015466079348698258,
0.2634451985359192
] |
{
"id": 5,
"code_window": [
" margin-bottom: 4px;\n",
" `\n",
" )}\n",
" >\n",
" <Input placeholder=\"Add Name\" onChange={this.onNameChange} value={newTag} onKeyUp={this.onKeyboardAdd} />\n",
" <Button className={getStyles().addButtonStyle} onClick={this.onAdd} variant=\"secondary\" size=\"md\">\n",
" Add\n",
" </Button>\n",
" </div>\n",
" <div className={getStyles().tagsCloudStyle}>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Input placeholder={placeholder} onChange={this.onNameChange} value={newTag} onKeyUp={this.onKeyboardAdd} />\n"
],
"file_path": "packages/grafana-ui/src/components/TagsInput/TagsInput.tsx",
"type": "replace",
"edit_start_line_idx": 106
} | +++
title = "Grafana Authentication"
description = "Grafana OAuthentication Guide "
keywords = ["grafana", "configuration", "documentation", "oauth"]
weight = 100
+++
## Grafana Auth
Grafana of course has a built in user authentication system with password authentication enabled by default. You can
disable authentication by enabling anonymous access. You can also hide login form and only allow login through an auth
provider (listed above). There is also options for allowing self sign up.
### Login and short-lived tokens
> The following applies when using Grafana's built in user authentication, LDAP (without Auth proxy) or OAuth integration.
Grafana are using short-lived tokens as a mechanism for verifying authenticated users.
These short-lived tokens are rotated each `token_rotation_interval_minutes` for an active authenticated user.
An active authenticated user that gets it token rotated will extend the `login_maximum_inactive_lifetime_days` time from "now" that Grafana will remember the user.
This means that a user can close its browser and come back before `now + login_maximum_inactive_lifetime_days` and still being authenticated.
This is true as long as the time since user login is less than `login_maximum_lifetime_days`.
#### Remote logout
You can logout from other devices by removing login sessions from the bottom of your profile page. If you are
a Grafana admin user you can also do the same for any user from the Server Admin / Edit User view.
## Settings
Example:
```bash
[auth]
# Login cookie name
login_cookie_name = grafana_session
# The lifetime (days) an authenticated user can be inactive before being required to login at next visit. Default is 7 days.
login_maximum_inactive_lifetime_days = 7
# The maximum lifetime (days) an authenticated user can be logged in since login time before being required to login. Default is 30 days.
login_maximum_lifetime_days = 30
# How often should auth tokens be rotated for authenticated users when being active. The default is each 10 minutes.
token_rotation_interval_minutes = 10
# The maximum lifetime (seconds) an api key can be used. If it is set all the api keys should have limited lifetime that is lower than this value.
api_key_max_seconds_to_live = -1
```
### Anonymous authentication
You can make Grafana accessible without any login required by enabling anonymous access in the configuration file.
Example:
```bash
[auth.anonymous]
enabled = true
# Organization name that should be used for unauthenticated users
org_name = Main Org.
# Role for unauthenticated users, other valid values are `Editor` and `Admin`
org_role = Viewer
```
If you change your organization name in the Grafana UI this setting needs to be updated to match the new name.
### Basic authentication
Basic auth is enabled by default and works with the built in Grafana user password authentication system and LDAP
authentication integration.
To disable basic auth:
```bash
[auth.basic]
enabled = false
```
### Disable login form
You can hide the Grafana login form using the below configuration settings.
```bash
[auth]
disable_login_form = true
```
### Automatic OAuth login
Set to true to attempt login with OAuth automatically, skipping the login screen.
This setting is ignored if multiple OAuth providers are configured.
Defaults to `false`.
```bash
[auth]
oauth_auto_login = true
```
### Hide sign-out menu
Set the option detailed below to true to hide sign-out menu link. Useful if you use an auth proxy.
```bash
[auth]
disable_signout_menu = true
```
### URL redirect after signing out
URL to redirect the user to after signing out from Grafana. This can for example be used to enable signout from oauth provider.
```bash
[auth]
signout_redirect_url =
```
| docs/sources/auth/grafana.md | 0 | https://github.com/grafana/grafana/commit/7d4c51459f4abce8cc23b1dcfb24757e65b18120 | [
0.0002129490749211982,
0.00017023055988829583,
0.00016265930025838315,
0.00016610465536359698,
0.000012733903531625401
] |
{
"id": 5,
"code_window": [
" margin-bottom: 4px;\n",
" `\n",
" )}\n",
" >\n",
" <Input placeholder=\"Add Name\" onChange={this.onNameChange} value={newTag} onKeyUp={this.onKeyboardAdd} />\n",
" <Button className={getStyles().addButtonStyle} onClick={this.onAdd} variant=\"secondary\" size=\"md\">\n",
" Add\n",
" </Button>\n",
" </div>\n",
" <div className={getStyles().tagsCloudStyle}>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Input placeholder={placeholder} onChange={this.onNameChange} value={newTag} onKeyUp={this.onKeyboardAdd} />\n"
],
"file_path": "packages/grafana-ui/src/components/TagsInput/TagsInput.tsx",
"type": "replace",
"edit_start_line_idx": 106
} | import React, { useCallback, useRef } from 'react';
import { css, cx } from 'emotion';
import uniqueId from 'lodash/uniqueId';
import { SelectableValue } from '@grafana/data';
import { RadioButtonSize, RadioButton } from './RadioButton';
import { Icon } from '../../Icon/Icon';
import { IconName } from '../../../types/icon';
const getRadioButtonGroupStyles = () => {
return {
wrapper: css`
display: flex;
flex-direction: row;
flex-wrap: nowrap;
position: relative;
`,
radioGroup: css`
display: flex;
flex-direction: row;
flex-wrap: nowrap;
label {
border-radius: 0px;
&:first-of-type {
border-radius: 2px 0px 0px 2px;
}
&:last-of-type {
border-radius: 0px 2px 2px 0px;
}
}
`,
icon: css`
margin-right: 6px;
`,
};
};
interface RadioButtonGroupProps<T> {
value?: T;
disabled?: boolean;
disabledOptions?: T[];
options: Array<SelectableValue<T>>;
onChange?: (value?: T) => void;
size?: RadioButtonSize;
fullWidth?: boolean;
className?: string;
}
export function RadioButtonGroup<T>({
options,
value,
onChange,
disabled,
disabledOptions,
size = 'md',
className,
fullWidth = false,
}: RadioButtonGroupProps<T>) {
const handleOnChange = useCallback(
(option: SelectableValue) => {
return () => {
if (onChange) {
onChange(option.value);
}
};
},
[onChange]
);
const id = uniqueId('radiogroup-');
const groupName = useRef(id);
const styles = getRadioButtonGroupStyles();
return (
<div className={cx(styles.radioGroup, className)}>
{options.map((o, i) => {
const isItemDisabled = disabledOptions && o.value && disabledOptions.includes(o.value);
return (
<RadioButton
size={size}
disabled={isItemDisabled || disabled}
active={value === o.value}
key={`o.label-${i}`}
onChange={handleOnChange(o)}
id={`option-${o.value}-${id}`}
name={groupName.current}
fullWidth={fullWidth}
description={o.description}
>
{o.icon && <Icon name={o.icon as IconName} className={styles.icon} />}
{o.label}
</RadioButton>
);
})}
</div>
);
}
RadioButtonGroup.displayName = 'RadioButtonGroup';
| packages/grafana-ui/src/components/Forms/RadioButtonGroup/RadioButtonGroup.tsx | 0 | https://github.com/grafana/grafana/commit/7d4c51459f4abce8cc23b1dcfb24757e65b18120 | [
0.004210230894386768,
0.0005807763081975281,
0.00016247980238404125,
0.00017078172822948545,
0.0011562210274860263
] |
{
"id": 5,
"code_window": [
" margin-bottom: 4px;\n",
" `\n",
" )}\n",
" >\n",
" <Input placeholder=\"Add Name\" onChange={this.onNameChange} value={newTag} onKeyUp={this.onKeyboardAdd} />\n",
" <Button className={getStyles().addButtonStyle} onClick={this.onAdd} variant=\"secondary\" size=\"md\">\n",
" Add\n",
" </Button>\n",
" </div>\n",
" <div className={getStyles().tagsCloudStyle}>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Input placeholder={placeholder} onChange={this.onNameChange} value={newTag} onKeyUp={this.onKeyboardAdd} />\n"
],
"file_path": "packages/grafana-ui/src/components/TagsInput/TagsInput.tsx",
"type": "replace",
"edit_start_line_idx": 106
} | import { getMappedValue } from './valueMappings';
import { ValueMapping, MappingType } from '../types';
describe('Format value with value mappings', () => {
it('should return undefined with no valuemappings', () => {
const valueMappings: ValueMapping[] = [];
const value = '10';
expect(getMappedValue(valueMappings, value)).toBeUndefined();
});
it('should return undefined with no matching valuemappings', () => {
const valueMappings: ValueMapping[] = [
{ id: 0, text: 'elva', type: MappingType.ValueToText, value: '11' },
{ id: 1, text: '1-9', type: MappingType.RangeToText, from: '1', to: '9' },
];
const value = '10';
expect(getMappedValue(valueMappings, value)).toBeUndefined();
});
it('should return first matching mapping with lowest id', () => {
const valueMappings: ValueMapping[] = [
{ id: 0, text: '1-20', type: MappingType.RangeToText, from: '1', to: '20' },
{ id: 1, text: 'tio', type: MappingType.ValueToText, value: '10' },
];
const value = '10';
expect(getMappedValue(valueMappings, value).text).toEqual('1-20');
});
it('should return if value is null and value to text mapping value is null', () => {
const valueMappings: ValueMapping[] = [
{ id: 0, text: '1-20', type: MappingType.RangeToText, from: '1', to: '20' },
{ id: 1, text: '<NULL>', type: MappingType.ValueToText, value: 'null' },
];
const value = null;
expect(getMappedValue(valueMappings, value).text).toEqual('<NULL>');
});
it('should return if value is null and range to text mapping from and to is null', () => {
const valueMappings: ValueMapping[] = [
{ id: 0, text: '<NULL>', type: MappingType.RangeToText, from: 'null', to: 'null' },
{ id: 1, text: 'elva', type: MappingType.ValueToText, value: '11' },
];
const value = null;
expect(getMappedValue(valueMappings, value).text).toEqual('<NULL>');
});
it('should return rangeToText mapping where value equals to', () => {
const valueMappings: ValueMapping[] = [
{ id: 0, text: '1-10', type: MappingType.RangeToText, from: '1', to: '10' },
{ id: 1, text: 'elva', type: MappingType.ValueToText, value: '11' },
];
const value = '10';
expect(getMappedValue(valueMappings, value).text).toEqual('1-10');
});
it('should return rangeToText mapping where value equals from', () => {
const valueMappings: ValueMapping[] = [
{ id: 0, text: '10-20', type: MappingType.RangeToText, from: '10', to: '20' },
{ id: 1, text: 'elva', type: MappingType.ValueToText, value: '11' },
];
const value = '10';
expect(getMappedValue(valueMappings, value).text).toEqual('10-20');
});
it('should return rangeToText mapping where value is between from and to', () => {
const valueMappings: ValueMapping[] = [
{ id: 0, text: '1-20', type: MappingType.RangeToText, from: '1', to: '20' },
{ id: 1, text: 'elva', type: MappingType.ValueToText, value: '11' },
];
const value = '10';
expect(getMappedValue(valueMappings, value).text).toEqual('1-20');
});
it('should map value text to mapping', () => {
const valueMappings: ValueMapping[] = [
{ id: 0, text: '1-20', type: MappingType.RangeToText, from: '1', to: '20' },
{ id: 1, text: 'ELVA', type: MappingType.ValueToText, value: 'elva' },
];
const value = 'elva';
expect(getMappedValue(valueMappings, value).text).toEqual('ELVA');
});
});
| packages/grafana-data/src/utils/valueMappings.test.ts | 0 | https://github.com/grafana/grafana/commit/7d4c51459f4abce8cc23b1dcfb24757e65b18120 | [
0.0001794843265088275,
0.00017729680985212326,
0.00017084687715396285,
0.00017880246741697192,
0.0000025833887775661424
] |
{
"id": 0,
"code_window": [
"{\n",
" \"$schema\": \"https://unpkg.com/knip@next/schema.json\",\n",
"\n",
" \"ignore\": \"**/*.d.ts\",\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"$schema\": \"https://unpkg.com/knip@1/schema.json\",\n"
],
"file_path": "knip.jsonc",
"type": "replace",
"edit_start_line_idx": 1
} | {
"$schema": "https://unpkg.com/knip@next/schema.json",
"ignore": "**/*.d.ts",
"ignoreBinaries": ["cd", "echo", "sh"],
// Only workspaces with a configuration below are analyzed by Knip
"workspaces": {
".": {
"entry": [],
// Configuration options can be overridden individually (necessary here as the default is `cypress/e2e/**/*.cy.{js,jsx,ts,tsx}`).
"cypress": ["cypress.config.js", "cypress/e2e/**/*.{js,ts}"]
},
"client": {
// Files used by Gatsby are handled by Knip's Gatsby plugin (https://github.com/webpro/knip/blob/next/src/plugins/gatsby/README.md)
// The rest are `webpack.entry` files.
"entry": [],
"project": ["**/*.{js,ts,tsx}"],
"webpack": {
"config": "webpack-workers.js",
"entry": [
"src/client/frame-runner.ts",
"src/client/workers/sass-compile.ts",
"src/client/workers/test-evaluator.ts"
]
},
"ignore": ["i18n/schema-validation.*", "**/__mocks__", "**/__fixtures__"]
},
"client/plugins/*": {
"entry": "gatsby-node.js"
},
// This monospace gives a few unused files, so as not to make the node.js-find-unused workflow fail this is still commented out
// Also try --production to find more unused files.
// "tools/ui-components": {
// "entry": ["src/index.ts!", "utils/gen-component-script.ts"],
// "project": ["src/**/*.{ts,tsx}!", "utils/*.ts"]
// },
"tools/scripts/build": {
"entry": ["*.ts"]
}
}
}
| knip.jsonc | 1 | https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d | [
0.3654789924621582,
0.07324843108654022,
0.0001646345917833969,
0.00017872675380203873,
0.1461152732372284
] |
{
"id": 0,
"code_window": [
"{\n",
" \"$schema\": \"https://unpkg.com/knip@next/schema.json\",\n",
"\n",
" \"ignore\": \"**/*.d.ts\",\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"$schema\": \"https://unpkg.com/knip@1/schema.json\",\n"
],
"file_path": "knip.jsonc",
"type": "replace",
"edit_start_line_idx": 1
} | ---
id: 60b69a66b6ddb80858c515b5
title: Paso 64
challengeType: 0
dashedName: step-64
---
# --description--
Dale estilo al elemento con el id `black-round-hat` usando un selector de id. Establezca el `width` en `180px`, el `height` en `150px` y el `background-color` a `rgb(45, 31, 19)`.
# --hints--
Debe tener un selector `#black-round-hat`.
```js
assert(new __helpers.CSSHelp(document).getStyle('#black-round-hat'));
```
Su selector `#black-round-hat` debe tener una propiedad `width` establecida en `180px`.
```js
assert(new __helpers.CSSHelp(document).getStyle('#black-round-hat')?.width === '180px');
```
Su selector `#black-round-hat` debe tener una propiedad `height` establecida en `150px`.
```js
assert(new __helpers.CSSHelp(document).getStyle('#black-round-hat')?.height === '150px');
```
Su selector `#black-round-hat` debe tener una propiedad `background-color` establecida en `rgb(45, 31, 19)`.
```js
assert(new __helpers.CSSHelp(document).getStyle('#black-round-hat')?.backgroundColor === 'rgb(45, 31, 19)');
```
# --seed--
## --seed-contents--
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Picasso Painting</title>
<link rel="stylesheet" href="./styles.css" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">
</head>
<body>
<div id="back-wall"></div>
<div class="characters">
<div id="offwhite-character">
<div id="white-hat"></div>
<div id="black-mask">
<div class="eyes left"></div>
<div class="eyes right"></div>
</div>
<div id="gray-instrument">
<div class="black-dot"></div>
<div class="black-dot"></div>
<div class="black-dot"></div>
<div class="black-dot"></div>
<div class="black-dot"></div>
</div>
<div id="tan-table"></div>
</div>
<div id="black-character">
<div id="black-hat"></div>
<div id="gray-mask">
<div class="eyes left"></div>
<div class="eyes right"></div>
</div>
<div id="white-paper">
<i class="fas fa-music"></i>
<i class="fas fa-music"></i>
<i class="fas fa-music"></i>
<i class="fas fa-music"></i>
</div>
</div>
<div class="blue" id="blue-left"></div>
<div class="blue" id="blue-right"></div>
<div id="orange-character">
<div id="black-round-hat"></div>
<div id="eyes-div">
<div class="eyes left"></div>
<div class="eyes right"></div>
</div>
<div id="triangles">
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
<div class="triangle"></div>
</div>
<div id="guitar">
<div class="guitar" id="guitar-left">
<i class="fas fa-bars"></i>
</div>
<div class="guitar" id="guitar-right">
<i class="fas fa-bars"></i>
</div>
<div id="guitar-neck"></div>
</div>
</div>
</div>
</body>
</html>
```
```css
body {
background-color: rgb(184, 132, 46);
}
#back-wall {
background-color: #8B4513;
width: 100%;
height: 60%;
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
#offwhite-character {
width: 300px;
height: 550px;
background-color: GhostWhite;
position: absolute;
top: 20%;
left: 17.5%;
}
#white-hat {
width: 0;
height: 0;
border-style: solid;
border-width: 0 120px 140px 180px;
border-top-color: transparent;
border-right-color: transparent;
border-bottom-color: GhostWhite;
border-left-color: transparent;
position: absolute;
top: -140px;
left: 0;
}
#black-mask {
width: 100%;
height: 50px;
background-color: rgb(45, 31, 19);
position: absolute;
top: 0;
left: 0;
z-index: 1;
}
#gray-instrument {
width: 15%;
height: 40%;
background-color: rgb(167, 162, 117);
position: absolute;
top: 50px;
left: 125px;
z-index: 1;
}
.black-dot {
width: 10px;
height: 10px;
background-color: rgb(45, 31, 19);
border-radius: 50%;
display: block;
margin: auto;
margin-top: 65%;
}
#tan-table {
width: 450px;
height: 140px;
background-color: #D2691E;
position: absolute;
top: 275px;
left: 15px;
z-index: 1;
}
#black-character {
width: 300px;
height: 500px;
background-color: rgb(45, 31, 19);
position: absolute;
top: 30%;
left: 59%;
}
#black-hat {
width: 0;
height: 0;
border-style: solid;
border-width: 150px 0 0 300px;
border-top-color: transparent;
border-right-color: transparent;
border-bottom-color: transparent;
border-left-color: rgb(45, 31, 19);
position: absolute;
top: -150px;
left: 0;
}
#gray-mask {
width: 150px;
height: 150px;
background-color: rgb(167, 162, 117);
position: absolute;
top: -10px;
left: 70px;
}
#white-paper {
width: 400px;
height: 100px;
background-color: GhostWhite;
position: absolute;
top: 250px;
left: -150px;
z-index: 1;
}
.fa-music {
display: inline-block;
margin-top: 8%;
margin-left: 13%;
}
.blue {
background-color: #1E90FF;
}
#blue-left {
width: 500px;
height: 300px;
position: absolute;
top: 20%;
left: 20%;
}
#blue-right {
width: 400px;
height: 300px;
position: absolute;
top: 50%;
left: 40%;
}
#orange-character {
width: 250px;
height: 550px;
background-color: rgb(240, 78, 42);
position: absolute;
top: 25%;
left: 40%;
}
--fcc-editable-region--
--fcc-editable-region--
```
| curriculum/challenges/espanol/14-responsive-web-design-22/learn-intermediate-css-by-building-a-picasso-painting/60b69a66b6ddb80858c515b5.md | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d | [
0.0001760551822371781,
0.00017054093768820167,
0.00016549947031307966,
0.00017029684386216104,
0.000002671455604286166
] |
{
"id": 0,
"code_window": [
"{\n",
" \"$schema\": \"https://unpkg.com/knip@next/schema.json\",\n",
"\n",
" \"ignore\": \"**/*.d.ts\",\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"$schema\": \"https://unpkg.com/knip@1/schema.json\",\n"
],
"file_path": "knip.jsonc",
"type": "replace",
"edit_start_line_idx": 1
} | ---
id: 587d7da9367417b2b2512b67
title: push の代わりに concat を使用して要素を配列の末尾に追加する
challengeType: 1
forumTopicId: 301226
dashedName: add-elements-to-the-end-of-an-array-using-concat-instead-of-push
---
# --description--
関数型プログラミングで重要なのは、ミューテーションを起こさない関数を作成して使用することです。
一つ前のチャレンジでは、元の配列をミューテートさせずに配列を新しい配列に統合する方法として、`concat` メソッドを紹介しました。 `concat` を `push` メソッドと比較してみましょう。 `push` は、このメソッドが呼び出された配列自体の末尾にアイテムを追加するため、その配列をミューテートさせます。 例を示します。
```js
const arr = [1, 2, 3];
arr.push(4, 5, 6);
```
`arr` の値は `[1, 2, 3, 4, 5, 6]` に変更されます。これは関数型プログラミングに適切な方法ではありません。
`concat` では、ミューテーションの副作用を起こさずに、配列の末尾に新しいアイテムを統合できます。
# --instructions--
`nonMutatingPush` 関数が `concat` を使用して `newItem` を `original` の末尾に統合するよう変更し、`newItem` および `original` がミューテートされないようにしてください。 この関数は配列を返す必要があります。
# --hints--
コードで `concat` メソッドを使用する必要があります。
```js
assert(code.match(/\.concat/g));
```
コードで `push` メソッドを使用しないでください。
```js
assert(!code.match(/\.?[\s\S]*?push/g));
```
`first` 配列を変更しないようにする必要があります。
```js
assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]));
```
`second` 配列を変更しないようにする必要があります。
```js
assert(JSON.stringify(second) === JSON.stringify([4, 5]));
```
`nonMutatingPush([1, 2, 3], [4, 5])` は `[1, 2, 3, 4, 5]` を返す必要があります。
```js
assert(
JSON.stringify(nonMutatingPush([1, 2, 3], [4, 5])) ===
JSON.stringify([1, 2, 3, 4, 5])
);
```
# --seed--
## --seed-contents--
```js
function nonMutatingPush(original, newItem) {
// Only change code below this line
return original.push(newItem);
// Only change code above this line
}
const first = [1, 2, 3];
const second = [4, 5];
nonMutatingPush(first, second);
```
# --solutions--
```js
function nonMutatingPush(original, newItem) {
return original.concat(newItem);
}
const first = [1, 2, 3];
const second = [4, 5];
```
| curriculum/challenges/japanese/02-javascript-algorithms-and-data-structures/functional-programming/add-elements-to-the-end-of-an-array-using-concat-instead-of-push.md | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d | [
0.0004909943090751767,
0.000205458200071007,
0.0001646115124458447,
0.00017044253763742745,
0.00010099521023221314
] |
{
"id": 0,
"code_window": [
"{\n",
" \"$schema\": \"https://unpkg.com/knip@next/schema.json\",\n",
"\n",
" \"ignore\": \"**/*.d.ts\",\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" \"$schema\": \"https://unpkg.com/knip@1/schema.json\",\n"
],
"file_path": "knip.jsonc",
"type": "replace",
"edit_start_line_idx": 1
} | ---
id: 60a3e3396c7b40068ad69990
title: Крок 38
challengeType: 0
dashedName: step-38
---
# --description--
Використайте таку ж саму декларацію `box-shadow` для `.two`, але змініть колір з `#efb762` на `#8f0401`.
# --hints--
Ви повинні встановити властивість `box-shadow` на `0 0 3px 3px #8f0401`.
```js
const hasBoxShadow = new __helpers.CSSHelp(document).getCSSRules().some(x => x.style['box-shadow'] === 'rgb(143, 4, 1) 0px 0px 3px 3px');
assert(hasBoxShadow);
```
Ваш елемент `.two` повинен мати `box-shadow` зі значенням `0 0 3px 3px #8f0401`.
```js
const twoShadow = new __helpers.CSSHelp(document).getStyle('.two')?.getPropertyValue('box-shadow');
assert(twoShadow === 'rgb(143, 4, 1) 0px 0px 3px 3px');
```
# --seed--
## --seed-contents--
```css
.canvas {
width: 500px;
height: 600px;
background-color: #4d0f00;
overflow: hidden;
filter: blur(2px);
}
.frame {
border: 50px solid black;
width: 500px;
padding: 50px;
margin: 20px auto;
}
.one {
width: 425px;
height: 150px;
background-color: #efb762;
margin: 20px auto;
box-shadow: 0 0 3px 3px #efb762;
}
.two {
width: 475px;
height: 200px;
background-color: #8f0401;
margin: 0 auto 20px;
--fcc-editable-region--
--fcc-editable-region--
}
.one, .two {
filter: blur(1px);
}
.three {
width: 91%;
height: 28%;
background-color: #b20403;
margin: auto;
filter: blur(2px);
}
```
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Rothko Painting</title>
<link href="./styles.css" rel="stylesheet">
</head>
<body>
<div class="frame">
<div class="canvas">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</div>
</div>
</body>
</html>
```
| curriculum/challenges/ukrainian/14-responsive-web-design-22/learn-the-css-box-model-by-building-a-rothko-painting/60a3e3396c7b40068ad69990.md | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d | [
0.00017603352898731828,
0.00017245809431187809,
0.00016553638852201402,
0.00017348678375128657,
0.000003401464255148312
] |
{
"id": 1,
"code_window": [
"\n",
" \"ignore\": \"**/*.d.ts\",\n",
" \"ignoreBinaries\": [\"cd\", \"echo\", \"sh\"],\n",
"\n",
" // Only workspaces with a configuration below are analyzed by Knip\n",
" \"workspaces\": {\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "knip.jsonc",
"type": "replace",
"edit_start_line_idx": 4
} | {
"$schema": "https://unpkg.com/knip@next/schema.json",
"ignore": "**/*.d.ts",
"ignoreBinaries": ["cd", "echo", "sh"],
// Only workspaces with a configuration below are analyzed by Knip
"workspaces": {
".": {
"entry": [],
// Configuration options can be overridden individually (necessary here as the default is `cypress/e2e/**/*.cy.{js,jsx,ts,tsx}`).
"cypress": ["cypress.config.js", "cypress/e2e/**/*.{js,ts}"]
},
"client": {
// Files used by Gatsby are handled by Knip's Gatsby plugin (https://github.com/webpro/knip/blob/next/src/plugins/gatsby/README.md)
// The rest are `webpack.entry` files.
"entry": [],
"project": ["**/*.{js,ts,tsx}"],
"webpack": {
"config": "webpack-workers.js",
"entry": [
"src/client/frame-runner.ts",
"src/client/workers/sass-compile.ts",
"src/client/workers/test-evaluator.ts"
]
},
"ignore": ["i18n/schema-validation.*", "**/__mocks__", "**/__fixtures__"]
},
"client/plugins/*": {
"entry": "gatsby-node.js"
},
// This monospace gives a few unused files, so as not to make the node.js-find-unused workflow fail this is still commented out
// Also try --production to find more unused files.
// "tools/ui-components": {
// "entry": ["src/index.ts!", "utils/gen-component-script.ts"],
// "project": ["src/**/*.{ts,tsx}!", "utils/*.ts"]
// },
"tools/scripts/build": {
"entry": ["*.ts"]
}
}
}
| knip.jsonc | 1 | https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d | [
0.905104398727417,
0.18118953704833984,
0.00016600759408902377,
0.00018015954992733896,
0.3619574308395386
] |
{
"id": 1,
"code_window": [
"\n",
" \"ignore\": \"**/*.d.ts\",\n",
" \"ignoreBinaries\": [\"cd\", \"echo\", \"sh\"],\n",
"\n",
" // Only workspaces with a configuration below are analyzed by Knip\n",
" \"workspaces\": {\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "knip.jsonc",
"type": "replace",
"edit_start_line_idx": 4
} | ---
id: a9bd25c716030ec90084d8a1
title: Chunky Monkey
challengeType: 1
forumTopicId: 16005
dashedName: chunky-monkey
---
# --description--
Write a function that splits an array (first argument) into groups the length of `size` (second argument) and returns them as a two-dimensional array.
# --hints--
`chunkArrayInGroups(["a", "b", "c", "d"], 2)` should return `[["a", "b"], ["c", "d"]]`.
```js
assert.deepEqual(chunkArrayInGroups(['a', 'b', 'c', 'd'], 2), [
['a', 'b'],
['c', 'd']
]);
```
`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3)` should return `[[0, 1, 2], [3, 4, 5]]`.
```js
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3), [
[0, 1, 2],
[3, 4, 5]
]);
```
`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2)` should return `[[0, 1], [2, 3], [4, 5]]`.
```js
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2), [
[0, 1],
[2, 3],
[4, 5]
]);
```
`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4)` should return `[[0, 1, 2, 3], [4, 5]]`.
```js
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4), [
[0, 1, 2, 3],
[4, 5]
]);
```
`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3)` should return `[[0, 1, 2], [3, 4, 5], [6]]`.
```js
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3), [
[0, 1, 2],
[3, 4, 5],
[6]
]);
```
`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4)` should return `[[0, 1, 2, 3], [4, 5, 6, 7], [8]]`.
```js
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4), [
[0, 1, 2, 3],
[4, 5, 6, 7],
[8]
]);
```
`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2)` should return `[[0, 1], [2, 3], [4, 5], [6, 7], [8]]`.
```js
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2), [
[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8]
]);
```
# --seed--
## --seed-contents--
```js
function chunkArrayInGroups(arr, size) {
return arr;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
```
# --solutions--
```js
function chunkArrayInGroups(arr, size) {
let out = [];
for (let i = 0; i < arr.length; i += size) {
out.push(arr.slice(i, i + size));
}
return out;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
```
| curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/chunky-monkey.md | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d | [
0.0001837495219660923,
0.00017190311336889863,
0.00016271173080895096,
0.00017017677600961179,
0.000006053052402421599
] |
{
"id": 1,
"code_window": [
"\n",
" \"ignore\": \"**/*.d.ts\",\n",
" \"ignoreBinaries\": [\"cd\", \"echo\", \"sh\"],\n",
"\n",
" // Only workspaces with a configuration below are analyzed by Knip\n",
" \"workspaces\": {\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "knip.jsonc",
"type": "replace",
"edit_start_line_idx": 4
} | ---
id: 60b69a66b6ddb80858c515a8
title: 步骤 51
challengeType: 0
dashedName: step-51
---
# --description--
使用类选择器来定位具有 `blue` 类的新元素。 将 `background-color` 设置为 `#1E90FF`。
# --hints--
你应该有一个 `.blue` 选择器。
```js
assert(new __helpers.CSSHelp(document).getStyle('.blue'));
```
你的 `.blue` 选择器应该有一个 `background-color` 属性设置为 `#1E90FF`。
```js
assert(new __helpers.CSSHelp(document).getStyle('.blue')?.backgroundColor === 'rgb(30, 144, 255)');
```
# --seed--
## --seed-contents--
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Picasso Painting</title>
<link rel="stylesheet" href="./styles.css" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">
</head>
<body>
<div id="back-wall"></div>
<div class="characters">
<div id="offwhite-character">
<div id="white-hat"></div>
<div id="black-mask">
<div class="eyes left"></div>
<div class="eyes right"></div>
</div>
<div id="gray-instrument">
<div class="black-dot"></div>
<div class="black-dot"></div>
<div class="black-dot"></div>
<div class="black-dot"></div>
<div class="black-dot"></div>
</div>
<div id="tan-table"></div>
</div>
<div id="black-character">
<div id="black-hat"></div>
<div id="gray-mask">
<div class="eyes left"></div>
<div class="eyes right"></div>
</div>
<div id="white-paper">
<i class="fas fa-music"></i>
<i class="fas fa-music"></i>
<i class="fas fa-music"></i>
<i class="fas fa-music"></i>
</div>
</div>
<div class="blue" id="blue-left"></div>
<div class="blue" id="blue-right"></div>
</div>
</body>
</html>
```
```css
body {
background-color: rgb(184, 132, 46);
}
#back-wall {
background-color: #8B4513;
width: 100%;
height: 60%;
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
#offwhite-character {
width: 300px;
height: 550px;
background-color: GhostWhite;
position: absolute;
top: 20%;
left: 17.5%;
}
#white-hat {
width: 0;
height: 0;
border-style: solid;
border-width: 0 120px 140px 180px;
border-top-color: transparent;
border-right-color: transparent;
border-bottom-color: GhostWhite;
border-left-color: transparent;
position: absolute;
top: -140px;
left: 0;
}
#black-mask {
width: 100%;
height: 50px;
background-color: rgb(45, 31, 19);
position: absolute;
top: 0;
left: 0;
z-index: 1;
}
#gray-instrument {
width: 15%;
height: 40%;
background-color: rgb(167, 162, 117);
position: absolute;
top: 50px;
left: 125px;
z-index: 1;
}
.black-dot {
width: 10px;
height: 10px;
background-color: rgb(45, 31, 19);
border-radius: 50%;
display: block;
margin: auto;
margin-top: 65%;
}
#tan-table {
width: 450px;
height: 140px;
background-color: #D2691E;
position: absolute;
top: 275px;
left: 15px;
z-index: 1;
}
#black-character {
width: 300px;
height: 500px;
background-color: rgb(45, 31, 19);
position: absolute;
top: 30%;
left: 59%;
}
#black-hat {
width: 0;
height: 0;
border-style: solid;
border-width: 150px 0 0 300px;
border-top-color: transparent;
border-right-color: transparent;
border-bottom-color: transparent;
border-left-color: rgb(45, 31, 19);
position: absolute;
top: -150px;
left: 0;
}
#gray-mask {
width: 150px;
height: 150px;
background-color: rgb(167, 162, 117);
position: absolute;
top: -10px;
left: 70px;
}
#white-paper {
width: 400px;
height: 100px;
background-color: GhostWhite;
position: absolute;
top: 250px;
left: -150px;
z-index: 1;
}
.fa-music {
display: inline-block;
margin-top: 8%;
margin-left: 13%;
}
--fcc-editable-region--
--fcc-editable-region--
```
| curriculum/challenges/chinese/14-responsive-web-design-22/learn-intermediate-css-by-building-a-picasso-painting/60b69a66b6ddb80858c515a8.md | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d | [
0.00017695558199193329,
0.0001725916808936745,
0.00016552676970604807,
0.00017339726036880165,
0.0000030065821192692965
] |
{
"id": 1,
"code_window": [
"\n",
" \"ignore\": \"**/*.d.ts\",\n",
" \"ignoreBinaries\": [\"cd\", \"echo\", \"sh\"],\n",
"\n",
" // Only workspaces with a configuration below are analyzed by Knip\n",
" \"workspaces\": {\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "knip.jsonc",
"type": "replace",
"edit_start_line_idx": 4
} | ---
id: 5a9d7286424fe3d0e10cad13
title: CSS 変数にフォールバック値を追加する
challengeType: 0
videoUrl: 'https://scrimba.com/c/c6bDNfp'
forumTopicId: 301084
dashedName: attach-a-fallback-value-to-a-css-variable
---
# --description--
CSS プロパティの値として変数を使用する場合、指定された変数が無効な場合にブラウザが代わりに使用するフォールバック値を付けることができます。
**注:** このフォールバックはブラウザの互換性を高めるためのものではなく、また IE では動作しません。 むしろ、ブラウザが変数を見つけられない場合に表示する色を持つようにするために使用されます。
方法は次のとおりです:
```css
background: var(--penguin-skin, black);
```
これで、もし変数が設定されていなかった場合に背景色を `black` にすることができます。 これがデバッグに役立つことに注目してください。
# --instructions--
`.penguin-top` クラスと `.penguin-bottom` クラスに与えられている変数に問題があるようですね。 誤字を直すのではなく、`.penguin-top` クラスと `.penguin-bottom` クラスの `background` プロパティにフォールバック値 `black` を追加してみましょう。
# --hints--
`penguin-top` クラスの `background` プロパティのフォールバック値に `black` を使用してください。
```js
assert(
code.match(
/.penguin-top\s*?{[\s\S]*background\s*?:\s*?var\(\s*?--pengiun-skin\s*?,\s*?black\s*?\)\s*?;[\s\S]*}[\s\S]*.penguin-bottom\s{/gi
)
);
```
`penguin-bottom` クラスの `background` プロパティのフォールバック値に `black` を使用してください。
```js
assert(
code.match(
/.penguin-bottom\s*?{[\s\S]*background\s*?:\s*?var\(\s*?--pengiun-skin\s*?,\s*?black\s*?\)\s*?;[\s\S]*}/gi
)
);
```
# --seed--
## --seed-contents--
```html
<style>
.penguin {
--penguin-skin: black;
--penguin-belly: gray;
--penguin-beak: yellow;
position: relative;
margin: auto;
display: block;
margin-top: 5%;
width: 300px;
height: 300px;
}
.penguin-top {
top: 10%;
left: 25%;
/* Change code below this line */
background: var(--pengiun-skin);
/* Change code above this line */
width: 50%;
height: 45%;
border-radius: 70% 70% 60% 60%;
}
.penguin-bottom {
top: 40%;
left: 23.5%;
/* Change code below this line */
background: var(--pengiun-skin);
/* Change code above this line */
width: 53%;
height: 45%;
border-radius: 70% 70% 100% 100%;
}
.right-hand {
top: 0%;
left: -5%;
background: var(--penguin-skin, black);
width: 30%;
height: 60%;
border-radius: 30% 30% 120% 30%;
transform: rotate(45deg);
z-index: -1;
}
.left-hand {
top: 0%;
left: 75%;
background: var(--penguin-skin, black);
width: 30%;
height: 60%;
border-radius: 30% 30% 30% 120%;
transform: rotate(-45deg);
z-index: -1;
}
.right-cheek {
top: 15%;
left: 35%;
background: var(--penguin-belly, white);
width: 60%;
height: 70%;
border-radius: 70% 70% 60% 60%;
}
.left-cheek {
top: 15%;
left: 5%;
background: var(--penguin-belly, white);
width: 60%;
height: 70%;
border-radius: 70% 70% 60% 60%;
}
.belly {
top: 60%;
left: 2.5%;
background: var(--penguin-belly, white);
width: 95%;
height: 100%;
border-radius: 120% 120% 100% 100%;
}
.right-feet {
top: 85%;
left: 60%;
background: var(--penguin-beak, orange);
width: 15%;
height: 30%;
border-radius: 50% 50% 50% 50%;
transform: rotate(-80deg);
z-index: -2222;
}
.left-feet {
top: 85%;
left: 25%;
background: var(--penguin-beak, orange);
width: 15%;
height: 30%;
border-radius: 50% 50% 50% 50%;
transform: rotate(80deg);
z-index: -2222;
}
.right-eye {
top: 45%;
left: 60%;
background: black;
width: 15%;
height: 17%;
border-radius: 50%;
}
.left-eye {
top: 45%;
left: 25%;
background: black;
width: 15%;
height: 17%;
border-radius: 50%;
}
.sparkle {
top: 25%;
left: 15%;
background: white;
width: 35%;
height: 35%;
border-radius: 50%;
}
.blush-right {
top: 65%;
left: 15%;
background: pink;
width: 15%;
height: 10%;
border-radius: 50%;
}
.blush-left {
top: 65%;
left: 70%;
background: pink;
width: 15%;
height: 10%;
border-radius: 50%;
}
.beak-top {
top: 60%;
left: 40%;
background: var(--penguin-beak, orange);
width: 20%;
height: 10%;
border-radius: 50%;
}
.beak-bottom {
top: 65%;
left: 42%;
background: var(--penguin-beak, orange);
width: 16%;
height: 10%;
border-radius: 50%;
}
body {
background: #c6faf1;
}
.penguin * {
position: absolute;
}
</style>
<div class="penguin">
<div class="penguin-bottom">
<div class="right-hand"></div>
<div class="left-hand"></div>
<div class="right-feet"></div>
<div class="left-feet"></div>
</div>
<div class="penguin-top">
<div class="right-cheek"></div>
<div class="left-cheek"></div>
<div class="belly"></div>
<div class="right-eye">
<div class="sparkle"></div>
</div>
<div class="left-eye">
<div class="sparkle"></div>
</div>
<div class="blush-right"></div>
<div class="blush-left"></div>
<div class="beak-top"></div>
<div class="beak-bottom"></div>
</div>
</div>
```
# --solutions--
```html
<style>
.penguin-top {
background: var(--pengiun-skin, black);
}
.penguin-bottom {
background: var(--pengiun-skin, black);
}
</style>
```
| curriculum/challenges/japanese/01-responsive-web-design/basic-css/attach-a-fallback-value-to-a-css-variable.md | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d | [
0.00017853853933047503,
0.00017200781439896673,
0.00016442891501355916,
0.00017303612548857927,
0.0000032975640351651236
] |
{
"id": 2,
"code_window": [
" // Only workspaces with a configuration below are analyzed by Knip\n",
" \"workspaces\": {\n",
" \".\": {\n",
" \"entry\": [],\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" // No custom entry/project files in root workspace to not interfere with workspaces that are not set up yet\n"
],
"file_path": "knip.jsonc",
"type": "add",
"edit_start_line_idx": 9
} | {
"$schema": "https://unpkg.com/knip@next/schema.json",
"ignore": "**/*.d.ts",
"ignoreBinaries": ["cd", "echo", "sh"],
// Only workspaces with a configuration below are analyzed by Knip
"workspaces": {
".": {
"entry": [],
// Configuration options can be overridden individually (necessary here as the default is `cypress/e2e/**/*.cy.{js,jsx,ts,tsx}`).
"cypress": ["cypress.config.js", "cypress/e2e/**/*.{js,ts}"]
},
"client": {
// Files used by Gatsby are handled by Knip's Gatsby plugin (https://github.com/webpro/knip/blob/next/src/plugins/gatsby/README.md)
// The rest are `webpack.entry` files.
"entry": [],
"project": ["**/*.{js,ts,tsx}"],
"webpack": {
"config": "webpack-workers.js",
"entry": [
"src/client/frame-runner.ts",
"src/client/workers/sass-compile.ts",
"src/client/workers/test-evaluator.ts"
]
},
"ignore": ["i18n/schema-validation.*", "**/__mocks__", "**/__fixtures__"]
},
"client/plugins/*": {
"entry": "gatsby-node.js"
},
// This monospace gives a few unused files, so as not to make the node.js-find-unused workflow fail this is still commented out
// Also try --production to find more unused files.
// "tools/ui-components": {
// "entry": ["src/index.ts!", "utils/gen-component-script.ts"],
// "project": ["src/**/*.{ts,tsx}!", "utils/*.ts"]
// },
"tools/scripts/build": {
"entry": ["*.ts"]
}
}
}
| knip.jsonc | 1 | https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d | [
0.9887864589691162,
0.198003351688385,
0.00016475455777253956,
0.00018106035713572055,
0.3953916132450104
] |
{
"id": 2,
"code_window": [
" // Only workspaces with a configuration below are analyzed by Knip\n",
" \"workspaces\": {\n",
" \".\": {\n",
" \"entry\": [],\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" // No custom entry/project files in root workspace to not interfere with workspaces that are not set up yet\n"
],
"file_path": "knip.jsonc",
"type": "add",
"edit_start_line_idx": 9
} | ---
id: 5eb3e4b5f629b9a07429a5d2
title: SHA-1
challengeType: 1
forumTopicId: 385326
dashedName: sha-1
---
# --description--
**SHA-1** 或称 **SHA1** 是一种单向散列函数,它产生数据的 160 位摘要信息。
SHA-1 经常出现在安全协议中;例如,许多 HTTPS 网站使用 SHA-1 来保护他们的连接。
BitTorrent 使用 SHA-1 来验证下载内容。
Git 和 Mercurial 使用 SHA-1 摘要来核验提交内容。
A US government standard, <a href="https://rosettacode.org/wiki/SHA-1/FIPS-180-1" target="_blank" rel="noopener noreferrer nofollow">FIPS 180-1</a>, defines SHA-1.
# --instructions--
写一个函数返回给定字符串的 SHA-1 消息摘要。
# --hints--
`SHA1` 应该是一个函数。
```js
assert(typeof SHA1 === 'function');
```
`SHA1("abc")` 应该返回一个字符串。
```js
assert(typeof SHA1('abc') === 'string');
```
`SHA1("abc")` 应该返回 `"a9993e364706816aba3e25717850c26c9cd0d89d"`
```js
assert.equal(SHA1('abc'), 'a9993e364706816aba3e25717850c26c9cd0d89d');
```
`SHA1("Rosetta Code")` 应该返回 `"48c98f7e5a6e736d790ab740dfc3f51a61abe2b5"`
```js
assert.equal(SHA1('Rosetta Code'), '48c98f7e5a6e736d790ab740dfc3f51a61abe2b5');
```
`SHA1("Hello world")` 应该返回 `"7b502c3a1f48c8609ae212cdfb639dee39673f5e"`
```js
assert.equal(SHA1('Hello world'), '7b502c3a1f48c8609ae212cdfb639dee39673f5e');
```
`SHA1("Programming")` 应该返回 `"d1a946bf8b2f2a7292c250063ee28989d742cd4b"`
```js
assert.equal(SHA1('Programming'), 'd1a946bf8b2f2a7292c250063ee28989d742cd4b');
```
`SHA1("is Awesome")` 应该返回 `"6537205da59c72b57ed3881843c2d24103d683a3"`
```js
assert.equal(SHA1('is Awesome'), '6537205da59c72b57ed3881843c2d24103d683a3');
```
# --seed--
## --seed-contents--
```js
function SHA1(input) {
}
```
# --solutions--
```js
function SHA1(input) {
var hexcase = 0;
var b64pad = '';
var chrsz = 8;
function hex_sha1(s) {
return binb2hex(core_sha1(str2binb(s), s.length * chrsz));
}
function core_sha1(x, len) {
x[len >> 5] |= 0x80 << (24 - (len % 32));
x[(((len + 64) >> 9) << 4) + 15] = len;
var w = Array(80);
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
var e = -1009589776;
for (var i = 0; i < x.length; i += 16) {
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
var olde = e;
for (var j = 0; j < 80; j++) {
if (j < 16) w[j] = x[i + j];
else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
var t = safe_add(
safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
safe_add(safe_add(e, w[j]), sha1_kt(j))
);
e = d;
d = c;
c = rol(b, 30);
b = a;
a = t;
}
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
e = safe_add(e, olde);
}
return Array(a, b, c, d, e);
}
function sha1_ft(t, b, c, d) {
if (t < 20) return (b & c) | (~b & d);
if (t < 40) return b ^ c ^ d;
if (t < 60) return (b & c) | (b & d) | (c & d);
return b ^ c ^ d;
}
function sha1_kt(t) {
return t < 20
? 1518500249
: t < 40
? 1859775393
: t < 60
? -1894007588
: -899497514;
}
function safe_add(x, y) {
var lsw = (x & 0xffff) + (y & 0xffff);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xffff);
}
function rol(num, cnt) {
return (num << cnt) | (num >>> (32 - cnt));
}
function str2binb(str) {
var bin = Array();
var mask = (1 << chrsz) - 1;
for (var i = 0; i < str.length * chrsz; i += chrsz)
bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - (i % 32));
return bin;
}
function binb2hex(binarray) {
var hex_tab = hexcase ? '0123456789ABCDEF' : '0123456789abcdef';
var str = '';
for (var i = 0; i < binarray.length * 4; i++) {
str +=
hex_tab.charAt((binarray[i >> 2] >> ((3 - (i % 4)) * 8 + 4)) & 0xf) +
hex_tab.charAt((binarray[i >> 2] >> ((3 - (i % 4)) * 8)) & 0xf);
}
return str;
}
return hex_sha1(input);
}
```
| curriculum/challenges/chinese/10-coding-interview-prep/rosetta-code/sha-1.md | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d | [
0.00018353450286667794,
0.00017188789206556976,
0.00016576447524130344,
0.0001716905098874122,
0.000003615553396230098
] |
{
"id": 2,
"code_window": [
" // Only workspaces with a configuration below are analyzed by Knip\n",
" \"workspaces\": {\n",
" \".\": {\n",
" \"entry\": [],\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" // No custom entry/project files in root workspace to not interfere with workspaces that are not set up yet\n"
],
"file_path": "knip.jsonc",
"type": "add",
"edit_start_line_idx": 9
} | ---
id: 5a24c314108439a4d4036173
title: 用 this.setState 設置狀態
challengeType: 6
forumTopicId: 301412
dashedName: set-state-with-this-setstate
---
# --description--
前面的挑戰涵蓋了組件的 `state` 以及如何在 `constructor` 中初始化 state。 還有一種方法可以更改組件的 `state`。 React 提供了 `setState` 方法來更新組件的 `state`。 在組件類中調用 `setState` 方法如下所示:`this.setState()`,傳入鍵值對的對象, 其中鍵是 state 屬性,值是更新後的 state 數據。 例如,如果我們在 state 中存儲 `username`,並想要更新它,代碼如下所示:
```jsx
this.setState({
username: 'Lewis'
});
```
React 要求永遠不要直接修改 `state`,而是在 state 發生改變時始終使用 `this.setState()`。 此外,應該注意,React 可以批量處理多個 state 更新以提高性能。 這意味着通過 `setState` 方法進行的 state 更新可以是異步的。 `setState` 方法有一種替代語法可以解決異步問題, 雖然這很少用到,但是最好還是記住它! 請查閱我們的 <a href="https://www.freecodecamp.org/news/what-is-state-in-react-explained-with-examples/" target="_blank" rel="noopener noreferrer nofollow">React 文章</a>瞭解更多詳情。
# --instructions--
代碼編輯器中有一個 `button` 元素,它有一個 `onClick()` handler。 當 `button` 在瀏覽器中接收到單擊事件時觸發此 handler,並運行 `MyComponent` 中定義的 `handleClick` 方法。 在 `handleClick` 方法中,使用 `this.setState()` 更新組件的 `state`。 設置 `state` 中的 `name` 屬性爲字符串 `React Rocks!`。
單擊按鈕查看渲染的 state 的更新。 如果不完全理解單擊處理程序代碼在此時的工作方式,請不要擔心。 在接下來的挑戰中會有講述。
# --hints--
`MyComponent` 的 state 應該使用鍵值對 `{ name: Initial State }` 來初始化。
```js
assert(
Enzyme.mount(React.createElement(MyComponent)).state('name') ===
'Initial State'
);
```
`MyComponent` 應該渲染一個 `h1` 標題元素。
```js
assert(Enzyme.mount(React.createElement(MyComponent)).find('h1').length === 1);
```
渲染的 `h1` 標題元素應包含從組件狀態渲染的文本。
```js
async () => {
const waitForIt = (fn) =>
new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250));
const mockedComponent = Enzyme.mount(React.createElement(MyComponent));
const first = () => {
mockedComponent.setState({ name: 'TestName' });
return waitForIt(() => mockedComponent.html());
};
const firstValue = await first();
assert(/<h1>TestName<\/h1>/.test(firstValue));
};
```
調用 `MyComponent` 的 `handleClick` 方法應該將 state 的 name 屬性設置爲 `React Rocks!`。
```js
async () => {
const waitForIt = (fn) =>
new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250));
const mockedComponent = Enzyme.mount(React.createElement(MyComponent));
const first = () => {
mockedComponent.setState({ name: 'Before' });
return waitForIt(() => mockedComponent.state('name'));
};
const second = () => {
mockedComponent.instance().handleClick();
return waitForIt(() => mockedComponent.state('name'));
};
const firstValue = await first();
const secondValue = await second();
assert(firstValue === 'Before' && secondValue === 'React Rocks!');
};
```
# --seed--
## --after-user-code--
```jsx
ReactDOM.render(<MyComponent />, document.getElementById('root'))
```
## --seed-contents--
```jsx
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'Initial State'
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
// Change code below this line
// Change code above this line
}
render() {
return (
<div>
<button onClick={this.handleClick}>Click Me</button>
<h1>{this.state.name}</h1>
</div>
);
}
};
```
# --solutions--
```jsx
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'Initial State'
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
// Change code below this line
this.setState({
name: 'React Rocks!'
});
// Change code above this line
}
render() {
return (
<div>
<button onClick = {this.handleClick}>Click Me</button>
<h1>{this.state.name}</h1>
</div>
);
}
};
```
| curriculum/challenges/chinese-traditional/03-front-end-development-libraries/react/set-state-with-this.setstate.md | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d | [
0.0013252634089440107,
0.00024841894628480077,
0.00016505050007253885,
0.00017063507402781397,
0.00028782847221009433
] |
{
"id": 2,
"code_window": [
" // Only workspaces with a configuration below are analyzed by Knip\n",
" \"workspaces\": {\n",
" \".\": {\n",
" \"entry\": [],\n"
],
"labels": [
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" // No custom entry/project files in root workspace to not interfere with workspaces that are not set up yet\n"
],
"file_path": "knip.jsonc",
"type": "add",
"edit_start_line_idx": 9
} | ---
id: 637f4e8772c65bc8e73dfe2d
videoId: gW6cBZLUk6M
title: Working With Text Question G
challengeType: 15
dashedName: working-with-text-question-g
---
# --description--
HTML comments are not visible to the browser; they allow us to comment on your code so that other developers or your future selves can read them and get some context about something that might not be clear in the code.
Writing an HTML comment is simple: You just enclose the comment with `<!--` and `-->`tags. For example:
```html
<h1> View the html to see the hidden comments </h1>
<!-- I am a html comment -->
<p>Some paragraph text</p>
<!-- I am another html comment -->
```
# --question--
## --assignment--
To get some practice working with text in HTML, create a plain blog article page which uses different headings, uses paragraphs, and has some text in the paragraphs bolded and italicized. You can use [Lorem Ipsum](https://loremipsum.io) to generate dummy text, in place of real text as you build your sites.
## --text--
How do you create HTML comments?
## --answers--
`/* This is an HTML comment */`
---
`<!-- This is an HTML comment -->`
---
`<-- This is an HTML comment --!>`
## --video-solution--
2
| curriculum/challenges/espanol/10-coding-interview-prep/the-odin-project/working-with-text-question-g.md | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d | [
0.0001759853766998276,
0.00017089259927161038,
0.00016644330753479153,
0.0001682431757217273,
0.0000041636949390522204
] |
{
"id": 3,
"code_window": [
" \"entry\": [],\n",
" // Configuration options can be overridden individually (necessary here as the default is `cypress/e2e/**/*.cy.{js,jsx,ts,tsx}`).\n",
" \"cypress\": [\"cypress.config.js\", \"cypress/e2e/**/*.{js,ts}\"]\n",
" },\n",
" \"client\": {\n",
" // Files used by Gatsby are handled by Knip's Gatsby plugin (https://github.com/webpro/knip/blob/next/src/plugins/gatsby/README.md)\n",
" // The rest are `webpack.entry` files.\n",
" \"entry\": [],\n",
" \"project\": [\"**/*.{js,ts,tsx}\"],\n",
" \"webpack\": {\n",
" \"config\": \"webpack-workers.js\",\n",
" \"entry\": [\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" \"cypress\": {\n",
" // Override all Cypress entry patterns as (only) spec paths don't match the default\n"
],
"file_path": "knip.jsonc",
"type": "replace",
"edit_start_line_idx": 10
} | {
"$schema": "https://unpkg.com/knip@next/schema.json",
"ignore": "**/*.d.ts",
"ignoreBinaries": ["cd", "echo", "sh"],
// Only workspaces with a configuration below are analyzed by Knip
"workspaces": {
".": {
"entry": [],
// Configuration options can be overridden individually (necessary here as the default is `cypress/e2e/**/*.cy.{js,jsx,ts,tsx}`).
"cypress": ["cypress.config.js", "cypress/e2e/**/*.{js,ts}"]
},
"client": {
// Files used by Gatsby are handled by Knip's Gatsby plugin (https://github.com/webpro/knip/blob/next/src/plugins/gatsby/README.md)
// The rest are `webpack.entry` files.
"entry": [],
"project": ["**/*.{js,ts,tsx}"],
"webpack": {
"config": "webpack-workers.js",
"entry": [
"src/client/frame-runner.ts",
"src/client/workers/sass-compile.ts",
"src/client/workers/test-evaluator.ts"
]
},
"ignore": ["i18n/schema-validation.*", "**/__mocks__", "**/__fixtures__"]
},
"client/plugins/*": {
"entry": "gatsby-node.js"
},
// This monospace gives a few unused files, so as not to make the node.js-find-unused workflow fail this is still commented out
// Also try --production to find more unused files.
// "tools/ui-components": {
// "entry": ["src/index.ts!", "utils/gen-component-script.ts"],
// "project": ["src/**/*.{ts,tsx}!", "utils/*.ts"]
// },
"tools/scripts/build": {
"entry": ["*.ts"]
}
}
}
| knip.jsonc | 1 | https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d | [
0.9977931976318359,
0.1997031420469284,
0.0001642109709791839,
0.00018075332627631724,
0.39904502034187317
] |
{
"id": 3,
"code_window": [
" \"entry\": [],\n",
" // Configuration options can be overridden individually (necessary here as the default is `cypress/e2e/**/*.cy.{js,jsx,ts,tsx}`).\n",
" \"cypress\": [\"cypress.config.js\", \"cypress/e2e/**/*.{js,ts}\"]\n",
" },\n",
" \"client\": {\n",
" // Files used by Gatsby are handled by Knip's Gatsby plugin (https://github.com/webpro/knip/blob/next/src/plugins/gatsby/README.md)\n",
" // The rest are `webpack.entry` files.\n",
" \"entry\": [],\n",
" \"project\": [\"**/*.{js,ts,tsx}\"],\n",
" \"webpack\": {\n",
" \"config\": \"webpack-workers.js\",\n",
" \"entry\": [\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" \"cypress\": {\n",
" // Override all Cypress entry patterns as (only) spec paths don't match the default\n"
],
"file_path": "knip.jsonc",
"type": "replace",
"edit_start_line_idx": 10
} | ---
id: 5dfa22d1b521be39a3de7be0
title: Step 12
challengeType: 0
dashedName: step-12
---
# --description--
In the previous step you turned the words `link to cat pictures` into a link by placing them between opening and closing anchor (`a`) tags. You can do the same to words inside of an element, such as a `p` element.
In the text of your `p` element, turn the words `cat photos` into a link to `https://freecatphotoapp.com` by adding opening and closing anchor (`a`) tags around these words.
# --hints--
You should nest a new anchor (`a`) element within the `p` element.
```js
assert($('p > a').length);
```
The link's `href` value should be `https://freecatphotoapp.com`. You have either omitted the `href` value or have a typo.
```js
const nestedAnchor = $('p > a')[0];
assert(
nestedAnchor.getAttribute('href') === 'https://freecatphotoapp.com'
);
```
The link's text should be `cat photos`. You have either omitted the text or have a typo.
```js
const nestedAnchor = $('p > a')[0];
assert(
nestedAnchor.innerText.toLowerCase().replace(/\s+/g, ' ') === 'cat photos'
);
```
After nesting the anchor (`a`) element, the only `p` element content visible in the browser should be `See more cat photos in our gallery.` Double check the text, spacing, or punctuation of both the `p` and nested anchor element.
```js
const pText = document
.querySelector('p')
.innerText.toLowerCase()
.replace(/\s+/g, ' ');
assert(pText.match(/see more cat photos in our gallery\.?$/));
```
# --seed--
## --seed-contents--
```html
<html>
<body>
<main>
<h1>CatPhotoApp</h1>
<h2>Cat Photos</h2>
<!-- TODO: Add link to cat photos -->
--fcc-editable-region--
<p>See more cat photos in our gallery.</p>
<a href="https://freecatphotoapp.com">link to cat pictures</a>
--fcc-editable-region--
<img src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/relaxing-cat.jpg" alt="A cute orange cat lying on its back.">
</main>
</body>
</html>
```
| curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5dfa22d1b521be39a3de7be0.md | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d | [
0.00017530706827528775,
0.00017160185961984098,
0.00016486032109241933,
0.00017178678535856307,
0.000002846799816325074
] |
{
"id": 3,
"code_window": [
" \"entry\": [],\n",
" // Configuration options can be overridden individually (necessary here as the default is `cypress/e2e/**/*.cy.{js,jsx,ts,tsx}`).\n",
" \"cypress\": [\"cypress.config.js\", \"cypress/e2e/**/*.{js,ts}\"]\n",
" },\n",
" \"client\": {\n",
" // Files used by Gatsby are handled by Knip's Gatsby plugin (https://github.com/webpro/knip/blob/next/src/plugins/gatsby/README.md)\n",
" // The rest are `webpack.entry` files.\n",
" \"entry\": [],\n",
" \"project\": [\"**/*.{js,ts,tsx}\"],\n",
" \"webpack\": {\n",
" \"config\": \"webpack-workers.js\",\n",
" \"entry\": [\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" \"cypress\": {\n",
" // Override all Cypress entry patterns as (only) spec paths don't match the default\n"
],
"file_path": "knip.jsonc",
"type": "replace",
"edit_start_line_idx": 10
} | ---
id: 5d822fd413a79914d39e992a
title: Paso 97
challengeType: 0
dashedName: step-97
---
# --description--
Proporcione a `.fb4b` un `width` de `100%` y `height` de `89%`.
# --hints--
Debe dar a `.fb4b` un `width` de `100%`.
```js
assert.equal(new __helpers.CSSHelp(document).getStyle(".fb4b")?.width, "100%");
```
Debe dar a `.fb4b` un `height` de `89%`.
```js
assert.equal(new __helpers.CSSHelp(document).getStyle(".fb4b")?.height, "89%");
```
# --seed--
## --seed-contents--
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>City Skyline</title>
<link href="styles.css" rel="stylesheet" />
</head>
<body>
<div class="background-buildings">
<div></div>
<div></div>
<div class="bb1 building-wrap">
<div class="bb1a bb1-window"></div>
<div class="bb1b bb1-window"></div>
<div class="bb1c bb1-window"></div>
<div class="bb1d"></div>
</div>
<div class="bb2">
<div class="bb2a"></div>
<div class="bb2b"></div>
</div>
<div class="bb3"></div>
<div></div>
<div class="bb4 building-wrap">
<div class="bb4a"></div>
<div class="bb4b"></div>
<div class="bb4c window-wrap">
<div class="bb4-window"></div>
<div class="bb4-window"></div>
<div class="bb4-window"></div>
<div class="bb4-window"></div>
</div>
</div>
<div></div>
<div></div>
</div>
<div class="foreground-buildings">
<div></div>
<div></div>
<div class="fb1 building-wrap">
<div class="fb1a"></div>
<div class="fb1b"></div>
<div class="fb1c"></div>
</div>
<div class="fb2">
<div class="fb2a"></div>
<div class="fb2b window-wrap">
<div class="fb2-window"></div>
<div class="fb2-window"></div>
<div class="fb2-window"></div>
</div>
</div>
<div></div>
<div class="fb3 building-wrap">
<div class="fb3a window-wrap">
<div class="fb3-window"></div>
<div class="fb3-window"></div>
<div class="fb3-window"></div>
</div>
<div class="fb3b"></div>
<div class="fb3a"></div>
<div class="fb3b"></div>
</div>
<div class="fb4">
<div class="fb4a"></div>
<div class="fb4b"></div>
</div>
<div class="fb5"></div>
<div class="fb6"></div>
<div></div>
<div></div>
</div>
</body>
</html>
```
```css
:root {
--building-color1: #aa80ff;
--building-color2: #66cc99;
--building-color3: #cc6699;
--building-color4: #538cc6;
--window-color1: #bb99ff;
--window-color2: #8cd9b3;
--window-color3: #d98cb3;
--window-color4: #8cb3d9;
}
* {
border: 1px solid black;
box-sizing: border-box;
}
body {
height: 100vh;
margin: 0;
overflow: hidden;
}
.background-buildings, .foreground-buildings {
width: 100%;
height: 100%;
display: flex;
align-items: flex-end;
justify-content: space-evenly;
position: absolute;
top: 0;
}
.building-wrap {
display: flex;
flex-direction: column;
align-items: center;
}
.window-wrap {
display: flex;
align-items: center;
justify-content: space-evenly;
}
/* BACKGROUND BUILDINGS - "bb" stands for "background building" */
.bb1 {
width: 10%;
height: 70%;
}
.bb1a {
width: 70%;
}
.bb1b {
width: 80%;
}
.bb1c {
width: 90%;
}
.bb1d {
width: 100%;
height: 70%;
background: linear-gradient(
var(--building-color1) 50%,
var(--window-color1)
);
}
.bb1-window {
height: 10%;
background: linear-gradient(
var(--building-color1),
var(--window-color1)
);
}
.bb2 {
width: 10%;
height: 50%;
}
.bb2a {
border-bottom: 5vh solid var(--building-color2);
border-left: 5vw solid transparent;
border-right: 5vw solid transparent;
}
.bb2b {
width: 100%;
height: 100%;
background: repeating-linear-gradient(
var(--building-color2),
var(--building-color2) 6%,
var(--window-color2) 6%,
var(--window-color2) 9%
);
}
.bb3 {
width: 10%;
height: 55%;
background: repeating-linear-gradient(
90deg,
var(--building-color3),
var(--building-color3),
var(--window-color3) 15%
);
}
.bb4 {
width: 11%;
height: 58%;
}
.bb4a {
width: 3%;
height: 10%;
background-color: var(--building-color4);
}
.bb4b {
width: 80%;
height: 5%;
background-color: var(--building-color4);
}
.bb4c {
width: 100%;
height: 85%;
background-color: var(--building-color4);
}
.bb4-window {
width: 18%;
height: 90%;
background-color: var(--window-color4);
}
/* FOREGROUND BUILDINGS - "fb" stands for "foreground building" */
.fb1 {
width: 10%;
height: 60%;
}
.fb1a {
border-bottom: 7vh solid var(--building-color4);
border-left: 2vw solid transparent;
border-right: 2vw solid transparent;
}
.fb1b {
width: 60%;
height: 10%;
background-color: var(--building-color4);
}
.fb1c {
width: 100%;
height: 80%;
background: repeating-linear-gradient(
90deg,
var(--building-color4),
var(--building-color4) 10%,
transparent 10%,
transparent 15%
),
repeating-linear-gradient(
var(--building-color4),
var(--building-color4) 10%,
var(--window-color4) 10%,
var(--window-color4) 90%
);
}
.fb2 {
width: 10%;
height: 40%;
}
.fb2a {
width: 100%;
border-bottom: 10vh solid var(--building-color3);
border-left: 1vw solid transparent;
border-right: 1vw solid transparent;
}
.fb2b {
width: 100%;
height: 75%;
background-color: var(--building-color3);
}
.fb2-window {
width: 22%;
height: 100%;
background-color: var(--window-color3);
}
.fb3 {
width: 10%;
height: 35%;
}
.fb3a {
width: 80%;
height: 15%;
background-color: var(--building-color1);
}
.fb3b {
width: 100%;
height: 35%;
background-color: var(--building-color1);
}
.fb3-window {
width: 25%;
height: 80%;
background-color: var(--window-color1);
}
.fb4 {
width: 8%;
height: 45%;
background-color: var(--building-color1);
position: relative;
left: 10%;
}
--fcc-editable-region--
--fcc-editable-region--
.fb5 {
width: 10%;
height: 33%;
background-color: var(--building-color2);
position: relative;
right: 10%;
}
.fb6 {
width: 9%;
height: 38%;
background-color: var(--building-color3);
}
```
| curriculum/challenges/espanol/14-responsive-web-design-22/learn-css-variables-by-building-a-city-skyline/5d822fd413a79914d39e992a.md | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d | [
0.0001754873665049672,
0.00017264454800169915,
0.0001669761404627934,
0.0001732387172523886,
0.000002131313522113487
] |
{
"id": 3,
"code_window": [
" \"entry\": [],\n",
" // Configuration options can be overridden individually (necessary here as the default is `cypress/e2e/**/*.cy.{js,jsx,ts,tsx}`).\n",
" \"cypress\": [\"cypress.config.js\", \"cypress/e2e/**/*.{js,ts}\"]\n",
" },\n",
" \"client\": {\n",
" // Files used by Gatsby are handled by Knip's Gatsby plugin (https://github.com/webpro/knip/blob/next/src/plugins/gatsby/README.md)\n",
" // The rest are `webpack.entry` files.\n",
" \"entry\": [],\n",
" \"project\": [\"**/*.{js,ts,tsx}\"],\n",
" \"webpack\": {\n",
" \"config\": \"webpack-workers.js\",\n",
" \"entry\": [\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" \"cypress\": {\n",
" // Override all Cypress entry patterns as (only) spec paths don't match the default\n"
],
"file_path": "knip.jsonc",
"type": "replace",
"edit_start_line_idx": 10
} | ---
id: 5d822fd413a79914d39e98e0
title: Step 24
challengeType: 0
dashedName: step-24
---
# --description--
Crea una nuova variabile sotto le altre, chiamala `--building-color3` e dalle il valore `#cc6699`. Quindi usala come valore di `background-color` della classe `.bb3` e aggiungi un valore di fallback `pink`.
# --hints--
Dovresti definire una nuova variabile di proprietà chiamata `--building-color3`.
```js
assert.exists(new __helpers.CSSHelp(document).isPropertyUsed('--building-color3'));
```
Dovresti dare a `--building-color3` il valore `#cc6699`.
```js
assert.equal(new __helpers.CSSHelp(document).getStyle('.bb1')?.getPropertyValue('--building-color3')?.trim(), '#cc6699');
```
Dovresti impostare la proprietà `background-color` di `.bb3`.
```js
assert.exists(new __helpers.CSSHelp(document).getStyle('.bb3')?.backgroundColor);
```
Dovresti impostare la proprietà `background-color` usando la variabile `--building-color3` e il fallback `pink`.
```js
assert.equal(new __helpers.CSSHelp(document).getStyle('.bb3')?.getPropVal('background-color', true), 'var(--building-color3,pink)');
```
# --seed--
## --seed-contents--
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>City Skyline</title>
<link href="styles.css" rel="stylesheet" />
</head>
<body>
<div class="background-buildings">
<div></div>
<div></div>
<div class="bb1">
<div class="bb1a"></div>
<div class="bb1b"></div>
<div class="bb1c"></div>
<div class="bb1d"></div>
</div>
<div class="bb2"></div>
<div class="bb3"></div>
<div></div>
<div class="bb4"></div>
<div></div>
<div></div>
</div>
</body>
</html>
```
```css
* {
border: 1px solid black;
box-sizing: border-box;
}
body {
height: 100vh;
margin: 0;
overflow: hidden;
}
.background-buildings {
width: 100%;
height: 100%;
display: flex;
align-items: flex-end;
justify-content: space-evenly;
}
--fcc-editable-region--
.bb1 {
width: 10%;
height: 70%;
display: flex;
flex-direction: column;
align-items: center;
--building-color1: #aa80ff;
--building-color2: #66cc99;
}
.bb1a {
width: 70%;
height: 10%;
background-color: var(--building-color1);
}
.bb1b {
width: 80%;
height: 10%;
background-color: var(--building-color1);
}
.bb1c {
width: 90%;
height: 10%;
background-color: var(--building-color1);
}
.bb1d {
width: 100%;
height: 70%;
background-color: var(--building-color1);
}
.bb2 {
width: 10%;
height: 50%;
background-color: var(--building-color2, green);
}
.bb3 {
width: 10%;
height: 55%;
}
--fcc-editable-region--
.bb4 {
width: 11%;
height: 58%;
}
```
| curriculum/challenges/italian/14-responsive-web-design-22/learn-css-variables-by-building-a-city-skyline/5d822fd413a79914d39e98e0.md | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d | [
0.00017630514048505574,
0.00017244865011889488,
0.00016702136781532317,
0.0001724657922750339,
0.000002446977305226028
] |
{
"id": 4,
"code_window": [
" \"entry\": [\n",
" \"src/client/frame-runner.ts\",\n",
" \"src/client/workers/sass-compile.ts\",\n",
" \"src/client/workers/test-evaluator.ts\"\n",
" ]\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" \"cypress.config.js\",\n",
" \"cypress/e2e/**/*.{js,ts}\",\n",
" \"cypress/support/*.ts\",\n",
" \"cypress/plugins/index.js\"\n"
],
"file_path": "knip.jsonc",
"type": "replace",
"edit_start_line_idx": 21
} | {
"$schema": "https://unpkg.com/knip@next/schema.json",
"ignore": "**/*.d.ts",
"ignoreBinaries": ["cd", "echo", "sh"],
// Only workspaces with a configuration below are analyzed by Knip
"workspaces": {
".": {
"entry": [],
// Configuration options can be overridden individually (necessary here as the default is `cypress/e2e/**/*.cy.{js,jsx,ts,tsx}`).
"cypress": ["cypress.config.js", "cypress/e2e/**/*.{js,ts}"]
},
"client": {
// Files used by Gatsby are handled by Knip's Gatsby plugin (https://github.com/webpro/knip/blob/next/src/plugins/gatsby/README.md)
// The rest are `webpack.entry` files.
"entry": [],
"project": ["**/*.{js,ts,tsx}"],
"webpack": {
"config": "webpack-workers.js",
"entry": [
"src/client/frame-runner.ts",
"src/client/workers/sass-compile.ts",
"src/client/workers/test-evaluator.ts"
]
},
"ignore": ["i18n/schema-validation.*", "**/__mocks__", "**/__fixtures__"]
},
"client/plugins/*": {
"entry": "gatsby-node.js"
},
// This monospace gives a few unused files, so as not to make the node.js-find-unused workflow fail this is still commented out
// Also try --production to find more unused files.
// "tools/ui-components": {
// "entry": ["src/index.ts!", "utils/gen-component-script.ts"],
// "project": ["src/**/*.{ts,tsx}!", "utils/*.ts"]
// },
"tools/scripts/build": {
"entry": ["*.ts"]
}
}
}
| knip.jsonc | 1 | https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d | [
0.9777801036834717,
0.19569244980812073,
0.00016475834127049893,
0.00017305402434431016,
0.39104384183883667
] |
{
"id": 4,
"code_window": [
" \"entry\": [\n",
" \"src/client/frame-runner.ts\",\n",
" \"src/client/workers/sass-compile.ts\",\n",
" \"src/client/workers/test-evaluator.ts\"\n",
" ]\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" \"cypress.config.js\",\n",
" \"cypress/e2e/**/*.{js,ts}\",\n",
" \"cypress/support/*.ts\",\n",
" \"cypress/plugins/index.js\"\n"
],
"file_path": "knip.jsonc",
"type": "replace",
"edit_start_line_idx": 21
} | ---
id: 5900f44b1000cf542c50ff5d
title: '問題 222: 球を詰める'
challengeType: 1
forumTopicId: 301865
dashedName: problem-222-sphere-packing
---
# --description--
内半径が 50 mm のパイプの中に半径 30 mm, 31 mm, ..., 50 mm の球を 21 個の詰める場合、これらで完全に詰めることができるパイプの最短の長さを求めなさい。
回答は、マイクロメートル (${10}^{-6}$ m) 単位で最も近い整数に四捨五入すること。
# --hints--
`spherePacking()` は `1590933` を返す必要があります。
```js
assert.strictEqual(spherePacking(), 1590933);
```
# --seed--
## --seed-contents--
```js
function spherePacking() {
return true;
}
spherePacking();
```
# --solutions--
```js
// solution required
```
| curriculum/challenges/japanese/10-coding-interview-prep/project-euler/problem-222-sphere-packing.md | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d | [
0.00017541376291774213,
0.00016925921954680234,
0.00016450873226858675,
0.00016770789807196707,
0.000004208777227177052
] |
{
"id": 4,
"code_window": [
" \"entry\": [\n",
" \"src/client/frame-runner.ts\",\n",
" \"src/client/workers/sass-compile.ts\",\n",
" \"src/client/workers/test-evaluator.ts\"\n",
" ]\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" \"cypress.config.js\",\n",
" \"cypress/e2e/**/*.{js,ts}\",\n",
" \"cypress/support/*.ts\",\n",
" \"cypress/plugins/index.js\"\n"
],
"file_path": "knip.jsonc",
"type": "replace",
"edit_start_line_idx": 21
} | ---
id: 612e8279827a28352ce83a72
title: Schritt 7
challengeType: 0
dashedName: step-7
---
# --description--
Kopiere nun die Menge von sieben `.key`-Elementen und füge zwei weitere Mengen in das `.keys`-div ein.
# --hints--
Du solltest 21 `.key`-Elemente haben.
```js
const keys = document.querySelectorAll('.key');
assert(keys?.length === 21);
```
Du solltest 15 `.black--key`-Elemente haben.
```js
const blackKeys = document.querySelectorAll('.black--key');
assert(blackKeys?.length === 15);
```
Alle `.key`-Elemente sollten sich innerhalb deines `.keys`-Elements befinden.
```js
const keys = document.querySelector('.keys');
assert(keys?.querySelectorAll('.key')?.length === 21);
```
Alle `.black--key`-Elemente sollten sich innerhalb deines `.keys`-Elements befinden.
```js
const keys = document.querySelector('.keys');
assert(keys?.querySelectorAll('.black--key')?.length === 15);
```
# --seed--
## --seed-contents--
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Piano</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
--fcc-editable-region--
<div id="piano">
<div class="keys">
<div class="key"></div>
<div class="key black--key"></div>
<div class="key black--key"></div>
<div class="key"></div>
<div class="key black--key"></div>
<div class="key black--key"></div>
<div class="key black--key"></div>
</div>
</div>
--fcc-editable-region--
</body>
</html>
```
```css
```
| curriculum/challenges/german/14-responsive-web-design-22/learn-responsive-web-design-by-building-a-piano/612e8279827a28352ce83a72.md | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d | [
0.00017802651564124972,
0.00017430474690627307,
0.00017157234833575785,
0.00017401931108906865,
0.0000018538186168370885
] |
{
"id": 4,
"code_window": [
" \"entry\": [\n",
" \"src/client/frame-runner.ts\",\n",
" \"src/client/workers/sass-compile.ts\",\n",
" \"src/client/workers/test-evaluator.ts\"\n",
" ]\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" \"cypress.config.js\",\n",
" \"cypress/e2e/**/*.{js,ts}\",\n",
" \"cypress/support/*.ts\",\n",
" \"cypress/plugins/index.js\"\n"
],
"file_path": "knip.jsonc",
"type": "replace",
"edit_start_line_idx": 21
} | // this lets us do dynamic work ahead of time, inlining motivation.json, so
// that Webpack will never try to include locales that we know are not used.
interface Quote {
quote: string;
author: string;
}
interface Motivation {
compliments: string[];
motivationalQuotes: Quote[];
}
declare const preval: (s: TemplateStringsArray) => Motivation;
const words = preval`
const config = require('../../../config/env.json');
const { clientLocale } = config;
const target = '../../i18n/locales/' + clientLocale + '/motivation.json';
const words = require(target);
module.exports = words;
`;
function randomItem<T>(arr: T[]): T {
return arr[Math.floor(Math.random() * arr.length)];
}
export function randomQuote(): Quote {
return randomItem(words.motivationalQuotes);
}
export function randomCompliment(): string {
return randomItem(words.compliments);
}
| client/src/utils/get-words.ts | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d | [
0.00017474833293817937,
0.0001727523049339652,
0.00017043798288796097,
0.00017291144467890263,
0.00000181012933353486
] |
{
"id": 5,
"code_window": [
" ]\n",
" },\n",
" \"ignore\": [\"i18n/schema-validation.*\", \"**/__mocks__\", \"**/__fixtures__\"]\n",
" },\n",
" \"client/plugins/*\": {\n",
" \"entry\": \"gatsby-node.js\"\n",
" },\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" }\n",
" },\n",
" \"client\": {\n",
" \"webpack\": \"webpack-workers.js\",\n",
" \"ignore\": [\"**/__mocks__\"]\n"
],
"file_path": "knip.jsonc",
"type": "replace",
"edit_start_line_idx": 25
} | {
"$schema": "https://unpkg.com/knip@next/schema.json",
"ignore": "**/*.d.ts",
"ignoreBinaries": ["cd", "echo", "sh"],
// Only workspaces with a configuration below are analyzed by Knip
"workspaces": {
".": {
"entry": [],
// Configuration options can be overridden individually (necessary here as the default is `cypress/e2e/**/*.cy.{js,jsx,ts,tsx}`).
"cypress": ["cypress.config.js", "cypress/e2e/**/*.{js,ts}"]
},
"client": {
// Files used by Gatsby are handled by Knip's Gatsby plugin (https://github.com/webpro/knip/blob/next/src/plugins/gatsby/README.md)
// The rest are `webpack.entry` files.
"entry": [],
"project": ["**/*.{js,ts,tsx}"],
"webpack": {
"config": "webpack-workers.js",
"entry": [
"src/client/frame-runner.ts",
"src/client/workers/sass-compile.ts",
"src/client/workers/test-evaluator.ts"
]
},
"ignore": ["i18n/schema-validation.*", "**/__mocks__", "**/__fixtures__"]
},
"client/plugins/*": {
"entry": "gatsby-node.js"
},
// This monospace gives a few unused files, so as not to make the node.js-find-unused workflow fail this is still commented out
// Also try --production to find more unused files.
// "tools/ui-components": {
// "entry": ["src/index.ts!", "utils/gen-component-script.ts"],
// "project": ["src/**/*.{ts,tsx}!", "utils/*.ts"]
// },
"tools/scripts/build": {
"entry": ["*.ts"]
}
}
}
| knip.jsonc | 1 | https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d | [
0.9931001663208008,
0.19893398880958557,
0.00016730955394450575,
0.00016959241474978626,
0.39708325266838074
] |
{
"id": 5,
"code_window": [
" ]\n",
" },\n",
" \"ignore\": [\"i18n/schema-validation.*\", \"**/__mocks__\", \"**/__fixtures__\"]\n",
" },\n",
" \"client/plugins/*\": {\n",
" \"entry\": \"gatsby-node.js\"\n",
" },\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" }\n",
" },\n",
" \"client\": {\n",
" \"webpack\": \"webpack-workers.js\",\n",
" \"ignore\": [\"**/__mocks__\"]\n"
],
"file_path": "knip.jsonc",
"type": "replace",
"edit_start_line_idx": 25
} | ---
id: 5a24c314108439a4d4036177
title: 寫一個簡單的計數器
challengeType: 6
forumTopicId: 301425
dashedName: write-a-simple-counter
---
# --description--
可以結合目前爲止所涵蓋的概念來設計更復雜的有狀態組件。 這包括初始化 `state`,編寫設置 `state` 的方法,以及指定單擊處理程序來觸發這些方法。
# --instructions--
`Counter` 組件跟蹤 `state` 中的 `count` 值。 有兩個按鈕分別調用 `increment()` 和 `decrement()` 方法。 編寫這些方法,使計數器值在單擊相應按鈕時增加或減少 1。 另外,創建一個 `reset()` 方法,當單擊 reset 按鈕時,把計數設置爲 0。
**注意:** 確保沒有修改按鈕的 `className`。 另外,請記住在構造函數中爲新創建的方法添加必要的綁定。
# --hints--
`Counter` 應該返回一個 `div` 元素,它包含三個按鈕,按鈕內容依次是 `Increment!`、`Decrement!`、`Reset`。
```js
assert(
(() => {
const mockedComponent = Enzyme.mount(React.createElement(Counter));
return (
mockedComponent.find('.inc').text() === 'Increment!' &&
mockedComponent.find('.dec').text() === 'Decrement!' &&
mockedComponent.find('.reset').text() === 'Reset'
);
})()
);
```
`Counter` 應該使用設置爲 `0` 的 `count` 屬性初始化 state。
```js
const mockedComponent = Enzyme.mount(React.createElement(Counter));
assert(mockedComponent.find('h1').text() === 'Current Count: 0');
```
單擊 increment 按鈕應將計數增加 `1`。
```js
const mockedComponent = Enzyme.mount(React.createElement(Counter));
mockedComponent.find('.inc').simulate('click');
assert(mockedComponent.find('h1').text() === 'Current Count: 1');
```
單擊 decrement 按鈕應將計數減少 `1`。
```js
const mockedComponent = Enzyme.mount(React.createElement(Counter));
mockedComponent.find('.dec').simulate('click');
assert(mockedComponent.find('h1').text() === 'Current Count: -1');
```
單擊 reset 按鈕應將計數重置爲 `0`。
```js
const mockedComponent = Enzyme.mount(React.createElement(Counter));
mockedComponent.setState({ count: 5 });
const currentCountElement = mockedComponent.find('h1');
assert(currentCountElement.text() === 'Current Count: 5');
mockedComponent.find('.reset').simulate('click');
assert(currentCountElement.text() === 'Current Count: 0');
```
# --seed--
## --after-user-code--
```jsx
ReactDOM.render(<Counter />, document.getElementById('root'))
```
## --seed-contents--
```jsx
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
// Change code below this line
// Change code above this line
}
// Change code below this line
// Change code above this line
render() {
return (
<div>
<button className='inc' onClick={this.increment}>Increment!</button>
<button className='dec' onClick={this.decrement}>Decrement!</button>
<button className='reset' onClick={this.reset}>Reset</button>
<h1>Current Count: {this.state.count}</h1>
</div>
);
}
};
```
# --solutions--
```jsx
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
this.increment = this.increment.bind(this);
this.decrement = this.decrement.bind(this);
this.reset = this.reset.bind(this);
}
reset() {
this.setState({
count: 0
});
}
increment() {
this.setState(state => ({
count: state.count + 1
}));
}
decrement() {
this.setState(state => ({
count: state.count - 1
}));
}
render() {
return (
<div>
<button className='inc' onClick={this.increment}>Increment!</button>
<button className='dec' onClick={this.decrement}>Decrement!</button>
<button className='reset' onClick={this.reset}>Reset</button>
<h1>Current Count: {this.state.count}</h1>
</div>
);
}
};
```
| curriculum/challenges/chinese-traditional/03-front-end-development-libraries/react/write-a-simple-counter.md | 0 | https://github.com/freeCodeCamp/freeCodeCamp/commit/e5715b5948de9aa665f78ce0ad94eaef0a3f5a6d | [
0.0003265095583628863,
0.0001790454116417095,
0.00016574581968598068,
0.0001691145880613476,
0.00003944605850847438
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.