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": 3, "code_window": [ " expect(() => {\n", " fixture = TestBed.createComponent(App);\n", " fixture.detectChanges();\n", " }).not.toThrow();\n", " });\n", "});" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " it('should support host attribute and @ContentChild on the same component', () => {\n", " @Component(\n", " {selector: 'test-component', template: `foo`, host: {'[attr.aria-disabled]': 'true'}})\n", " class TestComponent {\n", " @ContentChild(TemplateRef) tpl !: TemplateRef<any>;\n", " }\n", "\n", " TestBed.configureTestingModule({declarations: [TestComponent]});\n", " const fixture = TestBed.createComponent(TestComponent);\n", " fixture.detectChanges();\n", "\n", " expect(fixture.componentInstance.tpl).not.toBeNull();\n", " expect(fixture.debugElement.nativeElement.getAttribute('aria-disabled')).toBe('true');\n", " });\n" ], "file_path": "packages/core/test/acceptance/integration_spec.ts", "type": "add", "edit_start_line_idx": 104 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; export default [ [ [ 'შუაღამებ', 'შუადღ.', 'αƒ“αƒ˜αƒš.', 'αƒœαƒαƒ¨αƒ£αƒαƒ“αƒ¦.', 'ბაღ.', 'ღამ.' ], u, [ 'შუაღამებ', 'შუადღებ', 'αƒ“αƒ˜αƒšαƒ˜αƒ—', 'αƒœαƒαƒ¨αƒ£αƒαƒ“αƒ¦αƒ”αƒ•αƒ‘', 'ბაღამობ', 'αƒ¦αƒαƒ›αƒ˜αƒ—' ] ], [ [ 'შუაღამე', 'შუადღე', 'αƒ“αƒ˜αƒšαƒ', 'αƒœαƒαƒ¨αƒ£αƒαƒ“αƒ¦αƒ”αƒ•αƒ˜', 'ბაღამო', 'ღამე' ], u, u ], [ '00:00', '12:00', ['05:00', '12:00'], ['12:00', '18:00'], ['18:00', '21:00'], ['21:00', '05:00'] ] ];
packages/common/locales/extra/ka.ts
0
https://github.com/angular/angular/commit/d4c4a8943168eae9f7c70f25c42d7b5a6b5ccf8f
[ 0.0001762587489793077, 0.0001748984941514209, 0.00017380113422404975, 0.00017476704670116305, 9.240181384484458e-7 ]
{ "id": 3, "code_window": [ " expect(() => {\n", " fixture = TestBed.createComponent(App);\n", " fixture.detectChanges();\n", " }).not.toThrow();\n", " });\n", "});" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " it('should support host attribute and @ContentChild on the same component', () => {\n", " @Component(\n", " {selector: 'test-component', template: `foo`, host: {'[attr.aria-disabled]': 'true'}})\n", " class TestComponent {\n", " @ContentChild(TemplateRef) tpl !: TemplateRef<any>;\n", " }\n", "\n", " TestBed.configureTestingModule({declarations: [TestComponent]});\n", " const fixture = TestBed.createComponent(TestComponent);\n", " fixture.detectChanges();\n", "\n", " expect(fixture.componentInstance.tpl).not.toBeNull();\n", " expect(fixture.debugElement.nativeElement.getAttribute('aria-disabled')).toBe('true');\n", " });\n" ], "file_path": "packages/core/test/acceptance/integration_spec.ts", "type": "add", "edit_start_line_idx": 104 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {AotCompilerHost, AotCompilerOptions, GeneratedFile, createAotCompiler, toTypeScript} from '@angular/compiler'; import {MetadataBundlerHost} from '@angular/compiler-cli/src/metadata/bundler'; import {MetadataCollector} from '@angular/compiler-cli/src/metadata/collector'; import {ModuleMetadata} from '@angular/compiler-cli/src/metadata/index'; import * as fs from 'fs'; import * as path from 'path'; import * as ts from 'typescript'; export interface MetadataProvider { getMetadata(source: ts.SourceFile): ModuleMetadata|undefined; } let nodeModulesPath: string; let angularSourcePath: string; let rootPath: string; calcPathsOnDisc(); export type MockFileOrDirectory = string | MockDirectory; export type MockDirectory = { [name: string]: MockFileOrDirectory | undefined; }; export function isDirectory(data: MockFileOrDirectory | undefined): data is MockDirectory { return typeof data !== 'string'; } const NODE_MODULES = '/node_modules/'; const IS_GENERATED = /\.(ngfactory|ngstyle)$/; const angularts = /@angular\/(\w|\/|-)+\.tsx?$/; const rxjs = /\/rxjs\//; const tsxfile = /\.tsx$/; export const settings: ts.CompilerOptions = { target: ts.ScriptTarget.ES5, declaration: true, module: ts.ModuleKind.CommonJS, moduleResolution: ts.ModuleResolutionKind.NodeJs, emitDecoratorMetadata: true, experimentalDecorators: true, removeComments: false, noImplicitAny: false, skipLibCheck: true, strictNullChecks: true, lib: ['lib.es2015.d.ts', 'lib.dom.d.ts'], types: [] }; export interface EmitterOptions { emitMetadata: boolean; mockData?: MockDirectory; context?: Map<string, string>; } function calcPathsOnDisc() { const moduleFilename = module.filename.replace(/\\/g, '/'); const distIndex = moduleFilename.indexOf('/dist/all'); if (distIndex >= 0) { rootPath = moduleFilename.substr(0, distIndex); nodeModulesPath = path.join(rootPath, 'node_modules'); angularSourcePath = path.join(rootPath, 'packages'); } } export class EmittingCompilerHost implements ts.CompilerHost { private addedFiles = new Map<string, string>(); private writtenFiles = new Map<string, string>(); private scriptNames: string[]; private root = '/'; private collector = new MetadataCollector(); private cachedAddedDirectories: Set<string>|undefined; constructor(scriptNames: string[], private options: EmitterOptions) { // Rewrite references to scripts with '@angular' to its corresponding location in // the source tree. this.scriptNames = scriptNames.map(f => this.effectiveName(f)); this.root = rootPath || this.root; if (options.context) { this.addedFiles = mergeMaps(options.context); } } public writtenAngularFiles(target = new Map<string, string>()): Map<string, string> { this.written.forEach((value, key) => { const path = `/node_modules/@angular${key.substring(angularSourcePath.length)}`; target.set(path, value); }); return target; } public addScript(fileName: string, content: string) { const scriptName = this.effectiveName(fileName); this.addedFiles.set(scriptName, content); this.cachedAddedDirectories = undefined; this.scriptNames.push(scriptName); } public override(fileName: string, content: string) { const scriptName = this.effectiveName(fileName); this.addedFiles.set(scriptName, content); this.cachedAddedDirectories = undefined; } public addFiles(map: Map<string, string>) { for (const [name, content] of Array.from(map.entries())) { this.addedFiles.set(name, content); } } public addWrittenFile(fileName: string, content: string) { this.writtenFiles.set(this.effectiveName(fileName), content); } public getWrittenFiles(): {name: string, content: string}[] { return Array.from(this.writtenFiles).map(f => ({name: f[0], content: f[1]})); } public get scripts(): string[] { return this.scriptNames; } public get written(): Map<string, string> { return this.writtenFiles; } public effectiveName(fileName: string): string { const prefix = '@angular/'; return angularSourcePath && fileName.startsWith(prefix) ? path.join(angularSourcePath, fileName.substr(prefix.length)) : fileName; } // ts.ModuleResolutionHost fileExists(fileName: string): boolean { return this.addedFiles.has(fileName) || open(fileName, this.options.mockData) != null || fs.existsSync(fileName); } readFile(fileName: string): string { const result = this.addedFiles.get(fileName) || open(fileName, this.options.mockData); if (result) return result; let basename = path.basename(fileName); if (/^lib.*\.d\.ts$/.test(basename)) { let libPath = ts.getDefaultLibFilePath(settings); return fs.readFileSync(path.join(path.dirname(libPath), basename), 'utf8'); } return fs.readFileSync(fileName, 'utf8'); } directoryExists(directoryName: string): boolean { return directoryExists(directoryName, this.options.mockData) || this.getAddedDirectories().has(directoryName) || (fs.existsSync(directoryName) && fs.statSync(directoryName).isDirectory()); } getCurrentDirectory(): string { return this.root; } getDirectories(dir: string): string[] { const result = open(dir, this.options.mockData); if (result && typeof result !== 'string') { return Object.keys(result); } return fs.readdirSync(dir).filter(p => { const name = path.join(dir, p); const stat = fs.statSync(name); return stat && stat.isDirectory(); }); } // ts.CompilerHost getSourceFile( fileName: string, languageVersion: ts.ScriptTarget, onError?: (message: string) => void): ts.SourceFile { const content = this.readFile(fileName); if (content) { return ts.createSourceFile(fileName, content, languageVersion, /* setParentNodes */ true); } throw new Error(`File not found '${fileName}'.`); } getDefaultLibFileName(options: ts.CompilerOptions): string { return 'lib.d.ts'; } writeFile: ts.WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: ReadonlyArray<ts.SourceFile>) => { this.addWrittenFile(fileName, data); if (this.options.emitMetadata && sourceFiles && sourceFiles.length && DTS.test(fileName)) { const metadataFilePath = fileName.replace(DTS, '.metadata.json'); const metadata = this.collector.getMetadata(sourceFiles[0]); if (metadata) { this.addWrittenFile(metadataFilePath, JSON.stringify(metadata)); } } } getCanonicalFileName(fileName: string): string { return fileName; } useCaseSensitiveFileNames(): boolean { return false; } getNewLine(): string { return '\n'; } private getAddedDirectories(): Set<string> { let result = this.cachedAddedDirectories; if (!result) { const newCache = new Set<string>(); const addFile = (fileName: string) => { const directory = fileName.substr(0, fileName.lastIndexOf('/')); if (!newCache.has(directory)) { newCache.add(directory); addFile(directory); } }; Array.from(this.addedFiles.keys()).forEach(addFile); this.cachedAddedDirectories = result = newCache; } return result; } } export class MockCompilerHost implements ts.CompilerHost { scriptNames: string[]; public overrides = new Map<string, string>(); public writtenFiles = new Map<string, string>(); private sourceFiles = new Map<string, ts.SourceFile>(); private assumeExists = new Set<string>(); private traces: string[] = []; constructor(scriptNames: string[], private data: MockDirectory) { this.scriptNames = scriptNames.slice(0); } // Test API override(fileName: string, content: string) { if (content) { this.overrides.set(fileName, content); } else { this.overrides.delete(fileName); } this.sourceFiles.delete(fileName); } addScript(fileName: string, content: string) { this.overrides.set(fileName, content); this.scriptNames.push(fileName); this.sourceFiles.delete(fileName); } assumeFileExists(fileName: string) { this.assumeExists.add(fileName); } remove(files: string[]) { // Remove the files from the list of scripts. const fileSet = new Set(files); this.scriptNames = this.scriptNames.filter(f => fileSet.has(f)); // Remove files from written files files.forEach(f => this.writtenFiles.delete(f)); } // ts.ModuleResolutionHost fileExists(fileName: string): boolean { if (this.overrides.has(fileName) || this.writtenFiles.has(fileName) || this.assumeExists.has(fileName)) { return true; } const effectiveName = this.getEffectiveName(fileName); if (effectiveName == fileName) { return open(fileName, this.data) != null; } if (fileName.match(rxjs)) { return fs.existsSync(effectiveName); } return false; } readFile(fileName: string): string { return this.getFileContent(fileName) !; } trace(s: string): void { this.traces.push(s); } getCurrentDirectory(): string { return '/'; } getDirectories(dir: string): string[] { const effectiveName = this.getEffectiveName(dir); if (effectiveName === dir) { const data = find(dir, this.data); if (isDirectory(data)) { return Object.keys(data).filter(k => isDirectory(data[k])); } } return []; } // ts.CompilerHost getSourceFile( fileName: string, languageVersion: ts.ScriptTarget, onError?: (message: string) => void): ts.SourceFile { let result = this.sourceFiles.get(fileName); if (!result) { const content = this.getFileContent(fileName); if (content) { result = ts.createSourceFile(fileName, content, languageVersion); this.sourceFiles.set(fileName, result); } } return result !; } getDefaultLibFileName(options: ts.CompilerOptions): string { return 'lib.d.ts'; } writeFile: ts.WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean) => { this.writtenFiles.set(fileName, data); this.sourceFiles.delete(fileName); } getCanonicalFileName(fileName: string): string { return fileName; } useCaseSensitiveFileNames(): boolean { return false; } getNewLine(): string { return '\n'; } // Private methods private getFileContent(fileName: string): string|undefined { if (this.overrides.has(fileName)) { return this.overrides.get(fileName); } if (this.writtenFiles.has(fileName)) { return this.writtenFiles.get(fileName); } let basename = path.basename(fileName); if (/^lib.*\.d\.ts$/.test(basename)) { let libPath = ts.getDefaultLibFilePath(settings); return fs.readFileSync(path.join(path.dirname(libPath), basename), 'utf8'); } let effectiveName = this.getEffectiveName(fileName); if (effectiveName === fileName) { return open(fileName, this.data); } if (fileName.match(rxjs) && fs.existsSync(fileName)) { return fs.readFileSync(fileName, 'utf8'); } } private getEffectiveName(name: string): string { const node_modules = 'node_modules'; const rxjs = '/rxjs'; if (name.startsWith('/' + node_modules)) { if (nodeModulesPath && name.startsWith('/' + node_modules + rxjs)) { return path.join(nodeModulesPath, name.substr(node_modules.length + 1)); } } return name; } } const EXT = /(\.ts|\.d\.ts|\.js|\.jsx|\.tsx)$/; const DTS = /\.d\.ts$/; const GENERATED_FILES = /\.ngfactory\.ts$|\.ngstyle\.ts$/; export class MockAotCompilerHost implements AotCompilerHost { private metadataVisible: boolean = true; private dtsAreSource: boolean = true; private resolveModuleNameHost: ts.ModuleResolutionHost; constructor( private tsHost: MockCompilerHost, private metadataProvider: MetadataProvider = new MetadataCollector()) { this.resolveModuleNameHost = Object.create(tsHost); this.resolveModuleNameHost.fileExists = (fileName) => { fileName = stripNgResourceSuffix(fileName); return tsHost.fileExists(fileName); }; } hideMetadata() { this.metadataVisible = false; } tsFilesOnly() { this.dtsAreSource = false; } // StaticSymbolResolverHost getMetadataFor(modulePath: string): {[key: string]: any}[]|undefined { if (!this.tsHost.fileExists(modulePath)) { return undefined; } if (DTS.test(modulePath)) { if (this.metadataVisible) { const metadataPath = modulePath.replace(DTS, '.metadata.json'); if (this.tsHost.fileExists(metadataPath)) { let result = JSON.parse(this.tsHost.readFile(metadataPath)); return Array.isArray(result) ? result : [result]; } } } else { const sf = this.tsHost.getSourceFile(modulePath, ts.ScriptTarget.Latest); const metadata = this.metadataProvider.getMetadata(sf); return metadata ? [metadata] : []; } return undefined; } moduleNameToFileName(moduleName: string, containingFile: string): string|null { if (!containingFile || !containingFile.length) { if (moduleName.indexOf('.') === 0) { throw new Error('Resolution of relative paths requires a containing file.'); } // Any containing file gives the same result for absolute imports containingFile = path.join('/', 'index.ts'); } moduleName = moduleName.replace(EXT, ''); const resolved = ts.resolveModuleName( moduleName, containingFile.replace(/\\/g, '/'), {baseDir: '/', genDir: '/'}, this.resolveModuleNameHost) .resolvedModule; return resolved ? resolved.resolvedFileName : null; } getOutputName(filePath: string) { return filePath; } resourceNameToFileName(resourceName: string, containingFile: string) { // Note: we convert package paths into relative paths to be compatible with the the // previous implementation of UrlResolver. if (resourceName && resourceName.charAt(0) !== '.' && !path.isAbsolute(resourceName)) { resourceName = `./${resourceName}`; } const filePathWithNgResource = this.moduleNameToFileName(addNgResourceSuffix(resourceName), containingFile); return filePathWithNgResource ? stripNgResourceSuffix(filePathWithNgResource) : null; } // AotSummaryResolverHost loadSummary(filePath: string): string|null { return this.tsHost.readFile(filePath); } isSourceFile(sourceFilePath: string): boolean { return !GENERATED_FILES.test(sourceFilePath) && (this.dtsAreSource || !DTS.test(sourceFilePath)); } toSummaryFileName(filePath: string): string { return filePath.replace(EXT, '') + '.d.ts'; } fromSummaryFileName(filePath: string): string { return filePath; } // AotCompilerHost fileNameToModuleName(importedFile: string, containingFile: string): string { return importedFile.replace(EXT, ''); } loadResource(path: string): string { if (this.tsHost.fileExists(path)) { return this.tsHost.readFile(path); } else { throw new Error(`Resource ${path} not found.`); } } } export class MockMetadataBundlerHost implements MetadataBundlerHost { private collector = new MetadataCollector(); constructor(private host: ts.CompilerHost) {} getMetadataFor(moduleName: string): ModuleMetadata|undefined { const source = this.host.getSourceFile(moduleName + '.ts', ts.ScriptTarget.Latest); return source && this.collector.getMetadata(source); } } function find(fileName: string, data: MockFileOrDirectory | undefined): MockFileOrDirectory| undefined { if (!data) return undefined; const names = fileName.split('/'); if (names.length && !names[0].length) names.shift(); let current: MockFileOrDirectory|undefined = data; for (const name of names) { if (typeof current !== 'object') { return undefined; } current = current[name]; } return current; } function open(fileName: string, data: MockFileOrDirectory | undefined): string|undefined { let result = find(fileName, data); if (typeof result === 'string') { return result; } return undefined; } function directoryExists(dirname: string, data: MockFileOrDirectory | undefined): boolean { let result = find(dirname, data); return !!result && typeof result !== 'string'; } export type MockFileArray = { fileName: string, content: string }[]; export type MockData = MockDirectory | Map<string, string>| (MockDirectory | Map<string, string>)[]; export function toMockFileArray(data: MockData, target: MockFileArray = []): MockFileArray { if (data instanceof Map) { mapToMockFileArray(data, target); } else if (Array.isArray(data)) { data.forEach(entry => toMockFileArray(entry, target)); } else { mockDirToFileArray(data, '', target); } return target; } function mockDirToFileArray(dir: MockDirectory, path: string, target: MockFileArray) { Object.keys(dir).forEach((localFileName) => { const value = dir[localFileName] !; const fileName = `${path}/${localFileName}`; if (typeof value === 'string') { target.push({fileName, content: value}); } else { mockDirToFileArray(value, fileName, target); } }); } function mapToMockFileArray(files: Map<string, string>, target: MockFileArray) { files.forEach((content, fileName) => { target.push({fileName, content}); }); } export function arrayToMockMap(arr: MockFileArray): Map<string, string> { const map = new Map<string, string>(); arr.forEach(({fileName, content}) => { map.set(fileName, content); }); return map; } export function arrayToMockDir(arr: MockFileArray): MockDirectory { const rootDir: MockDirectory = {}; arr.forEach(({fileName, content}) => { let pathParts = fileName.split('/'); // trim trailing slash let startIndex = pathParts[0] ? 0 : 1; // get/create the directory let currentDir = rootDir; for (let i = startIndex; i < pathParts.length - 1; i++) { const pathPart = pathParts[i]; let localDir = <MockDirectory>currentDir[pathPart]; if (!localDir) { currentDir[pathPart] = localDir = {}; } currentDir = localDir; } // write the file currentDir[pathParts[pathParts.length - 1]] = content; }); return rootDir; } const minCoreIndex = ` export * from './src/application_module'; export * from './src/change_detection'; export * from './src/metadata'; export * from './src/di/metadata'; export * from './src/di/injectable'; export * from './src/di/injector'; export * from './src/di/injection_token'; export * from './src/linker'; export * from './src/render'; export * from './src/codegen_private_exports'; `; function readBazelWrittenFilesFrom( bazelPackageRoot: string, packageName: string, map: Map<string, string>, skip: (name: string, fullName: string) => boolean = () => false) { function processDirectory(dir: string, dest: string) { const entries = fs.readdirSync(dir); for (const name of entries) { const fullName = path.join(dir, name); const destName = path.join(dest, name); const stat = fs.statSync(fullName); if (!skip(name, fullName)) { if (stat.isDirectory()) { processDirectory(fullName, destName); } else { const content = fs.readFileSync(fullName, 'utf8'); map.set(destName, content); } } } } try { processDirectory(bazelPackageRoot, path.join('/node_modules/@angular', packageName)); // todo: check why we always need an index.d.ts if (fs.existsSync(path.join(bazelPackageRoot, `${packageName}.d.ts`))) { const content = fs.readFileSync(path.join(bazelPackageRoot, `${packageName}.d.ts`), 'utf8'); map.set(path.join('/node_modules/@angular', packageName, 'index.d.ts'), content); } } catch (e) { console.error( `Consider adding //packages/${packageName} as a data dependency in the BUILD.bazel rule for the failing test`); throw e; } } export function isInBazel(): boolean { return process.env.TEST_SRCDIR != null; } export function setup(options: { compileAngular: boolean, compileFakeCore?: boolean, compileAnimations: boolean, compileCommon?: boolean } = { compileAngular: true, compileAnimations: true, compileCommon: false, compileFakeCore: false, }) { let angularFiles = new Map<string, string>(); beforeAll(() => { const sources = process.env.TEST_SRCDIR; if (sources) { // If running under bazel then we get the compiled version of the files from the bazel package // output. const bundles = new Set([ 'bundles', 'esm2015', 'esm5', 'testing', 'testing.d.ts', 'testing.metadata.json', 'browser', 'browser.d.ts' ]); const skipDirs = (name: string) => bundles.has(name); if (options.compileAngular) { // If this fails please add //packages/core:npm_package as a test data dependency. readBazelWrittenFilesFrom( path.join(sources, 'angular/packages/core/npm_package'), 'core', angularFiles, skipDirs); } if (options.compileFakeCore) { readBazelWrittenFilesFrom( path.join(sources, 'angular/packages/compiler-cli/test/ngtsc/fake_core/npm_package'), 'core', angularFiles, skipDirs); } if (options.compileAnimations) { // If this fails please add //packages/animations:npm_package as a test data dependency. readBazelWrittenFilesFrom( path.join(sources, 'angular/packages/animations/npm_package'), 'animations', angularFiles, skipDirs); } if (options.compileCommon) { // If this fails please add //packages/common:npm_package as a test data dependency. readBazelWrittenFilesFrom( path.join(sources, 'angular/packages/common/npm_package'), 'common', angularFiles, skipDirs); } return; } if (options.compileAngular) { const emittingHost = new EmittingCompilerHost([], {emitMetadata: true}); emittingHost.addScript('@angular/core/index.ts', minCoreIndex); const emittingProgram = ts.createProgram(emittingHost.scripts, settings, emittingHost); emittingProgram.emit(); emittingHost.writtenAngularFiles(angularFiles); } if (options.compileCommon) { const emittingHost = new EmittingCompilerHost(['@angular/common/index.ts'], {emitMetadata: true}); const emittingProgram = ts.createProgram(emittingHost.scripts, settings, emittingHost); emittingProgram.emit(); emittingHost.writtenAngularFiles(angularFiles); } if (options.compileAnimations) { const emittingHost = new EmittingCompilerHost(['@angular/animations/index.ts'], {emitMetadata: true}); const emittingProgram = ts.createProgram(emittingHost.scripts, settings, emittingHost); emittingProgram.emit(); emittingHost.writtenAngularFiles(angularFiles); } }); return angularFiles; } export function expectNoDiagnostics(program: ts.Program) { function fileInfo(diagnostic: ts.Diagnostic): string { if (diagnostic.file) { return `${diagnostic.file.fileName}(${diagnostic.start}): `; } return ''; } function chars(len: number, ch: string): string { return new Array(len).fill(ch).join(''); } function lineNoOf(offset: number, text: string): number { let result = 1; for (let i = 0; i < offset; i++) { if (text[i] == '\n') result++; } return result; } function lineInfo(diagnostic: ts.Diagnostic): string { if (diagnostic.file) { const start = diagnostic.start !; let end = diagnostic.start ! + diagnostic.length !; const source = diagnostic.file.text; let lineStart = start; let lineEnd = end; while (lineStart > 0 && source[lineStart] != '\n') lineStart--; if (lineStart < start) lineStart++; while (lineEnd < source.length && source[lineEnd] != '\n') lineEnd++; let line = source.substring(lineStart, lineEnd); const lineIndex = line.indexOf('/n'); if (lineIndex > 0) { line = line.substr(0, lineIndex); end = start + lineIndex; } const lineNo = lineNoOf(start, source) + ': '; return '\n' + lineNo + line + '\n' + chars(start - lineStart + lineNo.length, ' ') + chars(end - start, '^'); } return ''; } function expectNoDiagnostics(diagnostics: ReadonlyArray<ts.Diagnostic>) { if (diagnostics && diagnostics.length) { throw new Error( 'Errors from TypeScript:\n' + diagnostics .map( d => `${fileInfo(d)}${ts.flattenDiagnosticMessageText(d.messageText, '\n')}${lineInfo(d)}`) .join(' \n')); } } expectNoDiagnostics(program.getOptionsDiagnostics()); expectNoDiagnostics(program.getSyntacticDiagnostics()); expectNoDiagnostics(program.getSemanticDiagnostics()); } export function isSource(fileName: string): boolean { return !isDts(fileName) && /\.ts$/.test(fileName); } function isDts(fileName: string): boolean { return /\.d.ts$/.test(fileName); } function isSourceOrDts(fileName: string): boolean { return /\.ts$/.test(fileName); } export function compile( rootDirs: MockData, options: { emit?: boolean, useSummaries?: boolean, preCompile?: (program: ts.Program) => void, postCompile?: (program: ts.Program) => void, }& AotCompilerOptions = {}, tsOptions: ts.CompilerOptions = {}): {genFiles: GeneratedFile[], outDir: MockDirectory} { // when using summaries, always emit so the next step can use the results. const emit = options.emit || options.useSummaries; const preCompile = options.preCompile || (() => {}); const postCompile = options.postCompile || expectNoDiagnostics; const rootDirArr = toMockFileArray(rootDirs); const scriptNames = rootDirArr.map(entry => entry.fileName) .filter(options.useSummaries ? isSource : isSourceOrDts); const host = new MockCompilerHost(scriptNames, arrayToMockDir(rootDirArr)); const aotHost = new MockAotCompilerHost(host); if (options.useSummaries) { aotHost.hideMetadata(); aotHost.tsFilesOnly(); } const tsSettings = {...settings, ...tsOptions}; const program = ts.createProgram(host.scriptNames.slice(0), tsSettings, host); preCompile(program); const {compiler, reflector} = createAotCompiler(aotHost, options, (err) => { throw err; }); const analyzedModules = compiler.analyzeModulesSync(program.getSourceFiles().map(sf => sf.fileName)); const genFiles = compiler.emitAllImpls(analyzedModules); genFiles.forEach((file) => { const source = file.source || toTypeScript(file); if (isSource(file.genFileUrl)) { host.addScript(file.genFileUrl, source); } else { host.override(file.genFileUrl, source); } }); const newProgram = ts.createProgram(host.scriptNames.slice(0), tsSettings, host); postCompile(newProgram); if (emit) { newProgram.emit(); } let outDir: MockDirectory = {}; if (emit) { const dtsFilesWithGenFiles = new Set<string>(genFiles.map(gf => gf.srcFileUrl).filter(isDts)); outDir = arrayToMockDir(toMockFileArray([host.writtenFiles, host.overrides]) .filter((entry) => !isSource(entry.fileName)) .concat(rootDirArr.filter(e => dtsFilesWithGenFiles.has(e.fileName)))); } return {genFiles, outDir}; } function stripNgResourceSuffix(fileName: string): string { return fileName.replace(/\.\$ngresource\$.*/, ''); } function addNgResourceSuffix(fileName: string): string { return `${fileName}.$ngresource$`; } function extractFileNames(directory: MockDirectory): string[] { const result: string[] = []; const scan = (directory: MockDirectory, prefix: string) => { for (let name of Object.getOwnPropertyNames(directory)) { const entry = directory[name]; const fileName = `${prefix}/${name}`; if (typeof entry === 'string') { result.push(fileName); } else if (entry) { scan(entry, fileName); } } }; scan(directory, ''); return result; } export function emitLibrary( context: Map<string, string>, mockData: MockDirectory, scriptFiles?: string[]): Map<string, string> { const emittingHost = new EmittingCompilerHost( scriptFiles || extractFileNames(mockData), {emitMetadata: true, mockData, context}); const emittingProgram = ts.createProgram(emittingHost.scripts, settings, emittingHost); expectNoDiagnostics(emittingProgram); emittingProgram.emit(); return emittingHost.written; } export function mergeMaps<K, V>(...maps: Map<K, V>[]): Map<K, V> { const result = new Map<K, V>(); for (const map of maps) { for (const [key, value] of Array.from(map.entries())) { result.set(key, value); } } return result; }
packages/compiler/test/aot/test_util.ts
0
https://github.com/angular/angular/commit/d4c4a8943168eae9f7c70f25c42d7b5a6b5ccf8f
[ 0.0007944551762193441, 0.00018066068878397346, 0.00016453729767818004, 0.00017396708426531404, 0.00006665536056971177 ]
{ "id": 0, "code_window": [ " return ($a <= code && code <= $z) || ($A <= code && code <= $Z) || (code == $_) || (code == $$);\n", "}\n", "\n", "function isIdentifierPart(code: number): boolean {\n", " return ($a <= code && code <= $z) || ($A <= code && code <= $Z) || ($0 <= code && code <= $9) ||\n", " (code == $_) || (code == $$);\n", "}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function isIdentifier(input: string): boolean {\n", " if (input.length == 0) return false;\n", " var scanner = new _Scanner(input);\n", " if (!isIdentifierStart(scanner.peek)) return false;\n", " scanner.advance();\n", " while (scanner.peek !== $EOF) {\n", " if (!isIdentifierPart(scanner.peek)) return false;\n", " scanner.advance();\n", " }\n", " return true;\n", "}\n", "\n" ], "file_path": "modules/angular2/src/core/change_detection/parser/lexer.ts", "type": "add", "edit_start_line_idx": 397 }
import {ddescribe, describe, it, xit, iit, expect, beforeEach} from 'angular2/testing_internal'; import {isBlank, isPresent} from 'angular2/src/facade/lang'; import {reflector} from 'angular2/src/core/reflection/reflection'; import {Parser} from 'angular2/src/core/change_detection/parser/parser'; import {Unparser} from './unparser'; import {Lexer} from 'angular2/src/core/change_detection/parser/lexer'; import {BindingPipe, LiteralPrimitive, AST} from 'angular2/src/core/change_detection/parser/ast'; export function main() { function createParser() { return new Parser(new Lexer(), reflector); } function parseAction(text, location = null): any { return createParser().parseAction(text, location); } function parseBinding(text, location = null): any { return createParser().parseBinding(text, location); } function parseTemplateBindings(text, location = null): any { return createParser().parseTemplateBindings(text, location); } function parseInterpolation(text, location = null): any { return createParser().parseInterpolation(text, location); } function parseSimpleBinding(text, location = null): any { return createParser().parseSimpleBinding(text, location); } function unparse(ast: AST): string { return new Unparser().unparse(ast); } function checkBinding(exp: string, expected?: string) { var ast = parseBinding(exp); if (isBlank(expected)) expected = exp; expect(unparse(ast)).toEqual(expected); } function checkAction(exp: string, expected?: string) { var ast = parseAction(exp); if (isBlank(expected)) expected = exp; expect(unparse(ast)).toEqual(expected); } function expectActionError(text) { return expect(() => parseAction(text)); } function expectBindingError(text) { return expect(() => parseBinding(text)); } describe("parser", () => { describe("parseAction", () => { it('should parse numbers', () => { checkAction("1"); }); it('should parse strings', () => { checkAction("'1'", '"1"'); checkAction('"1"'); }); it('should parse null', () => { checkAction("null"); }); it('should parse unary - expressions', () => { checkAction("-1", "0 - 1"); checkAction("+1", "1"); }); it('should parse unary ! expressions', () => { checkAction("!true"); checkAction("!!true"); checkAction("!!!true"); }); it('should parse multiplicative expressions', () => { checkAction("3*4/2%5", "3 * 4 / 2 % 5"); }); it('should parse additive expressions', () => { checkAction("3 + 6 - 2"); }); it('should parse relational expressions', () => { checkAction("2 < 3"); checkAction("2 > 3"); checkAction("2 <= 2"); checkAction("2 >= 2"); }); it('should parse equality expressions', () => { checkAction("2 == 3"); checkAction("2 != 3"); }); it('should parse strict equality expressions', () => { checkAction("2 === 3"); checkAction("2 !== 3"); }); it('should parse expressions', () => { checkAction("true && true"); checkAction("true || false"); }); it('should parse grouped expressions', () => { checkAction("(1 + 2) * 3", "1 + 2 * 3"); }); it('should parse an empty string', () => { checkAction(''); }); describe("literals", () => { it('should parse array', () => { checkAction("[1][0]"); checkAction("[[1]][0][0]"); checkAction("[]"); checkAction("[].length"); checkAction("[1, 2].length"); }); it('should parse map', () => { checkAction("{}"); checkAction("{a: 1}[2]"); checkAction("{}[\"a\"]"); }); it('should only allow identifier, string, or keyword as map key', () => { expectActionError('{(:0}') .toThrowError(new RegExp('expected identifier, keyword, or string')); expectActionError('{1234:0}') .toThrowError(new RegExp('expected identifier, keyword, or string')); }); }); describe("member access", () => { it("should parse field access", () => { checkAction("a"); checkAction("a.a"); }); it('should only allow identifier or keyword as member names', () => { expectActionError('x.(').toThrowError(new RegExp('identifier or keyword')); expectActionError('x. 1234').toThrowError(new RegExp('identifier or keyword')); expectActionError('x."foo"').toThrowError(new RegExp('identifier or keyword')); }); it('should parse safe field access', () => { checkAction('a?.a'); checkAction('a.a?.a'); }); }); describe("method calls", () => { it("should parse method calls", () => { checkAction("fn()"); checkAction("add(1, 2)"); checkAction("a.add(1, 2)"); checkAction("fn().add(1, 2)"); }); }); describe("functional calls", () => { it("should parse function calls", () => { checkAction("fn()(1, 2)"); }); }); describe("conditional", () => { it('should parse ternary/conditional expressions', () => { checkAction("7 == 3 + 4 ? 10 : 20"); checkAction("false ? 10 : 20"); }); it('should throw on incorrect ternary operator syntax', () => { expectActionError("true?1").toThrowError(new RegExp( 'Parser Error: Conditional expression true\\?1 requires all 3 expressions')); }); }); describe("assignment", () => { it("should support field assignments", () => { checkAction("a = 12"); checkAction("a.a.a = 123"); checkAction("a = 123; b = 234;"); }); it("should throw on safe field assignments", () => { expectActionError("a?.a = 123") .toThrowError(new RegExp('cannot be used in the assignment')); }); it("should support array updates", () => { checkAction("a[0] = 200"); }); }); it("should error when using pipes", () => { expectActionError('x|blah').toThrowError(new RegExp('Cannot have a pipe')); }); it('should store the source in the result', () => { expect(parseAction('someExpr').source).toBe('someExpr'); }); it('should store the passed-in location', () => { expect(parseAction('someExpr', 'location').location).toBe('location'); }); it("should throw when encountering interpolation", () => { expectActionError("{{a()}}") .toThrowErrorWith('Got interpolation ({{}}) where expression was expected'); }); }); describe("general error handling", () => { it("should throw on an unexpected token", () => { expectActionError("[1,2] trac").toThrowError(new RegExp('Unexpected token \'trac\'')); }); it('should throw a reasonable error for unconsumed tokens', () => { expectActionError(")") .toThrowError(new RegExp("Unexpected token \\) at column 1 in \\[\\)\\]")); }); it('should throw on missing expected token', () => { expectActionError("a(b").toThrowError( new RegExp("Missing expected \\) at the end of the expression \\[a\\(b\\]")); }); }); describe("parseBinding", () => { describe("pipes", () => { it("should parse pipes", () => { checkBinding('a(b | c)', 'a((b | c))'); checkBinding('a.b(c.d(e) | f)', 'a.b((c.d(e) | f))'); checkBinding('[1, 2, 3] | a', '([1, 2, 3] | a)'); checkBinding('{a: 1} | b', '({a: 1} | b)'); checkBinding('a[b] | c', '(a[b] | c)'); checkBinding('a?.b | c', '(a?.b | c)'); checkBinding('true | a', '(true | a)'); checkBinding('a | b:c | d', '((a | b:c) | d)'); checkBinding('a | b:(c | d)', '(a | b:(c | d))'); }); it('should only allow identifier or keyword as formatter names', () => { expectBindingError('"Foo"|(').toThrowError(new RegExp('identifier or keyword')); expectBindingError('"Foo"|1234').toThrowError(new RegExp('identifier or keyword')); expectBindingError('"Foo"|"uppercase"').toThrowError(new RegExp('identifier or keyword')); }); it('should parse quoted expressions', () => { checkBinding('a:b', 'a:b'); }); it('should ignore whitespace around quote prefix', () => { checkBinding(' a :b', 'a:b'); }); it('should refuse prefixes that are not single identifiers', () => { expectBindingError('a + b:c').toThrowError(); expectBindingError('1:c').toThrowError(); }); }); it('should store the source in the result', () => { expect(parseBinding('someExpr').source).toBe('someExpr'); }); it('should store the passed-in location', () => { expect(parseBinding('someExpr', 'location').location).toBe('location'); }); it('should throw on chain expressions', () => { expect(() => parseBinding("1;2")).toThrowError(new RegExp("contain chained expression")); }); it('should throw on assignment', () => { expect(() => parseBinding("a=2")).toThrowError(new RegExp("contain assignments")); }); it('should throw when encountering interpolation', () => { expectBindingError("{{a.b}}") .toThrowErrorWith('Got interpolation ({{}}) where expression was expected'); }); }); describe('parseTemplateBindings', () => { function keys(templateBindings: any[]) { return templateBindings.map(binding => binding.key); } function keyValues(templateBindings: any[]) { return templateBindings.map(binding => { if (binding.keyIsVar) { return '#' + binding.key + (isBlank(binding.name) ? '=null' : '=' + binding.name); } else { return binding.key + (isBlank(binding.expression) ? '' : `=${binding.expression}`) } }); } function exprSources(templateBindings: any[]) { return templateBindings.map( binding => isPresent(binding.expression) ? binding.expression.source : null); } it('should parse an empty string', () => { expect(parseTemplateBindings('')).toEqual([]); }); it('should parse a string without a value', () => { expect(keys(parseTemplateBindings('a'))).toEqual(['a']); }); it('should only allow identifier, string, or keyword including dashes as keys', () => { var bindings = parseTemplateBindings("a:'b'"); expect(keys(bindings)).toEqual(['a']); bindings = parseTemplateBindings("'a':'b'"); expect(keys(bindings)).toEqual(['a']); bindings = parseTemplateBindings("\"a\":'b'"); expect(keys(bindings)).toEqual(['a']); bindings = parseTemplateBindings("a-b:'c'"); expect(keys(bindings)).toEqual(['a-b']); expect(() => { parseTemplateBindings('(:0'); }) .toThrowError(new RegExp('expected identifier, keyword, or string')); expect(() => { parseTemplateBindings('1234:0'); }) .toThrowError(new RegExp('expected identifier, keyword, or string')); }); it('should detect expressions as value', () => { var bindings = parseTemplateBindings("a:b"); expect(exprSources(bindings)).toEqual(['b']); bindings = parseTemplateBindings("a:1+1"); expect(exprSources(bindings)).toEqual(['1+1']); }); it('should detect names as value', () => { var bindings = parseTemplateBindings("a:#b"); expect(keyValues(bindings)).toEqual(['a', '#b=\$implicit']); }); it('should allow space and colon as separators', () => { var bindings = parseTemplateBindings("a:b"); expect(keys(bindings)).toEqual(['a']); expect(exprSources(bindings)).toEqual(['b']); bindings = parseTemplateBindings("a b"); expect(keys(bindings)).toEqual(['a']); expect(exprSources(bindings)).toEqual(['b']); }); it('should allow multiple pairs', () => { var bindings = parseTemplateBindings("a 1 b 2"); expect(keys(bindings)).toEqual(['a', 'a-b']); expect(exprSources(bindings)).toEqual(['1 ', '2']); }); it('should store the sources in the result', () => { var bindings = parseTemplateBindings("a 1,b 2"); expect(bindings[0].expression.source).toEqual('1'); expect(bindings[1].expression.source).toEqual('2'); }); it('should store the passed-in location', () => { var bindings = parseTemplateBindings("a 1,b 2", 'location'); expect(bindings[0].expression.location).toEqual('location'); }); it('should support var/# notation', () => { var bindings = parseTemplateBindings("var i"); expect(keyValues(bindings)).toEqual(['#i=\$implicit']); bindings = parseTemplateBindings("#i"); expect(keyValues(bindings)).toEqual(['#i=\$implicit']); bindings = parseTemplateBindings("var a; var b"); expect(keyValues(bindings)).toEqual(['#a=\$implicit', '#b=\$implicit']); bindings = parseTemplateBindings("#a; #b;"); expect(keyValues(bindings)).toEqual(['#a=\$implicit', '#b=\$implicit']); bindings = parseTemplateBindings("var i-a = k-a"); expect(keyValues(bindings)).toEqual(['#i-a=k-a']); bindings = parseTemplateBindings("keyword var item; var i = k"); expect(keyValues(bindings)).toEqual(['keyword', '#item=\$implicit', '#i=k']); bindings = parseTemplateBindings("keyword: #item; #i = k"); expect(keyValues(bindings)).toEqual(['keyword', '#item=\$implicit', '#i=k']); bindings = parseTemplateBindings("directive: var item in expr; var a = b", 'location'); expect(keyValues(bindings)) .toEqual(['directive', '#item=\$implicit', 'directive-in=expr in location', '#a=b']); }); it('should parse pipes', () => { var bindings = parseTemplateBindings('key value|pipe'); var ast = bindings[0].expression.ast; expect(ast).toBeAnInstanceOf(BindingPipe); }); }); describe('parseInterpolation', () => { it('should return null if no interpolation', () => { expect(parseInterpolation('nothing')).toBe(null); }); it('should parse no prefix/suffix interpolation', () => { var ast = parseInterpolation('{{a}}').ast; expect(ast.strings).toEqual(['', '']); expect(ast.expressions.length).toEqual(1); expect(ast.expressions[0].name).toEqual('a'); }); it('should parse prefix/suffix with multiple interpolation', () => { var originalExp = 'before {{ a }} middle {{ b }} after'; var ast = parseInterpolation(originalExp).ast; expect(new Unparser().unparse(ast)).toEqual(originalExp); }); it("should throw on empty interpolation expressions", () => { expect(() => parseInterpolation("{{}}")) .toThrowErrorWith( "Parser Error: Blank expressions are not allowed in interpolated strings"); expect(() => parseInterpolation("foo {{ }}")) .toThrowErrorWith( "Parser Error: Blank expressions are not allowed in interpolated strings"); }); }); describe("parseSimpleBinding", () => { it("should parse a field access", () => { var p = parseSimpleBinding("name"); expect(unparse(p)).toEqual("name"); }); it("should parse a constant", () => { var p = parseSimpleBinding("[1, 2]"); expect(unparse(p)).toEqual("[1, 2]"); }); it("should throw when the given expression is not just a field name", () => { expect(() => parseSimpleBinding("name + 1")) .toThrowErrorWith( 'Host binding expression can only contain field access and constants'); }); it('should throw when encountering interpolation', () => { expect(() => parseSimpleBinding('{{exp}}')) .toThrowErrorWith('Got interpolation ({{}}) where expression was expected'); }); }); describe('wrapLiteralPrimitive', () => { it('should wrap a literal primitive', () => { expect(unparse(createParser().wrapLiteralPrimitive("foo", null))).toEqual('"foo"'); }); }); }); }
modules/angular2/test/core/change_detection/parser/parser_spec.ts
1
https://github.com/angular/angular/commit/b90de665352aca95f8b82c510bc7a7856beb8821
[ 0.00017971945635508746, 0.00017217326967511326, 0.00016657763626426458, 0.00017302630294580013, 0.0000027602497993939323 ]
{ "id": 0, "code_window": [ " return ($a <= code && code <= $z) || ($A <= code && code <= $Z) || (code == $_) || (code == $$);\n", "}\n", "\n", "function isIdentifierPart(code: number): boolean {\n", " return ($a <= code && code <= $z) || ($A <= code && code <= $Z) || ($0 <= code && code <= $9) ||\n", " (code == $_) || (code == $$);\n", "}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function isIdentifier(input: string): boolean {\n", " if (input.length == 0) return false;\n", " var scanner = new _Scanner(input);\n", " if (!isIdentifierStart(scanner.peek)) return false;\n", " scanner.advance();\n", " while (scanner.peek !== $EOF) {\n", " if (!isIdentifierPart(scanner.peek)) return false;\n", " scanner.advance();\n", " }\n", " return true;\n", "}\n", "\n" ], "file_path": "modules/angular2/src/core/change_detection/parser/lexer.ts", "type": "add", "edit_start_line_idx": 397 }
library playground.hello_world.index_common_dart.ng_deps.dart; import 'hello.template.dart' as _templates; import 'hello.dart'; import 'package:angular2/angular2.dart' show Component, Directive, View, NgElement; var _visited = false; void initReflector(reflector) { if (_visited) return; _visited = true; reflector ..registerType( HelloCmp, new ReflectionInfo(const [ const Component(selector: 'hello-app'), const View(template: '<div [a]="b">{{greeting}}</div>'), _templates.HostHelloCmpTemplate ], const [ const [] ], () => new HelloCmp())); }
modules_dart/transform/test/transform/template_compiler/inline_expression_files/expected/hello.ng_deps.dart
0
https://github.com/angular/angular/commit/b90de665352aca95f8b82c510bc7a7856beb8821
[ 0.00017466870485804975, 0.00017235544510185719, 0.00016908830730244517, 0.00017330932314507663, 0.000002375938038312597 ]
{ "id": 0, "code_window": [ " return ($a <= code && code <= $z) || ($A <= code && code <= $Z) || (code == $_) || (code == $$);\n", "}\n", "\n", "function isIdentifierPart(code: number): boolean {\n", " return ($a <= code && code <= $z) || ($A <= code && code <= $Z) || ($0 <= code && code <= $9) ||\n", " (code == $_) || (code == $$);\n", "}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function isIdentifier(input: string): boolean {\n", " if (input.length == 0) return false;\n", " var scanner = new _Scanner(input);\n", " if (!isIdentifierStart(scanner.peek)) return false;\n", " scanner.advance();\n", " while (scanner.peek !== $EOF) {\n", " if (!isIdentifierPart(scanner.peek)) return false;\n", " scanner.advance();\n", " }\n", " return true;\n", "}\n", "\n" ], "file_path": "modules/angular2/src/core/change_detection/parser/lexer.ts", "type": "add", "edit_start_line_idx": 397 }
import {Injectable, Injector, Key, bind, provide} from "angular2/core"; import {reflector} from 'angular2/src/core/reflection/reflection'; import {ReflectionCapabilities} from 'angular2/src/core/reflection/reflection_capabilities'; import {getIntParameter, bindAction, microBenchmark} from 'angular2/src/testing/benchmark_util'; import {BrowserDomAdapter} from 'angular2/src/platform/browser/browser_adapter'; var count = 0; function setupReflector() { reflector.reflectionCapabilities = new ReflectionCapabilities(); } export function main() { BrowserDomAdapter.makeCurrent(); var iterations = getIntParameter('iterations'); // This benchmark does not use bootstrap and needs to create a reflector setupReflector(); var bindings = [A, B, C, D, E]; var injector = Injector.resolveAndCreate(bindings); var D_KEY = Key.get(D); var E_KEY = Key.get(E); var childInjector = injector.resolveAndCreateChild([]) .resolveAndCreateChild([]) .resolveAndCreateChild([]) .resolveAndCreateChild([]) .resolveAndCreateChild([]); var variousProviders = [A, provide(B, {useClass: C}), [D, [E]], provide(F, {useValue: 6})]; var variousProvidersResolved = Injector.resolve(variousProviders); function getByToken() { for (var i = 0; i < iterations; ++i) { injector.get(D); injector.get(E); } } function getByKey() { for (var i = 0; i < iterations; ++i) { injector.get(D_KEY); injector.get(E_KEY); } } function getChild() { for (var i = 0; i < iterations; ++i) { childInjector.get(D); childInjector.get(E); } } function instantiate() { for (var i = 0; i < iterations; ++i) { var child = injector.resolveAndCreateChild([E]); child.get(E); } } /** * Creates an injector with a variety of provider types. */ function createVariety() { for (var i = 0; i < iterations; ++i) { Injector.resolveAndCreate(variousProviders); } } /** * Same as [createVariety] but resolves providers ahead of time. */ function createVarietyResolved() { for (var i = 0; i < iterations; ++i) { Injector.fromResolvedProviders(variousProvidersResolved); } } bindAction('#getByToken', () => microBenchmark('injectAvg', iterations, getByToken)); bindAction('#getByKey', () => microBenchmark('injectAvg', iterations, getByKey)); bindAction('#getChild', () => microBenchmark('injectAvg', iterations, getChild)); bindAction('#instantiate', () => microBenchmark('injectAvg', iterations, instantiate)); bindAction('#createVariety', () => microBenchmark('injectAvg', iterations, createVariety)); bindAction('#createVarietyResolved', () => microBenchmark('injectAvg', iterations, createVarietyResolved)); } @Injectable() class A { constructor() { count++; } } @Injectable() class B { constructor(a: A) { count++; } } @Injectable() class C { constructor(b: B) { count++; } } @Injectable() class D { constructor(c: C, b: B) { count++; } } @Injectable() class E { constructor(d: D, c: C) { count++; } } @Injectable() class F { constructor(e: E, d: D) { count++; } }
modules/benchmarks/src/di/di_benchmark.ts
0
https://github.com/angular/angular/commit/b90de665352aca95f8b82c510bc7a7856beb8821
[ 0.0014380579814314842, 0.0002784730168059468, 0.00016890719416551292, 0.00017308988026343286, 0.0003496360732242465 ]
{ "id": 0, "code_window": [ " return ($a <= code && code <= $z) || ($A <= code && code <= $Z) || (code == $_) || (code == $$);\n", "}\n", "\n", "function isIdentifierPart(code: number): boolean {\n", " return ($a <= code && code <= $z) || ($A <= code && code <= $Z) || ($0 <= code && code <= $9) ||\n", " (code == $_) || (code == $$);\n", "}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function isIdentifier(input: string): boolean {\n", " if (input.length == 0) return false;\n", " var scanner = new _Scanner(input);\n", " if (!isIdentifierStart(scanner.peek)) return false;\n", " scanner.advance();\n", " while (scanner.peek !== $EOF) {\n", " if (!isIdentifierPart(scanner.peek)) return false;\n", " scanner.advance();\n", " }\n", " return true;\n", "}\n", "\n" ], "file_path": "modules/angular2/src/core/change_detection/parser/lexer.ts", "type": "add", "edit_start_line_idx": 397 }
import {BaseException, unimplemented} from 'angular2/src/facade/exceptions'; import {ViewRef, ViewRef_} from './view_ref'; import {RenderViewRef, RenderElementRef, Renderer} from 'angular2/src/core/render/api'; /** * Represents a location in a View that has an injection, change-detection and render context * associated with it. * * An `ElementRef` is created for each element in the Template that contains a Directive, Component * or data-binding. * * An `ElementRef` is backed by a render-specific element. In the browser, this is usually a DOM * element. */ export abstract class ElementRef implements RenderElementRef { /** * @internal * * Reference to the {@link ViewRef} that this `ElementRef` is part of. */ parentView: ViewRef; /** * @internal * * Index of the element inside the {@link ViewRef}. * * This is used internally by the Angular framework to locate elements. */ boundElementIndex: number; /** * The underlying native element or `null` if direct access to native elements is not supported * (e.g. when the application runs in a web worker). * * <div class="callout is-critical"> * <header>Use with caution</header> * <p> * Use this API as the last resort when direct access to DOM is needed. Use templating and * data-binding provided by Angular instead. Alternatively you take a look at {@link Renderer} * which provides API that can safely be used even when direct access to native elements is not * supported. * </p> * <p> * Relying on direct DOM access creates tight coupling between your application and rendering * layers which will make it impossible to separate the two and deploy your application into a * web worker. * </p> * </div> */ get nativeElement(): any { return unimplemented(); }; get renderView(): RenderViewRef { return unimplemented(); } } export class ElementRef_ extends ElementRef { constructor(public parentView: ViewRef, /** * Index of the element inside the {@link ViewRef}. * * This is used internally by the Angular framework to locate elements. */ public boundElementIndex: number, private _renderer: Renderer) { super(); } get renderView(): RenderViewRef { return (<ViewRef_>this.parentView).render; } set renderView(value) { unimplemented(); } get nativeElement(): any { return this._renderer.getNativeElementSync(this); } }
modules/angular2/src/core/linker/element_ref.ts
0
https://github.com/angular/angular/commit/b90de665352aca95f8b82c510bc7a7856beb8821
[ 0.0018138143932446837, 0.0003727146831806749, 0.00016157800564542413, 0.0001687648764345795, 0.000544693146366626 ]
{ "id": 1, "code_window": [ "import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';\n", "import {ListWrapper} from 'angular2/src/facade/collection';\n", "import {\n", " Lexer,\n", " EOF,\n", " Token,\n", " $PERIOD,\n", " $COLON,\n", " $SEMICOLON,\n", " $LBRACKET,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " isIdentifier,\n" ], "file_path": "modules/angular2/src/core/change_detection/parser/parser.ts", "type": "add", "edit_start_line_idx": 7 }
import {Injectable} from 'angular2/src/core/di/decorators'; import {isBlank, isPresent, StringWrapper} from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {ListWrapper} from 'angular2/src/facade/collection'; import { Lexer, EOF, Token, $PERIOD, $COLON, $SEMICOLON, $LBRACKET, $RBRACKET, $COMMA, $LBRACE, $RBRACE, $LPAREN, $RPAREN } from './lexer'; import {reflector, Reflector} from 'angular2/src/core/reflection/reflection'; import { AST, EmptyExpr, ImplicitReceiver, PropertyRead, PropertyWrite, SafePropertyRead, LiteralPrimitive, Binary, PrefixNot, Conditional, BindingPipe, Chain, KeyedRead, KeyedWrite, LiteralArray, LiteralMap, Interpolation, MethodCall, SafeMethodCall, FunctionCall, TemplateBinding, ASTWithSource, AstVisitor, Quote } from './ast'; var _implicitReceiver = new ImplicitReceiver(); // TODO(tbosch): Cannot make this const/final right now because of the transpiler... var INTERPOLATION_REGEXP = /\{\{(.*?)\}\}/g; class ParseException extends BaseException { constructor(message: string, input: string, errLocation: string, ctxLocation?: any) { super(`Parser Error: ${message} ${errLocation} [${input}] in ${ctxLocation}`); } } @Injectable() export class Parser { /** @internal */ _reflector: Reflector; constructor(/** @internal */ public _lexer: Lexer, providedReflector: Reflector = null) { this._reflector = isPresent(providedReflector) ? providedReflector : reflector; } parseAction(input: string, location: any): ASTWithSource { this._checkNoInterpolation(input, location); var tokens = this._lexer.tokenize(input); var ast = new _ParseAST(input, location, tokens, this._reflector, true).parseChain(); return new ASTWithSource(ast, input, location); } parseBinding(input: string, location: any): ASTWithSource { var ast = this._parseBindingAst(input, location); return new ASTWithSource(ast, input, location); } parseSimpleBinding(input: string, location: string): ASTWithSource { var ast = this._parseBindingAst(input, location); if (!SimpleExpressionChecker.check(ast)) { throw new ParseException( 'Host binding expression can only contain field access and constants', input, location); } return new ASTWithSource(ast, input, location); } private _parseBindingAst(input: string, location: string): AST { // Quotes expressions use 3rd-party expression language. We don't want to use // our lexer or parser for that, so we check for that ahead of time. var quote = this._parseQuote(input, location); if (isPresent(quote)) { return quote; } this._checkNoInterpolation(input, location); var tokens = this._lexer.tokenize(input); return new _ParseAST(input, location, tokens, this._reflector, false).parseChain(); } private _parseQuote(input: string, location: any): AST { if (isBlank(input)) return null; var prefixSeparatorIndex = input.indexOf(':'); if (prefixSeparatorIndex == -1) return null; var prefix = input.substring(0, prefixSeparatorIndex); var uninterpretedExpression = input.substring(prefixSeparatorIndex + 1); // while we do not interpret the expression, we do interpret the prefix var prefixTokens = this._lexer.tokenize(prefix); // quote prefix must be a single legal identifier if (prefixTokens.length != 1 || !prefixTokens[0].isIdentifier()) return null; return new Quote(prefixTokens[0].strValue, uninterpretedExpression, location); } parseTemplateBindings(input: string, location: any): TemplateBinding[] { var tokens = this._lexer.tokenize(input); return new _ParseAST(input, location, tokens, this._reflector, false).parseTemplateBindings(); } parseInterpolation(input: string, location: any): ASTWithSource { var parts = StringWrapper.split(input, INTERPOLATION_REGEXP); if (parts.length <= 1) { return null; } var strings = []; var expressions = []; for (var i = 0; i < parts.length; i++) { var part: string = parts[i]; if (i % 2 === 0) { // fixed string strings.push(part); } else if (part.trim().length > 0) { var tokens = this._lexer.tokenize(part); var ast = new _ParseAST(input, location, tokens, this._reflector, false).parseChain(); expressions.push(ast); } else { throw new ParseException('Blank expressions are not allowed in interpolated strings', input, `at column ${this._findInterpolationErrorColumn(parts, i)} in`, location); } } return new ASTWithSource(new Interpolation(strings, expressions), input, location); } wrapLiteralPrimitive(input: string, location: any): ASTWithSource { return new ASTWithSource(new LiteralPrimitive(input), input, location); } private _checkNoInterpolation(input: string, location: any): void { var parts = StringWrapper.split(input, INTERPOLATION_REGEXP); if (parts.length > 1) { throw new ParseException('Got interpolation ({{}}) where expression was expected', input, `at column ${this._findInterpolationErrorColumn(parts, 1)} in`, location); } } private _findInterpolationErrorColumn(parts: string[], partInErrIdx: number): number { var errLocation = ''; for (var j = 0; j < partInErrIdx; j++) { errLocation += j % 2 === 0 ? parts[j] : `{{${parts[j]}}}`; } return errLocation.length; } } export class _ParseAST { index: number = 0; constructor(public input: string, public location: any, public tokens: any[], public reflector: Reflector, public parseAction: boolean) {} peek(offset: number): Token { var i = this.index + offset; return i < this.tokens.length ? this.tokens[i] : EOF; } get next(): Token { return this.peek(0); } get inputIndex(): number { return (this.index < this.tokens.length) ? this.next.index : this.input.length; } advance() { this.index++; } optionalCharacter(code: number): boolean { if (this.next.isCharacter(code)) { this.advance(); return true; } else { return false; } } optionalKeywordVar(): boolean { if (this.peekKeywordVar()) { this.advance(); return true; } else { return false; } } peekKeywordVar(): boolean { return this.next.isKeywordVar() || this.next.isOperator('#'); } expectCharacter(code: number) { if (this.optionalCharacter(code)) return; this.error(`Missing expected ${StringWrapper.fromCharCode(code)}`); } optionalOperator(op: string): boolean { if (this.next.isOperator(op)) { this.advance(); return true; } else { return false; } } expectOperator(operator: string) { if (this.optionalOperator(operator)) return; this.error(`Missing expected operator ${operator}`); } expectIdentifierOrKeyword(): string { var n = this.next; if (!n.isIdentifier() && !n.isKeyword()) { this.error(`Unexpected token ${n}, expected identifier or keyword`); } this.advance(); return n.toString(); } expectIdentifierOrKeywordOrString(): string { var n = this.next; if (!n.isIdentifier() && !n.isKeyword() && !n.isString()) { this.error(`Unexpected token ${n}, expected identifier, keyword, or string`); } this.advance(); return n.toString(); } parseChain(): AST { var exprs = []; while (this.index < this.tokens.length) { var expr = this.parsePipe(); exprs.push(expr); if (this.optionalCharacter($SEMICOLON)) { if (!this.parseAction) { this.error("Binding expression cannot contain chained expression"); } while (this.optionalCharacter($SEMICOLON)) { } // read all semicolons } else if (this.index < this.tokens.length) { this.error(`Unexpected token '${this.next}'`); } } if (exprs.length == 0) return new EmptyExpr(); if (exprs.length == 1) return exprs[0]; return new Chain(exprs); } parsePipe(): AST { var result = this.parseExpression(); if (this.optionalOperator("|")) { if (this.parseAction) { this.error("Cannot have a pipe in an action expression"); } do { var name = this.expectIdentifierOrKeyword(); var args = []; while (this.optionalCharacter($COLON)) { args.push(this.parseExpression()); } result = new BindingPipe(result, name, args); } while (this.optionalOperator("|")); } return result; } parseExpression(): AST { return this.parseConditional(); } parseConditional(): AST { var start = this.inputIndex; var result = this.parseLogicalOr(); if (this.optionalOperator('?')) { var yes = this.parsePipe(); if (!this.optionalCharacter($COLON)) { var end = this.inputIndex; var expression = this.input.substring(start, end); this.error(`Conditional expression ${expression} requires all 3 expressions`); } var no = this.parsePipe(); return new Conditional(result, yes, no); } else { return result; } } parseLogicalOr(): AST { // '||' var result = this.parseLogicalAnd(); while (this.optionalOperator('||')) { result = new Binary('||', result, this.parseLogicalAnd()); } return result; } parseLogicalAnd(): AST { // '&&' var result = this.parseEquality(); while (this.optionalOperator('&&')) { result = new Binary('&&', result, this.parseEquality()); } return result; } parseEquality(): AST { // '==','!=','===','!==' var result = this.parseRelational(); while (true) { if (this.optionalOperator('==')) { result = new Binary('==', result, this.parseRelational()); } else if (this.optionalOperator('===')) { result = new Binary('===', result, this.parseRelational()); } else if (this.optionalOperator('!=')) { result = new Binary('!=', result, this.parseRelational()); } else if (this.optionalOperator('!==')) { result = new Binary('!==', result, this.parseRelational()); } else { return result; } } } parseRelational(): AST { // '<', '>', '<=', '>=' var result = this.parseAdditive(); while (true) { if (this.optionalOperator('<')) { result = new Binary('<', result, this.parseAdditive()); } else if (this.optionalOperator('>')) { result = new Binary('>', result, this.parseAdditive()); } else if (this.optionalOperator('<=')) { result = new Binary('<=', result, this.parseAdditive()); } else if (this.optionalOperator('>=')) { result = new Binary('>=', result, this.parseAdditive()); } else { return result; } } } parseAdditive(): AST { // '+', '-' var result = this.parseMultiplicative(); while (true) { if (this.optionalOperator('+')) { result = new Binary('+', result, this.parseMultiplicative()); } else if (this.optionalOperator('-')) { result = new Binary('-', result, this.parseMultiplicative()); } else { return result; } } } parseMultiplicative(): AST { // '*', '%', '/' var result = this.parsePrefix(); while (true) { if (this.optionalOperator('*')) { result = new Binary('*', result, this.parsePrefix()); } else if (this.optionalOperator('%')) { result = new Binary('%', result, this.parsePrefix()); } else if (this.optionalOperator('/')) { result = new Binary('/', result, this.parsePrefix()); } else { return result; } } } parsePrefix(): AST { if (this.optionalOperator('+')) { return this.parsePrefix(); } else if (this.optionalOperator('-')) { return new Binary('-', new LiteralPrimitive(0), this.parsePrefix()); } else if (this.optionalOperator('!')) { return new PrefixNot(this.parsePrefix()); } else { return this.parseCallChain(); } } parseCallChain(): AST { var result = this.parsePrimary(); while (true) { if (this.optionalCharacter($PERIOD)) { result = this.parseAccessMemberOrMethodCall(result, false); } else if (this.optionalOperator('?.')) { result = this.parseAccessMemberOrMethodCall(result, true); } else if (this.optionalCharacter($LBRACKET)) { var key = this.parsePipe(); this.expectCharacter($RBRACKET); if (this.optionalOperator("=")) { var value = this.parseConditional(); result = new KeyedWrite(result, key, value); } else { result = new KeyedRead(result, key); } } else if (this.optionalCharacter($LPAREN)) { var args = this.parseCallArguments(); this.expectCharacter($RPAREN); result = new FunctionCall(result, args); } else { return result; } } } parsePrimary(): AST { if (this.optionalCharacter($LPAREN)) { let result = this.parsePipe(); this.expectCharacter($RPAREN); return result; } else if (this.next.isKeywordNull() || this.next.isKeywordUndefined()) { this.advance(); return new LiteralPrimitive(null); } else if (this.next.isKeywordTrue()) { this.advance(); return new LiteralPrimitive(true); } else if (this.next.isKeywordFalse()) { this.advance(); return new LiteralPrimitive(false); } else if (this.optionalCharacter($LBRACKET)) { var elements = this.parseExpressionList($RBRACKET); this.expectCharacter($RBRACKET); return new LiteralArray(elements); } else if (this.next.isCharacter($LBRACE)) { return this.parseLiteralMap(); } else if (this.next.isIdentifier()) { return this.parseAccessMemberOrMethodCall(_implicitReceiver, false); } else if (this.next.isNumber()) { var value = this.next.toNumber(); this.advance(); return new LiteralPrimitive(value); } else if (this.next.isString()) { var literalValue = this.next.toString(); this.advance(); return new LiteralPrimitive(literalValue); } else if (this.index >= this.tokens.length) { this.error(`Unexpected end of expression: ${this.input}`); } else { this.error(`Unexpected token ${this.next}`); } // error() throws, so we don't reach here. throw new BaseException("Fell through all cases in parsePrimary"); } parseExpressionList(terminator: number): any[] { var result = []; if (!this.next.isCharacter(terminator)) { do { result.push(this.parsePipe()); } while (this.optionalCharacter($COMMA)); } return result; } parseLiteralMap(): LiteralMap { var keys = []; var values = []; this.expectCharacter($LBRACE); if (!this.optionalCharacter($RBRACE)) { do { var key = this.expectIdentifierOrKeywordOrString(); keys.push(key); this.expectCharacter($COLON); values.push(this.parsePipe()); } while (this.optionalCharacter($COMMA)); this.expectCharacter($RBRACE); } return new LiteralMap(keys, values); } parseAccessMemberOrMethodCall(receiver: AST, isSafe: boolean = false): AST { let id = this.expectIdentifierOrKeyword(); if (this.optionalCharacter($LPAREN)) { let args = this.parseCallArguments(); this.expectCharacter($RPAREN); let fn = this.reflector.method(id); return isSafe ? new SafeMethodCall(receiver, id, fn, args) : new MethodCall(receiver, id, fn, args); } else { if (isSafe) { if (this.optionalOperator("=")) { this.error("The '?.' operator cannot be used in the assignment"); } else { return new SafePropertyRead(receiver, id, this.reflector.getter(id)); } } else { if (this.optionalOperator("=")) { if (!this.parseAction) { this.error("Bindings cannot contain assignments"); } let value = this.parseConditional(); return new PropertyWrite(receiver, id, this.reflector.setter(id), value); } else { return new PropertyRead(receiver, id, this.reflector.getter(id)); } } } return null; } parseCallArguments(): BindingPipe[] { if (this.next.isCharacter($RPAREN)) return []; var positionals = []; do { positionals.push(this.parsePipe()); } while (this.optionalCharacter($COMMA)); return positionals; } parseBlockContent(): AST { if (!this.parseAction) { this.error("Binding expression cannot contain chained expression"); } var exprs = []; while (this.index < this.tokens.length && !this.next.isCharacter($RBRACE)) { var expr = this.parseExpression(); exprs.push(expr); if (this.optionalCharacter($SEMICOLON)) { while (this.optionalCharacter($SEMICOLON)) { } // read all semicolons } } if (exprs.length == 0) return new EmptyExpr(); if (exprs.length == 1) return exprs[0]; return new Chain(exprs); } /** * An identifier, a keyword, a string with an optional `-` inbetween. */ expectTemplateBindingKey(): string { var result = ''; var operatorFound = false; do { result += this.expectIdentifierOrKeywordOrString(); operatorFound = this.optionalOperator('-'); if (operatorFound) { result += '-'; } } while (operatorFound); return result.toString(); } parseTemplateBindings(): any[] { var bindings = []; var prefix = null; while (this.index < this.tokens.length) { var keyIsVar: boolean = this.optionalKeywordVar(); var key = this.expectTemplateBindingKey(); if (!keyIsVar) { if (prefix == null) { prefix = key; } else { key = prefix + '-' + key; } } this.optionalCharacter($COLON); var name = null; var expression = null; if (keyIsVar) { if (this.optionalOperator("=")) { name = this.expectTemplateBindingKey(); } else { name = '\$implicit'; } } else if (this.next !== EOF && !this.peekKeywordVar()) { var start = this.inputIndex; var ast = this.parsePipe(); var source = this.input.substring(start, this.inputIndex); expression = new ASTWithSource(ast, source, this.location); } bindings.push(new TemplateBinding(key, keyIsVar, name, expression)); if (!this.optionalCharacter($SEMICOLON)) { this.optionalCharacter($COMMA); } } return bindings; } error(message: string, index: number = null) { if (isBlank(index)) index = this.index; var location = (index < this.tokens.length) ? `at column ${this.tokens[index].index + 1} in` : `at the end of the expression`; throw new ParseException(message, this.input, location, this.location); } } class SimpleExpressionChecker implements AstVisitor { static check(ast: AST): boolean { var s = new SimpleExpressionChecker(); ast.visit(s); return s.simple; } simple = true; visitImplicitReceiver(ast: ImplicitReceiver) {} visitInterpolation(ast: Interpolation) { this.simple = false; } visitLiteralPrimitive(ast: LiteralPrimitive) {} visitPropertyRead(ast: PropertyRead) {} visitPropertyWrite(ast: PropertyWrite) { this.simple = false; } visitSafePropertyRead(ast: SafePropertyRead) { this.simple = false; } visitMethodCall(ast: MethodCall) { this.simple = false; } visitSafeMethodCall(ast: SafeMethodCall) { this.simple = false; } visitFunctionCall(ast: FunctionCall) { this.simple = false; } visitLiteralArray(ast: LiteralArray) { this.visitAll(ast.expressions); } visitLiteralMap(ast: LiteralMap) { this.visitAll(ast.values); } visitBinary(ast: Binary) { this.simple = false; } visitPrefixNot(ast: PrefixNot) { this.simple = false; } visitConditional(ast: Conditional) { this.simple = false; } visitPipe(ast: BindingPipe) { this.simple = false; } visitKeyedRead(ast: KeyedRead) { this.simple = false; } visitKeyedWrite(ast: KeyedWrite) { this.simple = false; } visitAll(asts: any[]): any[] { var res = ListWrapper.createFixedSize(asts.length); for (var i = 0; i < asts.length; ++i) { res[i] = asts[i].visit(this); } return res; } visitChain(ast: Chain) { this.simple = false; } visitQuote(ast: Quote) { this.simple = false; } }
modules/angular2/src/core/change_detection/parser/parser.ts
1
https://github.com/angular/angular/commit/b90de665352aca95f8b82c510bc7a7856beb8821
[ 0.9857136011123657, 0.03194228559732437, 0.00015979989257175475, 0.0001752290118020028, 0.16444379091262817 ]
{ "id": 1, "code_window": [ "import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';\n", "import {ListWrapper} from 'angular2/src/facade/collection';\n", "import {\n", " Lexer,\n", " EOF,\n", " Token,\n", " $PERIOD,\n", " $COLON,\n", " $SEMICOLON,\n", " $LBRACKET,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " isIdentifier,\n" ], "file_path": "modules/angular2/src/core/change_detection/parser/parser.ts", "type": "add", "edit_start_line_idx": 7 }
import {RuleFailure} from 'tslint/lib/lint'; import {AbstractRule} from 'tslint/lib/rules'; import {RuleWalker} from 'tslint/lib/language/walker'; import * as ts from 'tslint/node_modules/typescript'; export class Rule extends AbstractRule { public apply(sourceFile: ts.SourceFile): RuleFailure[] { const typedefWalker = new TypedefWalker(sourceFile, this.getOptions()); return this.applyWithWalker(typedefWalker); } } class TypedefWalker extends RuleWalker { protected visitPropertyDeclaration(node: ts.PropertyDeclaration): void { this.assertInternalAnnotationPresent(node); super.visitPropertyDeclaration(node); } public visitMethodDeclaration(node: ts.MethodDeclaration): void { this.assertInternalAnnotationPresent(node); super.visitMethodDeclaration(node); } private hasInternalAnnotation(range: ts.CommentRange): boolean { let text = this.getSourceFile().text; let comment = text.substring(range.pos, range.end); return comment.indexOf("@internal") >= 0; } private assertInternalAnnotationPresent(node: ts.Declaration) { if (node.name.getText().charAt(0) !== '_') return; if (node.modifiers && node.modifiers.flags & ts.NodeFlags.Private) return; const ranges = ts.getLeadingCommentRanges(this.getSourceFile().text, node.pos); if (ranges) { for (let i = 0; i < ranges.length; i++) { if (this.hasInternalAnnotation(ranges[i])) return; } } this.addFailure(this.createFailure( node.getStart(), node.getWidth(), `module-private member ${node.name.getText()} must be annotated @internal`)); } }
tools/tslint/requireInternalWithUnderscoreRule.ts
0
https://github.com/angular/angular/commit/b90de665352aca95f8b82c510bc7a7856beb8821
[ 0.00017849258438218385, 0.00017507966549601406, 0.00017319749167654663, 0.00017447062418796122, 0.0000018330425746171386 ]
{ "id": 1, "code_window": [ "import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';\n", "import {ListWrapper} from 'angular2/src/facade/collection';\n", "import {\n", " Lexer,\n", " EOF,\n", " Token,\n", " $PERIOD,\n", " $COLON,\n", " $SEMICOLON,\n", " $LBRACKET,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " isIdentifier,\n" ], "file_path": "modules/angular2/src/core/change_detection/parser/parser.ts", "type": "add", "edit_start_line_idx": 7 }
modules/angular2/docs/core/11_shadow_dom.md
0
https://github.com/angular/angular/commit/b90de665352aca95f8b82c510bc7a7856beb8821
[ 0.00017464488337282091, 0.00017464488337282091, 0.00017464488337282091, 0.00017464488337282091, 0 ]
{ "id": 1, "code_window": [ "import {BaseException, WrappedException} from 'angular2/src/facade/exceptions';\n", "import {ListWrapper} from 'angular2/src/facade/collection';\n", "import {\n", " Lexer,\n", " EOF,\n", " Token,\n", " $PERIOD,\n", " $COLON,\n", " $SEMICOLON,\n", " $LBRACKET,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " isIdentifier,\n" ], "file_path": "modules/angular2/src/core/change_detection/parser/parser.ts", "type": "add", "edit_start_line_idx": 7 }
library web_foo; import 'package:angular2/bootstrap.dart'; import 'package:angular2/src/core/reflection/reflection.dart'; import 'package:angular2/src/core/reflection/reflection_capabilities.dart'; void main() { reflector.reflectionCapabilities = new ReflectionCapabilities(); bootstrap(MyComponent); }
modules_dart/transform/test/transform/reflection_remover/log_mirrors_files/index.dart
0
https://github.com/angular/angular/commit/b90de665352aca95f8b82c510bc7a7856beb8821
[ 0.00017464488337282091, 0.00017359817866235971, 0.00017255147395189852, 0.00017359817866235971, 0.0000010467047104611993 ]
{ "id": 2, "code_window": [ " private _parseQuote(input: string, location: any): AST {\n", " if (isBlank(input)) return null;\n", " var prefixSeparatorIndex = input.indexOf(':');\n", " if (prefixSeparatorIndex == -1) return null;\n", " var prefix = input.substring(0, prefixSeparatorIndex);\n", " var uninterpretedExpression = input.substring(prefixSeparatorIndex + 1);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " var prefix = input.substring(0, prefixSeparatorIndex).trim();\n", " if (!isIdentifier(prefix)) return null;\n" ], "file_path": "modules/angular2/src/core/change_detection/parser/parser.ts", "type": "replace", "edit_start_line_idx": 107 }
import {Injectable} from 'angular2/src/core/di/decorators'; import {ListWrapper, SetWrapper} from "angular2/src/facade/collection"; import {NumberWrapper, StringJoiner, StringWrapper, isPresent} from "angular2/src/facade/lang"; import {BaseException} from 'angular2/src/facade/exceptions'; export enum TokenType { Character, Identifier, Keyword, String, Operator, Number } @Injectable() export class Lexer { tokenize(text: string): any[] { var scanner = new _Scanner(text); var tokens = []; var token = scanner.scanToken(); while (token != null) { tokens.push(token); token = scanner.scanToken(); } return tokens; } } export class Token { constructor(public index: number, public type: TokenType, public numValue: number, public strValue: string) {} isCharacter(code: number): boolean { return (this.type == TokenType.Character && this.numValue == code); } isNumber(): boolean { return (this.type == TokenType.Number); } isString(): boolean { return (this.type == TokenType.String); } isOperator(operater: string): boolean { return (this.type == TokenType.Operator && this.strValue == operater); } isIdentifier(): boolean { return (this.type == TokenType.Identifier); } isKeyword(): boolean { return (this.type == TokenType.Keyword); } isKeywordVar(): boolean { return (this.type == TokenType.Keyword && this.strValue == "var"); } isKeywordNull(): boolean { return (this.type == TokenType.Keyword && this.strValue == "null"); } isKeywordUndefined(): boolean { return (this.type == TokenType.Keyword && this.strValue == "undefined"); } isKeywordTrue(): boolean { return (this.type == TokenType.Keyword && this.strValue == "true"); } isKeywordFalse(): boolean { return (this.type == TokenType.Keyword && this.strValue == "false"); } toNumber(): number { // -1 instead of NULL ok? return (this.type == TokenType.Number) ? this.numValue : -1; } toString(): string { switch (this.type) { case TokenType.Character: case TokenType.Identifier: case TokenType.Keyword: case TokenType.Operator: case TokenType.String: return this.strValue; case TokenType.Number: return this.numValue.toString(); default: return null; } } } function newCharacterToken(index: number, code: number): Token { return new Token(index, TokenType.Character, code, StringWrapper.fromCharCode(code)); } function newIdentifierToken(index: number, text: string): Token { return new Token(index, TokenType.Identifier, 0, text); } function newKeywordToken(index: number, text: string): Token { return new Token(index, TokenType.Keyword, 0, text); } function newOperatorToken(index: number, text: string): Token { return new Token(index, TokenType.Operator, 0, text); } function newStringToken(index: number, text: string): Token { return new Token(index, TokenType.String, 0, text); } function newNumberToken(index: number, n: number): Token { return new Token(index, TokenType.Number, n, ""); } export var EOF: Token = new Token(-1, TokenType.Character, 0, ""); export const $EOF = 0; export const $TAB = 9; export const $LF = 10; export const $VTAB = 11; export const $FF = 12; export const $CR = 13; export const $SPACE = 32; export const $BANG = 33; export const $DQ = 34; export const $HASH = 35; export const $$ = 36; export const $PERCENT = 37; export const $AMPERSAND = 38; export const $SQ = 39; export const $LPAREN = 40; export const $RPAREN = 41; export const $STAR = 42; export const $PLUS = 43; export const $COMMA = 44; export const $MINUS = 45; export const $PERIOD = 46; export const $SLASH = 47; export const $COLON = 58; export const $SEMICOLON = 59; export const $LT = 60; export const $EQ = 61; export const $GT = 62; export const $QUESTION = 63; const $0 = 48; const $9 = 57; const $A = 65, $E = 69, $Z = 90; export const $LBRACKET = 91; export const $BACKSLASH = 92; export const $RBRACKET = 93; const $CARET = 94; const $_ = 95; const $a = 97, $e = 101, $f = 102, $n = 110, $r = 114, $t = 116, $u = 117, $v = 118, $z = 122; export const $LBRACE = 123; export const $BAR = 124; export const $RBRACE = 125; const $NBSP = 160; export class ScannerError extends BaseException { constructor(public message) { super(); } toString(): string { return this.message; } } class _Scanner { length: number; peek: number = 0; index: number = -1; constructor(public input: string) { this.length = input.length; this.advance(); } advance() { this.peek = ++this.index >= this.length ? $EOF : StringWrapper.charCodeAt(this.input, this.index); } scanToken(): Token { var input = this.input, length = this.length, peek = this.peek, index = this.index; // Skip whitespace. while (peek <= $SPACE) { if (++index >= length) { peek = $EOF; break; } else { peek = StringWrapper.charCodeAt(input, index); } } this.peek = peek; this.index = index; if (index >= length) { return null; } // Handle identifiers and numbers. if (isIdentifierStart(peek)) return this.scanIdentifier(); if (isDigit(peek)) return this.scanNumber(index); var start: number = index; switch (peek) { case $PERIOD: this.advance(); return isDigit(this.peek) ? this.scanNumber(start) : newCharacterToken(start, $PERIOD); case $LPAREN: case $RPAREN: case $LBRACE: case $RBRACE: case $LBRACKET: case $RBRACKET: case $COMMA: case $COLON: case $SEMICOLON: return this.scanCharacter(start, peek); case $SQ: case $DQ: return this.scanString(); case $HASH: case $PLUS: case $MINUS: case $STAR: case $SLASH: case $PERCENT: case $CARET: return this.scanOperator(start, StringWrapper.fromCharCode(peek)); case $QUESTION: return this.scanComplexOperator(start, '?', $PERIOD, '.'); case $LT: case $GT: return this.scanComplexOperator(start, StringWrapper.fromCharCode(peek), $EQ, '='); case $BANG: case $EQ: return this.scanComplexOperator(start, StringWrapper.fromCharCode(peek), $EQ, '=', $EQ, '='); case $AMPERSAND: return this.scanComplexOperator(start, '&', $AMPERSAND, '&'); case $BAR: return this.scanComplexOperator(start, '|', $BAR, '|'); case $NBSP: while (isWhitespace(this.peek)) this.advance(); return this.scanToken(); } this.error(`Unexpected character [${StringWrapper.fromCharCode(peek)}]`, 0); return null; } scanCharacter(start: number, code: number): Token { assert(this.peek == code); this.advance(); return newCharacterToken(start, code); } scanOperator(start: number, str: string): Token { assert(this.peek == StringWrapper.charCodeAt(str, 0)); assert(SetWrapper.has(OPERATORS, str)); this.advance(); return newOperatorToken(start, str); } /** * Tokenize a 2/3 char long operator * * @param start start index in the expression * @param one first symbol (always part of the operator) * @param twoCode code point for the second symbol * @param two second symbol (part of the operator when the second code point matches) * @param threeCode code point for the third symbol * @param three third symbol (part of the operator when provided and matches source expression) * @returns {Token} */ scanComplexOperator(start: number, one: string, twoCode: number, two: string, threeCode?: number, three?: string): Token { assert(this.peek == StringWrapper.charCodeAt(one, 0)); this.advance(); var str: string = one; if (this.peek == twoCode) { this.advance(); str += two; } if (isPresent(threeCode) && this.peek == threeCode) { this.advance(); str += three; } assert(SetWrapper.has(OPERATORS, str)); return newOperatorToken(start, str); } scanIdentifier(): Token { assert(isIdentifierStart(this.peek)); var start: number = this.index; this.advance(); while (isIdentifierPart(this.peek)) this.advance(); var str: string = this.input.substring(start, this.index); if (SetWrapper.has(KEYWORDS, str)) { return newKeywordToken(start, str); } else { return newIdentifierToken(start, str); } } scanNumber(start: number): Token { assert(isDigit(this.peek)); var simple: boolean = (this.index === start); this.advance(); // Skip initial digit. while (true) { if (isDigit(this.peek)) { // Do nothing. } else if (this.peek == $PERIOD) { simple = false; } else if (isExponentStart(this.peek)) { this.advance(); if (isExponentSign(this.peek)) this.advance(); if (!isDigit(this.peek)) this.error('Invalid exponent', -1); simple = false; } else { break; } this.advance(); } var str: string = this.input.substring(start, this.index); // TODO var value: number = simple ? NumberWrapper.parseIntAutoRadix(str) : NumberWrapper.parseFloat(str); return newNumberToken(start, value); } scanString(): Token { assert(this.peek == $SQ || this.peek == $DQ); var start: number = this.index; var quote: number = this.peek; this.advance(); // Skip initial quote. var buffer: StringJoiner; var marker: number = this.index; var input: string = this.input; while (this.peek != quote) { if (this.peek == $BACKSLASH) { if (buffer == null) buffer = new StringJoiner(); buffer.add(input.substring(marker, this.index)); this.advance(); var unescapedCode: number; if (this.peek == $u) { // 4 character hex code for unicode character. var hex: string = input.substring(this.index + 1, this.index + 5); try { unescapedCode = NumberWrapper.parseInt(hex, 16); } catch (e) { this.error(`Invalid unicode escape [\\u${hex}]`, 0); } for (var i: number = 0; i < 5; i++) { this.advance(); } } else { unescapedCode = unescape(this.peek); this.advance(); } buffer.add(StringWrapper.fromCharCode(unescapedCode)); marker = this.index; } else if (this.peek == $EOF) { this.error('Unterminated quote', 0); } else { this.advance(); } } var last: string = input.substring(marker, this.index); this.advance(); // Skip terminating quote. // Compute the unescaped string value. var unescaped: string = last; if (buffer != null) { buffer.add(last); unescaped = buffer.toString(); } return newStringToken(start, unescaped); } error(message: string, offset: number) { var position: number = this.index + offset; throw new ScannerError( `Lexer Error: ${message} at column ${position} in expression [${this.input}]`); } } function isWhitespace(code: number): boolean { return (code >= $TAB && code <= $SPACE) || (code == $NBSP); } function isIdentifierStart(code: number): boolean { return ($a <= code && code <= $z) || ($A <= code && code <= $Z) || (code == $_) || (code == $$); } function isIdentifierPart(code: number): boolean { return ($a <= code && code <= $z) || ($A <= code && code <= $Z) || ($0 <= code && code <= $9) || (code == $_) || (code == $$); } function isDigit(code: number): boolean { return $0 <= code && code <= $9; } function isExponentStart(code: number): boolean { return code == $e || code == $E; } function isExponentSign(code: number): boolean { return code == $MINUS || code == $PLUS; } function unescape(code: number): number { switch (code) { case $n: return $LF; case $f: return $FF; case $r: return $CR; case $t: return $TAB; case $v: return $VTAB; default: return code; } } var OPERATORS = SetWrapper.createFromList([ '+', '-', '*', '/', '%', '^', '=', '==', '!=', '===', '!==', '<', '>', '<=', '>=', '&&', '||', '&', '|', '!', '?', '#', '?.' ]); var KEYWORDS = SetWrapper.createFromList(['var', 'null', 'undefined', 'true', 'false', 'if', 'else']);
modules/angular2/src/core/change_detection/parser/lexer.ts
1
https://github.com/angular/angular/commit/b90de665352aca95f8b82c510bc7a7856beb8821
[ 0.03667253255844116, 0.0019410372478887439, 0.00016635667998343706, 0.0001730870280880481, 0.006019173189997673 ]
{ "id": 2, "code_window": [ " private _parseQuote(input: string, location: any): AST {\n", " if (isBlank(input)) return null;\n", " var prefixSeparatorIndex = input.indexOf(':');\n", " if (prefixSeparatorIndex == -1) return null;\n", " var prefix = input.substring(0, prefixSeparatorIndex);\n", " var uninterpretedExpression = input.substring(prefixSeparatorIndex + 1);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " var prefix = input.substring(0, prefixSeparatorIndex).trim();\n", " if (!isIdentifier(prefix)) return null;\n" ], "file_path": "modules/angular2/src/core/change_detection/parser/parser.ts", "type": "replace", "edit_start_line_idx": 107 }
library web_foo; import 'package:angular2/src/core/application.dart'; import 'package:angular2/src/core/reflection/reflection.dart'; import 'package:angular2/src/core/reflection/reflection_capabilities.dart'; import 'hello.ng_deps.dart' deferred as a; // ng_deps. Should be rewritten. import 'b.dart' deferred as b; // No ng_deps. Shouldn't be rewritten. void main() { reflector.reflectionCapabilities = new ReflectionCapabilities(); a.loadLibrary().then((_) { a.initReflector(); }).then((_) { bootstrap(a.HelloCmp); }); b.loadLibrary(); }
modules_dart/transform/test/transform/deferred_rewriter/complex_deferred_example/expected/index.dart
0
https://github.com/angular/angular/commit/b90de665352aca95f8b82c510bc7a7856beb8821
[ 0.00017884215048979968, 0.0001785752538125962, 0.00017830835713539273, 0.0001785752538125962, 2.6689667720347643e-7 ]
{ "id": 2, "code_window": [ " private _parseQuote(input: string, location: any): AST {\n", " if (isBlank(input)) return null;\n", " var prefixSeparatorIndex = input.indexOf(':');\n", " if (prefixSeparatorIndex == -1) return null;\n", " var prefix = input.substring(0, prefixSeparatorIndex);\n", " var uninterpretedExpression = input.substring(prefixSeparatorIndex + 1);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " var prefix = input.substring(0, prefixSeparatorIndex).trim();\n", " if (!isIdentifier(prefix)) return null;\n" ], "file_path": "modules/angular2/src/core/change_detection/parser/parser.ts", "type": "replace", "edit_start_line_idx": 107 }
export {Sampler, SampleState} from './src/sampler'; export {Metric} from './src/metric'; export {Validator} from './src/validator'; export {Reporter} from './src/reporter'; export {WebDriverExtension, PerfLogFeatures} from './src/web_driver_extension'; export {WebDriverAdapter} from './src/web_driver_adapter'; export {SizeValidator} from './src/validator/size_validator'; export {RegressionSlopeValidator} from './src/validator/regression_slope_validator'; export {ConsoleReporter} from './src/reporter/console_reporter'; export {JsonFileReporter} from './src/reporter/json_file_reporter'; export {SampleDescription} from './src/sample_description'; export {PerflogMetric} from './src/metric/perflog_metric'; export {ChromeDriverExtension} from './src/webdriver/chrome_driver_extension'; export {FirefoxDriverExtension} from './src/webdriver/firefox_driver_extension'; export {IOsDriverExtension} from './src/webdriver/ios_driver_extension'; export {Runner} from './src/runner'; export {Options} from './src/common_options'; export {MeasureValues} from './src/measure_values'; export {MultiMetric} from './src/metric/multi_metric'; export {MultiReporter} from './src/reporter/multi_reporter'; export {bind, provide, Injector, OpaqueToken} from 'angular2/src/core/di';
modules/benchpress/common.ts
0
https://github.com/angular/angular/commit/b90de665352aca95f8b82c510bc7a7856beb8821
[ 0.0001758984726620838, 0.0001751622330630198, 0.00017466337885707617, 0.0001749248622218147, 5.314286113389244e-7 ]
{ "id": 2, "code_window": [ " private _parseQuote(input: string, location: any): AST {\n", " if (isBlank(input)) return null;\n", " var prefixSeparatorIndex = input.indexOf(':');\n", " if (prefixSeparatorIndex == -1) return null;\n", " var prefix = input.substring(0, prefixSeparatorIndex);\n", " var uninterpretedExpression = input.substring(prefixSeparatorIndex + 1);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " var prefix = input.substring(0, prefixSeparatorIndex).trim();\n", " if (!isIdentifier(prefix)) return null;\n" ], "file_path": "modules/angular2/src/core/change_detection/parser/parser.ts", "type": "replace", "edit_start_line_idx": 107 }
modules/angular2/docs/core/06_viewport_directive.md
0
https://github.com/angular/angular/commit/b90de665352aca95f8b82c510bc7a7856beb8821
[ 0.00017451471649110317, 0.00017451471649110317, 0.00017451471649110317, 0.00017451471649110317, 0 ]
{ "id": 3, "code_window": [ " var uninterpretedExpression = input.substring(prefixSeparatorIndex + 1);\n", "\n", " // while we do not interpret the expression, we do interpret the prefix\n", " var prefixTokens = this._lexer.tokenize(prefix);\n", "\n", " // quote prefix must be a single legal identifier\n", " if (prefixTokens.length != 1 || !prefixTokens[0].isIdentifier()) return null;\n", " return new Quote(prefixTokens[0].strValue, uninterpretedExpression, location);\n", " }\n", "\n", " parseTemplateBindings(input: string, location: any): TemplateBinding[] {\n", " var tokens = this._lexer.tokenize(input);\n", " return new _ParseAST(input, location, tokens, this._reflector, false).parseTemplateBindings();\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return new Quote(prefix, uninterpretedExpression, location);\n" ], "file_path": "modules/angular2/src/core/change_detection/parser/parser.ts", "type": "replace", "edit_start_line_idx": 109 }
import {Injectable} from 'angular2/src/core/di/decorators'; import {isBlank, isPresent, StringWrapper} from 'angular2/src/facade/lang'; import {BaseException, WrappedException} from 'angular2/src/facade/exceptions'; import {ListWrapper} from 'angular2/src/facade/collection'; import { Lexer, EOF, Token, $PERIOD, $COLON, $SEMICOLON, $LBRACKET, $RBRACKET, $COMMA, $LBRACE, $RBRACE, $LPAREN, $RPAREN } from './lexer'; import {reflector, Reflector} from 'angular2/src/core/reflection/reflection'; import { AST, EmptyExpr, ImplicitReceiver, PropertyRead, PropertyWrite, SafePropertyRead, LiteralPrimitive, Binary, PrefixNot, Conditional, BindingPipe, Chain, KeyedRead, KeyedWrite, LiteralArray, LiteralMap, Interpolation, MethodCall, SafeMethodCall, FunctionCall, TemplateBinding, ASTWithSource, AstVisitor, Quote } from './ast'; var _implicitReceiver = new ImplicitReceiver(); // TODO(tbosch): Cannot make this const/final right now because of the transpiler... var INTERPOLATION_REGEXP = /\{\{(.*?)\}\}/g; class ParseException extends BaseException { constructor(message: string, input: string, errLocation: string, ctxLocation?: any) { super(`Parser Error: ${message} ${errLocation} [${input}] in ${ctxLocation}`); } } @Injectable() export class Parser { /** @internal */ _reflector: Reflector; constructor(/** @internal */ public _lexer: Lexer, providedReflector: Reflector = null) { this._reflector = isPresent(providedReflector) ? providedReflector : reflector; } parseAction(input: string, location: any): ASTWithSource { this._checkNoInterpolation(input, location); var tokens = this._lexer.tokenize(input); var ast = new _ParseAST(input, location, tokens, this._reflector, true).parseChain(); return new ASTWithSource(ast, input, location); } parseBinding(input: string, location: any): ASTWithSource { var ast = this._parseBindingAst(input, location); return new ASTWithSource(ast, input, location); } parseSimpleBinding(input: string, location: string): ASTWithSource { var ast = this._parseBindingAst(input, location); if (!SimpleExpressionChecker.check(ast)) { throw new ParseException( 'Host binding expression can only contain field access and constants', input, location); } return new ASTWithSource(ast, input, location); } private _parseBindingAst(input: string, location: string): AST { // Quotes expressions use 3rd-party expression language. We don't want to use // our lexer or parser for that, so we check for that ahead of time. var quote = this._parseQuote(input, location); if (isPresent(quote)) { return quote; } this._checkNoInterpolation(input, location); var tokens = this._lexer.tokenize(input); return new _ParseAST(input, location, tokens, this._reflector, false).parseChain(); } private _parseQuote(input: string, location: any): AST { if (isBlank(input)) return null; var prefixSeparatorIndex = input.indexOf(':'); if (prefixSeparatorIndex == -1) return null; var prefix = input.substring(0, prefixSeparatorIndex); var uninterpretedExpression = input.substring(prefixSeparatorIndex + 1); // while we do not interpret the expression, we do interpret the prefix var prefixTokens = this._lexer.tokenize(prefix); // quote prefix must be a single legal identifier if (prefixTokens.length != 1 || !prefixTokens[0].isIdentifier()) return null; return new Quote(prefixTokens[0].strValue, uninterpretedExpression, location); } parseTemplateBindings(input: string, location: any): TemplateBinding[] { var tokens = this._lexer.tokenize(input); return new _ParseAST(input, location, tokens, this._reflector, false).parseTemplateBindings(); } parseInterpolation(input: string, location: any): ASTWithSource { var parts = StringWrapper.split(input, INTERPOLATION_REGEXP); if (parts.length <= 1) { return null; } var strings = []; var expressions = []; for (var i = 0; i < parts.length; i++) { var part: string = parts[i]; if (i % 2 === 0) { // fixed string strings.push(part); } else if (part.trim().length > 0) { var tokens = this._lexer.tokenize(part); var ast = new _ParseAST(input, location, tokens, this._reflector, false).parseChain(); expressions.push(ast); } else { throw new ParseException('Blank expressions are not allowed in interpolated strings', input, `at column ${this._findInterpolationErrorColumn(parts, i)} in`, location); } } return new ASTWithSource(new Interpolation(strings, expressions), input, location); } wrapLiteralPrimitive(input: string, location: any): ASTWithSource { return new ASTWithSource(new LiteralPrimitive(input), input, location); } private _checkNoInterpolation(input: string, location: any): void { var parts = StringWrapper.split(input, INTERPOLATION_REGEXP); if (parts.length > 1) { throw new ParseException('Got interpolation ({{}}) where expression was expected', input, `at column ${this._findInterpolationErrorColumn(parts, 1)} in`, location); } } private _findInterpolationErrorColumn(parts: string[], partInErrIdx: number): number { var errLocation = ''; for (var j = 0; j < partInErrIdx; j++) { errLocation += j % 2 === 0 ? parts[j] : `{{${parts[j]}}}`; } return errLocation.length; } } export class _ParseAST { index: number = 0; constructor(public input: string, public location: any, public tokens: any[], public reflector: Reflector, public parseAction: boolean) {} peek(offset: number): Token { var i = this.index + offset; return i < this.tokens.length ? this.tokens[i] : EOF; } get next(): Token { return this.peek(0); } get inputIndex(): number { return (this.index < this.tokens.length) ? this.next.index : this.input.length; } advance() { this.index++; } optionalCharacter(code: number): boolean { if (this.next.isCharacter(code)) { this.advance(); return true; } else { return false; } } optionalKeywordVar(): boolean { if (this.peekKeywordVar()) { this.advance(); return true; } else { return false; } } peekKeywordVar(): boolean { return this.next.isKeywordVar() || this.next.isOperator('#'); } expectCharacter(code: number) { if (this.optionalCharacter(code)) return; this.error(`Missing expected ${StringWrapper.fromCharCode(code)}`); } optionalOperator(op: string): boolean { if (this.next.isOperator(op)) { this.advance(); return true; } else { return false; } } expectOperator(operator: string) { if (this.optionalOperator(operator)) return; this.error(`Missing expected operator ${operator}`); } expectIdentifierOrKeyword(): string { var n = this.next; if (!n.isIdentifier() && !n.isKeyword()) { this.error(`Unexpected token ${n}, expected identifier or keyword`); } this.advance(); return n.toString(); } expectIdentifierOrKeywordOrString(): string { var n = this.next; if (!n.isIdentifier() && !n.isKeyword() && !n.isString()) { this.error(`Unexpected token ${n}, expected identifier, keyword, or string`); } this.advance(); return n.toString(); } parseChain(): AST { var exprs = []; while (this.index < this.tokens.length) { var expr = this.parsePipe(); exprs.push(expr); if (this.optionalCharacter($SEMICOLON)) { if (!this.parseAction) { this.error("Binding expression cannot contain chained expression"); } while (this.optionalCharacter($SEMICOLON)) { } // read all semicolons } else if (this.index < this.tokens.length) { this.error(`Unexpected token '${this.next}'`); } } if (exprs.length == 0) return new EmptyExpr(); if (exprs.length == 1) return exprs[0]; return new Chain(exprs); } parsePipe(): AST { var result = this.parseExpression(); if (this.optionalOperator("|")) { if (this.parseAction) { this.error("Cannot have a pipe in an action expression"); } do { var name = this.expectIdentifierOrKeyword(); var args = []; while (this.optionalCharacter($COLON)) { args.push(this.parseExpression()); } result = new BindingPipe(result, name, args); } while (this.optionalOperator("|")); } return result; } parseExpression(): AST { return this.parseConditional(); } parseConditional(): AST { var start = this.inputIndex; var result = this.parseLogicalOr(); if (this.optionalOperator('?')) { var yes = this.parsePipe(); if (!this.optionalCharacter($COLON)) { var end = this.inputIndex; var expression = this.input.substring(start, end); this.error(`Conditional expression ${expression} requires all 3 expressions`); } var no = this.parsePipe(); return new Conditional(result, yes, no); } else { return result; } } parseLogicalOr(): AST { // '||' var result = this.parseLogicalAnd(); while (this.optionalOperator('||')) { result = new Binary('||', result, this.parseLogicalAnd()); } return result; } parseLogicalAnd(): AST { // '&&' var result = this.parseEquality(); while (this.optionalOperator('&&')) { result = new Binary('&&', result, this.parseEquality()); } return result; } parseEquality(): AST { // '==','!=','===','!==' var result = this.parseRelational(); while (true) { if (this.optionalOperator('==')) { result = new Binary('==', result, this.parseRelational()); } else if (this.optionalOperator('===')) { result = new Binary('===', result, this.parseRelational()); } else if (this.optionalOperator('!=')) { result = new Binary('!=', result, this.parseRelational()); } else if (this.optionalOperator('!==')) { result = new Binary('!==', result, this.parseRelational()); } else { return result; } } } parseRelational(): AST { // '<', '>', '<=', '>=' var result = this.parseAdditive(); while (true) { if (this.optionalOperator('<')) { result = new Binary('<', result, this.parseAdditive()); } else if (this.optionalOperator('>')) { result = new Binary('>', result, this.parseAdditive()); } else if (this.optionalOperator('<=')) { result = new Binary('<=', result, this.parseAdditive()); } else if (this.optionalOperator('>=')) { result = new Binary('>=', result, this.parseAdditive()); } else { return result; } } } parseAdditive(): AST { // '+', '-' var result = this.parseMultiplicative(); while (true) { if (this.optionalOperator('+')) { result = new Binary('+', result, this.parseMultiplicative()); } else if (this.optionalOperator('-')) { result = new Binary('-', result, this.parseMultiplicative()); } else { return result; } } } parseMultiplicative(): AST { // '*', '%', '/' var result = this.parsePrefix(); while (true) { if (this.optionalOperator('*')) { result = new Binary('*', result, this.parsePrefix()); } else if (this.optionalOperator('%')) { result = new Binary('%', result, this.parsePrefix()); } else if (this.optionalOperator('/')) { result = new Binary('/', result, this.parsePrefix()); } else { return result; } } } parsePrefix(): AST { if (this.optionalOperator('+')) { return this.parsePrefix(); } else if (this.optionalOperator('-')) { return new Binary('-', new LiteralPrimitive(0), this.parsePrefix()); } else if (this.optionalOperator('!')) { return new PrefixNot(this.parsePrefix()); } else { return this.parseCallChain(); } } parseCallChain(): AST { var result = this.parsePrimary(); while (true) { if (this.optionalCharacter($PERIOD)) { result = this.parseAccessMemberOrMethodCall(result, false); } else if (this.optionalOperator('?.')) { result = this.parseAccessMemberOrMethodCall(result, true); } else if (this.optionalCharacter($LBRACKET)) { var key = this.parsePipe(); this.expectCharacter($RBRACKET); if (this.optionalOperator("=")) { var value = this.parseConditional(); result = new KeyedWrite(result, key, value); } else { result = new KeyedRead(result, key); } } else if (this.optionalCharacter($LPAREN)) { var args = this.parseCallArguments(); this.expectCharacter($RPAREN); result = new FunctionCall(result, args); } else { return result; } } } parsePrimary(): AST { if (this.optionalCharacter($LPAREN)) { let result = this.parsePipe(); this.expectCharacter($RPAREN); return result; } else if (this.next.isKeywordNull() || this.next.isKeywordUndefined()) { this.advance(); return new LiteralPrimitive(null); } else if (this.next.isKeywordTrue()) { this.advance(); return new LiteralPrimitive(true); } else if (this.next.isKeywordFalse()) { this.advance(); return new LiteralPrimitive(false); } else if (this.optionalCharacter($LBRACKET)) { var elements = this.parseExpressionList($RBRACKET); this.expectCharacter($RBRACKET); return new LiteralArray(elements); } else if (this.next.isCharacter($LBRACE)) { return this.parseLiteralMap(); } else if (this.next.isIdentifier()) { return this.parseAccessMemberOrMethodCall(_implicitReceiver, false); } else if (this.next.isNumber()) { var value = this.next.toNumber(); this.advance(); return new LiteralPrimitive(value); } else if (this.next.isString()) { var literalValue = this.next.toString(); this.advance(); return new LiteralPrimitive(literalValue); } else if (this.index >= this.tokens.length) { this.error(`Unexpected end of expression: ${this.input}`); } else { this.error(`Unexpected token ${this.next}`); } // error() throws, so we don't reach here. throw new BaseException("Fell through all cases in parsePrimary"); } parseExpressionList(terminator: number): any[] { var result = []; if (!this.next.isCharacter(terminator)) { do { result.push(this.parsePipe()); } while (this.optionalCharacter($COMMA)); } return result; } parseLiteralMap(): LiteralMap { var keys = []; var values = []; this.expectCharacter($LBRACE); if (!this.optionalCharacter($RBRACE)) { do { var key = this.expectIdentifierOrKeywordOrString(); keys.push(key); this.expectCharacter($COLON); values.push(this.parsePipe()); } while (this.optionalCharacter($COMMA)); this.expectCharacter($RBRACE); } return new LiteralMap(keys, values); } parseAccessMemberOrMethodCall(receiver: AST, isSafe: boolean = false): AST { let id = this.expectIdentifierOrKeyword(); if (this.optionalCharacter($LPAREN)) { let args = this.parseCallArguments(); this.expectCharacter($RPAREN); let fn = this.reflector.method(id); return isSafe ? new SafeMethodCall(receiver, id, fn, args) : new MethodCall(receiver, id, fn, args); } else { if (isSafe) { if (this.optionalOperator("=")) { this.error("The '?.' operator cannot be used in the assignment"); } else { return new SafePropertyRead(receiver, id, this.reflector.getter(id)); } } else { if (this.optionalOperator("=")) { if (!this.parseAction) { this.error("Bindings cannot contain assignments"); } let value = this.parseConditional(); return new PropertyWrite(receiver, id, this.reflector.setter(id), value); } else { return new PropertyRead(receiver, id, this.reflector.getter(id)); } } } return null; } parseCallArguments(): BindingPipe[] { if (this.next.isCharacter($RPAREN)) return []; var positionals = []; do { positionals.push(this.parsePipe()); } while (this.optionalCharacter($COMMA)); return positionals; } parseBlockContent(): AST { if (!this.parseAction) { this.error("Binding expression cannot contain chained expression"); } var exprs = []; while (this.index < this.tokens.length && !this.next.isCharacter($RBRACE)) { var expr = this.parseExpression(); exprs.push(expr); if (this.optionalCharacter($SEMICOLON)) { while (this.optionalCharacter($SEMICOLON)) { } // read all semicolons } } if (exprs.length == 0) return new EmptyExpr(); if (exprs.length == 1) return exprs[0]; return new Chain(exprs); } /** * An identifier, a keyword, a string with an optional `-` inbetween. */ expectTemplateBindingKey(): string { var result = ''; var operatorFound = false; do { result += this.expectIdentifierOrKeywordOrString(); operatorFound = this.optionalOperator('-'); if (operatorFound) { result += '-'; } } while (operatorFound); return result.toString(); } parseTemplateBindings(): any[] { var bindings = []; var prefix = null; while (this.index < this.tokens.length) { var keyIsVar: boolean = this.optionalKeywordVar(); var key = this.expectTemplateBindingKey(); if (!keyIsVar) { if (prefix == null) { prefix = key; } else { key = prefix + '-' + key; } } this.optionalCharacter($COLON); var name = null; var expression = null; if (keyIsVar) { if (this.optionalOperator("=")) { name = this.expectTemplateBindingKey(); } else { name = '\$implicit'; } } else if (this.next !== EOF && !this.peekKeywordVar()) { var start = this.inputIndex; var ast = this.parsePipe(); var source = this.input.substring(start, this.inputIndex); expression = new ASTWithSource(ast, source, this.location); } bindings.push(new TemplateBinding(key, keyIsVar, name, expression)); if (!this.optionalCharacter($SEMICOLON)) { this.optionalCharacter($COMMA); } } return bindings; } error(message: string, index: number = null) { if (isBlank(index)) index = this.index; var location = (index < this.tokens.length) ? `at column ${this.tokens[index].index + 1} in` : `at the end of the expression`; throw new ParseException(message, this.input, location, this.location); } } class SimpleExpressionChecker implements AstVisitor { static check(ast: AST): boolean { var s = new SimpleExpressionChecker(); ast.visit(s); return s.simple; } simple = true; visitImplicitReceiver(ast: ImplicitReceiver) {} visitInterpolation(ast: Interpolation) { this.simple = false; } visitLiteralPrimitive(ast: LiteralPrimitive) {} visitPropertyRead(ast: PropertyRead) {} visitPropertyWrite(ast: PropertyWrite) { this.simple = false; } visitSafePropertyRead(ast: SafePropertyRead) { this.simple = false; } visitMethodCall(ast: MethodCall) { this.simple = false; } visitSafeMethodCall(ast: SafeMethodCall) { this.simple = false; } visitFunctionCall(ast: FunctionCall) { this.simple = false; } visitLiteralArray(ast: LiteralArray) { this.visitAll(ast.expressions); } visitLiteralMap(ast: LiteralMap) { this.visitAll(ast.values); } visitBinary(ast: Binary) { this.simple = false; } visitPrefixNot(ast: PrefixNot) { this.simple = false; } visitConditional(ast: Conditional) { this.simple = false; } visitPipe(ast: BindingPipe) { this.simple = false; } visitKeyedRead(ast: KeyedRead) { this.simple = false; } visitKeyedWrite(ast: KeyedWrite) { this.simple = false; } visitAll(asts: any[]): any[] { var res = ListWrapper.createFixedSize(asts.length); for (var i = 0; i < asts.length; ++i) { res[i] = asts[i].visit(this); } return res; } visitChain(ast: Chain) { this.simple = false; } visitQuote(ast: Quote) { this.simple = false; } }
modules/angular2/src/core/change_detection/parser/parser.ts
1
https://github.com/angular/angular/commit/b90de665352aca95f8b82c510bc7a7856beb8821
[ 0.9983704686164856, 0.04116179794073105, 0.00015948388318065554, 0.0001721506705507636, 0.1901971846818924 ]
{ "id": 3, "code_window": [ " var uninterpretedExpression = input.substring(prefixSeparatorIndex + 1);\n", "\n", " // while we do not interpret the expression, we do interpret the prefix\n", " var prefixTokens = this._lexer.tokenize(prefix);\n", "\n", " // quote prefix must be a single legal identifier\n", " if (prefixTokens.length != 1 || !prefixTokens[0].isIdentifier()) return null;\n", " return new Quote(prefixTokens[0].strValue, uninterpretedExpression, location);\n", " }\n", "\n", " parseTemplateBindings(input: string, location: any): TemplateBinding[] {\n", " var tokens = this._lexer.tokenize(input);\n", " return new _ParseAST(input, location, tokens, this._reflector, false).parseTemplateBindings();\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return new Quote(prefix, uninterpretedExpression, location);\n" ], "file_path": "modules/angular2/src/core/change_detection/parser/parser.ts", "type": "replace", "edit_start_line_idx": 109 }
import {bootstrap} from 'angular2/bootstrap'; import {Component, Directive, View, Host, forwardRef, Provider, Injectable} from 'angular2/core'; import {NgIf, NgFor, FORM_DIRECTIVES} from 'angular2/common'; import {CONST_EXPR} from 'angular2/src/facade/lang'; /** * You can find the Angular 1 implementation of this example here: * https://github.com/wardbell/ng1DataBinding */ // ---- model var _nextId = 1; class Person { personId: number; mom: Person; dad: Person; friends: Person[]; constructor(public firstName: string, public lastName: string, public yearOfBirth: number) { this.personId = _nextId++; this.firstName = firstName; this.lastName = lastName; this.mom = null; this.dad = null; this.friends = []; this.personId = _nextId++; } get age(): number { return 2015 - this.yearOfBirth; } get fullName(): string { return `${this.firstName} ${this.lastName}`; } get friendNames(): string { return this.friends.map(f => f.fullName).join(', '); } } // ---- services @Injectable() class DataService { currentPerson: Person; persons: Person[]; constructor() { this.persons = [ new Person('Victor', 'Savkin', 1930), new Person('Igor', 'Minar', 1920), new Person('John', 'Papa', 1910), new Person('Nancy', 'Duarte', 1910), new Person('Jack', 'Papa', 1910), new Person('Jill', 'Papa', 1910), new Person('Ward', 'Bell', 1910), new Person('Robert', 'Bell', 1910), new Person('Tracy', 'Ward', 1910), new Person('Dan', 'Wahlin', 1910) ]; this.persons[0].friends = [0, 1, 2, 6, 9].map(_ => this.persons[_]); this.persons[1].friends = [0, 2, 6, 9].map(_ => this.persons[_]); this.persons[2].friends = [0, 1, 6, 9].map(_ => this.persons[_]); this.persons[6].friends = [0, 1, 2, 9].map(_ => this.persons[_]); this.persons[9].friends = [0, 1, 2, 6].map(_ => this.persons[_]); this.persons[2].mom = this.persons[5]; this.persons[2].dad = this.persons[4]; this.persons[6].mom = this.persons[8]; this.persons[6].dad = this.persons[7]; this.currentPerson = this.persons[0]; } } // ---- components @Component({selector: 'full-name-cmp'}) @View({ template: ` <h1>Edit Full Name</h1> <div> <form> <div> <label> First: <input [(ng-model)]="person.firstName" type="text" placeholder="First name"> </label> </div> <div> <label> Last: <input [(ng-model)]="person.lastName" type="text" placeholder="Last name"> </label> </div> <div> <label>{{person.fullName}}</label> </div> </form> </div> `, directives: [FORM_DIRECTIVES] }) class FullNameComponent { constructor(private _service: DataService) {} get person(): Person { return this._service.currentPerson; } } @Component({selector: 'person-detail-cmp'}) @View({ template: ` <h2>{{person.fullName}}</h2> <div> <form> <div> <label>First: <input [(ng-model)]="person.firstName" type="text" placeholder="First name"></label> </div> <div> <label>Last: <input [(ng-model)]="person.lastName" type="text" placeholder="Last name"></label> </div> <div> <label>Year of birth: <input [(ng-model)]="person.yearOfBirth" type="number" placeholder="Year of birth"></label> Age: {{person.age}} </div>\ <div *ng-if="person.mom != null"> <label>Mom:</label> <input [(ng-model)]="person.mom.firstName" type="text" placeholder="Mom's first name"> <input [(ng-model)]="person.mom.lastName" type="text" placeholder="Mom's last name"> {{person.mom.fullName}} </div> <div *ng-if="person.dad != null"> <label>Dad:</label> <input [(ng-model)]="person.dad.firstName" type="text" placeholder="Dad's first name"> <input [(ng-model)]="person.dad.lastName" type="text" placeholder="Dad's last name"> {{person.dad.fullName}} </div> <div *ng-if="person.friends.length > 0"> <label>Friends:</label> {{person.friendNames}} </div> </form> </div> `, directives: [FORM_DIRECTIVES, NgIf] }) class PersonsDetailComponent { constructor(private _service: DataService) {} get person(): Person { return this._service.currentPerson; } } @Component({selector: 'persons-cmp'}) @View({ template: ` <h1>FullName Demo</h1> <div> <ul> <li *ng-for="#person of persons"> <label (click)="select(person)">{{person.fullName}}</label> </li> </ul> <person-detail-cmp></person-detail-cmp> </div> `, directives: [FORM_DIRECTIVES, PersonsDetailComponent, NgFor] }) class PersonsComponent { persons: Person[]; constructor(private _service: DataService) { this.persons = _service.persons; } select(person: Person): void { this._service.currentPerson = person; } } @Component({selector: 'person-management-app', viewBindings: [DataService]}) @View({ template: ` <button (click)="switchToEditName()">Edit Full Name</button> <button (click)="switchToPersonList()">Person Array</button> <full-name-cmp *ng-if="mode == 'editName'"></full-name-cmp> <persons-cmp *ng-if="mode == 'personList'"></persons-cmp> `, directives: [FullNameComponent, PersonsComponent, NgIf] }) class PersonManagementApplication { mode: string; switchToEditName(): void { this.mode = 'editName'; } switchToPersonList(): void { this.mode = 'personList'; } } export function main() { bootstrap(PersonManagementApplication); }
modules/playground/src/person_management/index.ts
0
https://github.com/angular/angular/commit/b90de665352aca95f8b82c510bc7a7856beb8821
[ 0.00017690294771455228, 0.00017357387696392834, 0.00017023950931616127, 0.00017393426969647408, 0.0000016092561736513744 ]
{ "id": 3, "code_window": [ " var uninterpretedExpression = input.substring(prefixSeparatorIndex + 1);\n", "\n", " // while we do not interpret the expression, we do interpret the prefix\n", " var prefixTokens = this._lexer.tokenize(prefix);\n", "\n", " // quote prefix must be a single legal identifier\n", " if (prefixTokens.length != 1 || !prefixTokens[0].isIdentifier()) return null;\n", " return new Quote(prefixTokens[0].strValue, uninterpretedExpression, location);\n", " }\n", "\n", " parseTemplateBindings(input: string, location: any): TemplateBinding[] {\n", " var tokens = this._lexer.tokenize(input);\n", " return new _ParseAST(input, location, tokens, this._reflector, false).parseTemplateBindings();\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return new Quote(prefix, uninterpretedExpression, location);\n" ], "file_path": "modules/angular2/src/core/change_detection/parser/parser.ts", "type": "replace", "edit_start_line_idx": 109 }
import {verifyNoBrowserErrors} from 'angular2/src/testing/e2e_util'; import {Promise} from 'angular2/src/facade/async'; function waitForElement(selector) { var EC = (<any>protractor).ExpectedConditions; // Waits for the element with id 'abc' to be present on the dom. browser.wait(EC.presenceOf($(selector)), 20000); } describe('hash routing example app', function() { afterEach(verifyNoBrowserErrors); var URL = 'playground/src/hash_routing/index.html'; it('should navigate between routes', function() { browser.get(URL + '#/bye'); waitForElement('goodbye-cmp'); element(by.css('#hello-link')).click(); waitForElement('hello-cmp'); expect(element(by.css('hello-cmp')).getText()).toContain('hello'); browser.navigate().back(); waitForElement('goodbye-cmp'); expect(element(by.css('goodbye-cmp')).getText()).toContain('goodbye'); }); it('should open in new window if target is _blank', () => { var URL = 'playground/src/hash_routing/index.html'; browser.get(URL + '#/'); waitForElement('hello-cmp'); element(by.css('#goodbye-link-blank')).click(); expect(browser.driver.getCurrentUrl()).not.toContain('#/bye'); browser.getAllWindowHandles().then(function(windows) { browser.switchTo() .window(windows[1]) .then(function() { expect(browser.driver.getCurrentUrl()).toContain("#/bye"); }); }); }); });
modules/playground/e2e_test/hash_routing/hash_location_spec.ts
0
https://github.com/angular/angular/commit/b90de665352aca95f8b82c510bc7a7856beb8821
[ 0.00017606525216251612, 0.00017313924035988748, 0.0001704864262137562, 0.00017259015294257551, 0.000002008606315939687 ]
{ "id": 3, "code_window": [ " var uninterpretedExpression = input.substring(prefixSeparatorIndex + 1);\n", "\n", " // while we do not interpret the expression, we do interpret the prefix\n", " var prefixTokens = this._lexer.tokenize(prefix);\n", "\n", " // quote prefix must be a single legal identifier\n", " if (prefixTokens.length != 1 || !prefixTokens[0].isIdentifier()) return null;\n", " return new Quote(prefixTokens[0].strValue, uninterpretedExpression, location);\n", " }\n", "\n", " parseTemplateBindings(input: string, location: any): TemplateBinding[] {\n", " var tokens = this._lexer.tokenize(input);\n", " return new _ParseAST(input, location, tokens, this._reflector, false).parseTemplateBindings();\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " return new Quote(prefix, uninterpretedExpression, location);\n" ], "file_path": "modules/angular2/src/core/change_detection/parser/parser.ts", "type": "replace", "edit_start_line_idx": 109 }
import { describe, it, iit, ddescribe, expect, tick, SpyObject, beforeEach, proxy, containsRegexp } from 'angular2/testing_internal'; import {DOM} from 'angular2/src/platform/dom/dom_adapter'; import {MapWrapper} from 'angular2/src/facade/collection'; import {RegExpWrapper} from 'angular2/src/facade/lang'; class TestObj { prop; constructor(prop) { this.prop = prop; } someFunc(): number { return -1; } someComplexFunc(a) { return a; } } class SpyTestObj extends SpyObject { constructor() { super(TestObj); } noSuchMethod(m) { return super.noSuchMethod(m) } } export function main() { describe('testing', () => { describe('equality', () => { it('should structurally compare objects', () => { var expected = new TestObj(new TestObj({'one': [1, 2]})); var actual = new TestObj(new TestObj({'one': [1, 2]})); var falseActual = new TestObj(new TestObj({'one': [1, 3]})); expect(actual).toEqual(expected); expect(falseActual).not.toEqual(expected); }); }); describe("toHaveCssClass", () => { it("should assert that the CSS class is present", () => { var el = DOM.createElement('div'); DOM.addClass(el, 'matias'); expect(el).toHaveCssClass('matias'); }); it("should assert that the CSS class is not present", () => { var el = DOM.createElement('div'); DOM.addClass(el, 'matias'); expect(el).not.toHaveCssClass('fatias'); }); }); describe('toEqual for Maps', () => { it('should detect equality for same reference', () => { var m1 = MapWrapper.createFromStringMap({'a': 1}); expect(m1).toEqual(m1); }); it('should detect equality for same content', () => { expect(MapWrapper.createFromStringMap({'a': 1})) .toEqual(MapWrapper.createFromStringMap({'a': 1})); }); it('should detect missing entries', () => { expect(MapWrapper.createFromStringMap({'a': 1})) .not.toEqual(MapWrapper.createFromStringMap({})); }); it('should detect different values', () => { expect(MapWrapper.createFromStringMap({'a': 1})) .not.toEqual(MapWrapper.createFromStringMap({'a': 2})); }); it('should detect additional entries', () => { expect(MapWrapper.createFromStringMap({'a': 1})) .not.toEqual(MapWrapper.createFromStringMap({'a': 1, 'b': 1})); }); }); describe("spy objects", () => { var spyObj; beforeEach(() => { spyObj = <any>new SpyTestObj(); }); it("should return a new spy func with no calls", () => { expect(spyObj.spy("someFunc")).not.toHaveBeenCalled(); }); it("should record function calls", () => { spyObj.spy("someFunc").andCallFake((a, b) => {return a + b}); expect(spyObj.someFunc(1, 2)).toEqual(3); expect(spyObj.spy("someFunc")).toHaveBeenCalledWith(1, 2); }); it("should match multiple function calls", () => { spyObj.someFunc(1, 2); spyObj.someFunc(3, 4); expect(spyObj.spy("someFunc")).toHaveBeenCalledWith(1, 2); expect(spyObj.spy("someFunc")).toHaveBeenCalledWith(3, 4); }); it("should match null arguments", () => { spyObj.someFunc(null, "hello"); expect(spyObj.spy("someFunc")).toHaveBeenCalledWith(null, "hello"); }); it("should match using deep equality", () => { spyObj.someComplexFunc([1]); expect(spyObj.spy("someComplexFunc")).toHaveBeenCalledWith([1]); }); it("should support stubs", () => { var s = SpyObject.stub({"a": 1}, {"b": 2}); expect(s.a()).toEqual(1); expect(s.b()).toEqual(2); }); it('should create spys for all methods', () => { expect(() => spyObj.someFunc()).not.toThrow(); }); it('should create a default spy that does not fail for numbers', () => { // Previously needed for rtts_assert. Revisit this behavior. expect(spyObj.someFunc()).toBe(null); }); }); describe('containsRegexp', () => { it('should allow any prefix and suffix', () => { expect(RegExpWrapper.firstMatch(containsRegexp('b'), 'abc')).toBeTruthy(); expect(RegExpWrapper.firstMatch(containsRegexp('b'), 'adc')).toBeFalsy(); }); it('should match various special characters', () => { expect(RegExpWrapper.firstMatch(containsRegexp('a.b'), 'a.b')).toBeTruthy(); expect(RegExpWrapper.firstMatch(containsRegexp('axb'), 'a.b')).toBeFalsy(); }); }); }); }
modules/angular2/test/testing/testing_internal_spec.ts
0
https://github.com/angular/angular/commit/b90de665352aca95f8b82c510bc7a7856beb8821
[ 0.00017775548622012138, 0.00017559764091856778, 0.00017174224194604903, 0.00017566699534654617, 0.0000016754084981585038 ]
{ "id": 4, "code_window": [ "\n", " it('should parse quoted expressions', () => { checkBinding('a:b', 'a:b'); });\n", "\n", " it('should ignore whitespace around quote prefix', () => { checkBinding(' a :b', 'a:b'); });\n", "\n", " it('should refuse prefixes that are not single identifiers', () => {\n", " expectBindingError('a + b:c').toThrowError();\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should not crash when prefix part is not tokenizable',\n", " () => { checkBinding('\"a:b\"', '\"a:b\"'); });\n", "\n" ], "file_path": "modules/angular2/test/core/change_detection/parser/parser_spec.ts", "type": "add", "edit_start_line_idx": 235 }
import {Injectable} from 'angular2/src/core/di/decorators'; import {ListWrapper, SetWrapper} from "angular2/src/facade/collection"; import {NumberWrapper, StringJoiner, StringWrapper, isPresent} from "angular2/src/facade/lang"; import {BaseException} from 'angular2/src/facade/exceptions'; export enum TokenType { Character, Identifier, Keyword, String, Operator, Number } @Injectable() export class Lexer { tokenize(text: string): any[] { var scanner = new _Scanner(text); var tokens = []; var token = scanner.scanToken(); while (token != null) { tokens.push(token); token = scanner.scanToken(); } return tokens; } } export class Token { constructor(public index: number, public type: TokenType, public numValue: number, public strValue: string) {} isCharacter(code: number): boolean { return (this.type == TokenType.Character && this.numValue == code); } isNumber(): boolean { return (this.type == TokenType.Number); } isString(): boolean { return (this.type == TokenType.String); } isOperator(operater: string): boolean { return (this.type == TokenType.Operator && this.strValue == operater); } isIdentifier(): boolean { return (this.type == TokenType.Identifier); } isKeyword(): boolean { return (this.type == TokenType.Keyword); } isKeywordVar(): boolean { return (this.type == TokenType.Keyword && this.strValue == "var"); } isKeywordNull(): boolean { return (this.type == TokenType.Keyword && this.strValue == "null"); } isKeywordUndefined(): boolean { return (this.type == TokenType.Keyword && this.strValue == "undefined"); } isKeywordTrue(): boolean { return (this.type == TokenType.Keyword && this.strValue == "true"); } isKeywordFalse(): boolean { return (this.type == TokenType.Keyword && this.strValue == "false"); } toNumber(): number { // -1 instead of NULL ok? return (this.type == TokenType.Number) ? this.numValue : -1; } toString(): string { switch (this.type) { case TokenType.Character: case TokenType.Identifier: case TokenType.Keyword: case TokenType.Operator: case TokenType.String: return this.strValue; case TokenType.Number: return this.numValue.toString(); default: return null; } } } function newCharacterToken(index: number, code: number): Token { return new Token(index, TokenType.Character, code, StringWrapper.fromCharCode(code)); } function newIdentifierToken(index: number, text: string): Token { return new Token(index, TokenType.Identifier, 0, text); } function newKeywordToken(index: number, text: string): Token { return new Token(index, TokenType.Keyword, 0, text); } function newOperatorToken(index: number, text: string): Token { return new Token(index, TokenType.Operator, 0, text); } function newStringToken(index: number, text: string): Token { return new Token(index, TokenType.String, 0, text); } function newNumberToken(index: number, n: number): Token { return new Token(index, TokenType.Number, n, ""); } export var EOF: Token = new Token(-1, TokenType.Character, 0, ""); export const $EOF = 0; export const $TAB = 9; export const $LF = 10; export const $VTAB = 11; export const $FF = 12; export const $CR = 13; export const $SPACE = 32; export const $BANG = 33; export const $DQ = 34; export const $HASH = 35; export const $$ = 36; export const $PERCENT = 37; export const $AMPERSAND = 38; export const $SQ = 39; export const $LPAREN = 40; export const $RPAREN = 41; export const $STAR = 42; export const $PLUS = 43; export const $COMMA = 44; export const $MINUS = 45; export const $PERIOD = 46; export const $SLASH = 47; export const $COLON = 58; export const $SEMICOLON = 59; export const $LT = 60; export const $EQ = 61; export const $GT = 62; export const $QUESTION = 63; const $0 = 48; const $9 = 57; const $A = 65, $E = 69, $Z = 90; export const $LBRACKET = 91; export const $BACKSLASH = 92; export const $RBRACKET = 93; const $CARET = 94; const $_ = 95; const $a = 97, $e = 101, $f = 102, $n = 110, $r = 114, $t = 116, $u = 117, $v = 118, $z = 122; export const $LBRACE = 123; export const $BAR = 124; export const $RBRACE = 125; const $NBSP = 160; export class ScannerError extends BaseException { constructor(public message) { super(); } toString(): string { return this.message; } } class _Scanner { length: number; peek: number = 0; index: number = -1; constructor(public input: string) { this.length = input.length; this.advance(); } advance() { this.peek = ++this.index >= this.length ? $EOF : StringWrapper.charCodeAt(this.input, this.index); } scanToken(): Token { var input = this.input, length = this.length, peek = this.peek, index = this.index; // Skip whitespace. while (peek <= $SPACE) { if (++index >= length) { peek = $EOF; break; } else { peek = StringWrapper.charCodeAt(input, index); } } this.peek = peek; this.index = index; if (index >= length) { return null; } // Handle identifiers and numbers. if (isIdentifierStart(peek)) return this.scanIdentifier(); if (isDigit(peek)) return this.scanNumber(index); var start: number = index; switch (peek) { case $PERIOD: this.advance(); return isDigit(this.peek) ? this.scanNumber(start) : newCharacterToken(start, $PERIOD); case $LPAREN: case $RPAREN: case $LBRACE: case $RBRACE: case $LBRACKET: case $RBRACKET: case $COMMA: case $COLON: case $SEMICOLON: return this.scanCharacter(start, peek); case $SQ: case $DQ: return this.scanString(); case $HASH: case $PLUS: case $MINUS: case $STAR: case $SLASH: case $PERCENT: case $CARET: return this.scanOperator(start, StringWrapper.fromCharCode(peek)); case $QUESTION: return this.scanComplexOperator(start, '?', $PERIOD, '.'); case $LT: case $GT: return this.scanComplexOperator(start, StringWrapper.fromCharCode(peek), $EQ, '='); case $BANG: case $EQ: return this.scanComplexOperator(start, StringWrapper.fromCharCode(peek), $EQ, '=', $EQ, '='); case $AMPERSAND: return this.scanComplexOperator(start, '&', $AMPERSAND, '&'); case $BAR: return this.scanComplexOperator(start, '|', $BAR, '|'); case $NBSP: while (isWhitespace(this.peek)) this.advance(); return this.scanToken(); } this.error(`Unexpected character [${StringWrapper.fromCharCode(peek)}]`, 0); return null; } scanCharacter(start: number, code: number): Token { assert(this.peek == code); this.advance(); return newCharacterToken(start, code); } scanOperator(start: number, str: string): Token { assert(this.peek == StringWrapper.charCodeAt(str, 0)); assert(SetWrapper.has(OPERATORS, str)); this.advance(); return newOperatorToken(start, str); } /** * Tokenize a 2/3 char long operator * * @param start start index in the expression * @param one first symbol (always part of the operator) * @param twoCode code point for the second symbol * @param two second symbol (part of the operator when the second code point matches) * @param threeCode code point for the third symbol * @param three third symbol (part of the operator when provided and matches source expression) * @returns {Token} */ scanComplexOperator(start: number, one: string, twoCode: number, two: string, threeCode?: number, three?: string): Token { assert(this.peek == StringWrapper.charCodeAt(one, 0)); this.advance(); var str: string = one; if (this.peek == twoCode) { this.advance(); str += two; } if (isPresent(threeCode) && this.peek == threeCode) { this.advance(); str += three; } assert(SetWrapper.has(OPERATORS, str)); return newOperatorToken(start, str); } scanIdentifier(): Token { assert(isIdentifierStart(this.peek)); var start: number = this.index; this.advance(); while (isIdentifierPart(this.peek)) this.advance(); var str: string = this.input.substring(start, this.index); if (SetWrapper.has(KEYWORDS, str)) { return newKeywordToken(start, str); } else { return newIdentifierToken(start, str); } } scanNumber(start: number): Token { assert(isDigit(this.peek)); var simple: boolean = (this.index === start); this.advance(); // Skip initial digit. while (true) { if (isDigit(this.peek)) { // Do nothing. } else if (this.peek == $PERIOD) { simple = false; } else if (isExponentStart(this.peek)) { this.advance(); if (isExponentSign(this.peek)) this.advance(); if (!isDigit(this.peek)) this.error('Invalid exponent', -1); simple = false; } else { break; } this.advance(); } var str: string = this.input.substring(start, this.index); // TODO var value: number = simple ? NumberWrapper.parseIntAutoRadix(str) : NumberWrapper.parseFloat(str); return newNumberToken(start, value); } scanString(): Token { assert(this.peek == $SQ || this.peek == $DQ); var start: number = this.index; var quote: number = this.peek; this.advance(); // Skip initial quote. var buffer: StringJoiner; var marker: number = this.index; var input: string = this.input; while (this.peek != quote) { if (this.peek == $BACKSLASH) { if (buffer == null) buffer = new StringJoiner(); buffer.add(input.substring(marker, this.index)); this.advance(); var unescapedCode: number; if (this.peek == $u) { // 4 character hex code for unicode character. var hex: string = input.substring(this.index + 1, this.index + 5); try { unescapedCode = NumberWrapper.parseInt(hex, 16); } catch (e) { this.error(`Invalid unicode escape [\\u${hex}]`, 0); } for (var i: number = 0; i < 5; i++) { this.advance(); } } else { unescapedCode = unescape(this.peek); this.advance(); } buffer.add(StringWrapper.fromCharCode(unescapedCode)); marker = this.index; } else if (this.peek == $EOF) { this.error('Unterminated quote', 0); } else { this.advance(); } } var last: string = input.substring(marker, this.index); this.advance(); // Skip terminating quote. // Compute the unescaped string value. var unescaped: string = last; if (buffer != null) { buffer.add(last); unescaped = buffer.toString(); } return newStringToken(start, unescaped); } error(message: string, offset: number) { var position: number = this.index + offset; throw new ScannerError( `Lexer Error: ${message} at column ${position} in expression [${this.input}]`); } } function isWhitespace(code: number): boolean { return (code >= $TAB && code <= $SPACE) || (code == $NBSP); } function isIdentifierStart(code: number): boolean { return ($a <= code && code <= $z) || ($A <= code && code <= $Z) || (code == $_) || (code == $$); } function isIdentifierPart(code: number): boolean { return ($a <= code && code <= $z) || ($A <= code && code <= $Z) || ($0 <= code && code <= $9) || (code == $_) || (code == $$); } function isDigit(code: number): boolean { return $0 <= code && code <= $9; } function isExponentStart(code: number): boolean { return code == $e || code == $E; } function isExponentSign(code: number): boolean { return code == $MINUS || code == $PLUS; } function unescape(code: number): number { switch (code) { case $n: return $LF; case $f: return $FF; case $r: return $CR; case $t: return $TAB; case $v: return $VTAB; default: return code; } } var OPERATORS = SetWrapper.createFromList([ '+', '-', '*', '/', '%', '^', '=', '==', '!=', '===', '!==', '<', '>', '<=', '>=', '&&', '||', '&', '|', '!', '?', '#', '?.' ]); var KEYWORDS = SetWrapper.createFromList(['var', 'null', 'undefined', 'true', 'false', 'if', 'else']);
modules/angular2/src/core/change_detection/parser/lexer.ts
1
https://github.com/angular/angular/commit/b90de665352aca95f8b82c510bc7a7856beb8821
[ 0.0016244465950876474, 0.0002536228857934475, 0.00016421990585513413, 0.00017198380373883992, 0.0002541721914894879 ]
{ "id": 4, "code_window": [ "\n", " it('should parse quoted expressions', () => { checkBinding('a:b', 'a:b'); });\n", "\n", " it('should ignore whitespace around quote prefix', () => { checkBinding(' a :b', 'a:b'); });\n", "\n", " it('should refuse prefixes that are not single identifiers', () => {\n", " expectBindingError('a + b:c').toThrowError();\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should not crash when prefix part is not tokenizable',\n", " () => { checkBinding('\"a:b\"', '\"a:b\"'); });\n", "\n" ], "file_path": "modules/angular2/test/core/change_detection/parser/parser_spec.ts", "type": "add", "edit_start_line_idx": 235 }
{ "name": "ngHttp", "version": "<%= packageJson.version %>", "description": "Http module for Angular 2", "homepage": "<%= packageJson.homepage %>", "bugs": "<%= packageJson.bugs %>", "contributors": <%= JSON.stringify(packageJson.contributors) %>, "license": "<%= packageJson.license %>", "repository": <%= JSON.stringify(packageJson.repository) %>, "dependencies": { "angular2": "<%= packageJson.version %>", "@reactivex/rxjs": "<%= packageJson.dependencies['@reactivex/rxjs'] %>", "reflect-metadata": "<%= packageJson.dependencies['reflect-metadata'] %>" }, "devDependencies": <%= JSON.stringify(packageJson.defaultDevDependencies) %> }
modules/angular2/src/http/package.json
0
https://github.com/angular/angular/commit/b90de665352aca95f8b82c510bc7a7856beb8821
[ 0.00017699624004308134, 0.00017674462287686765, 0.0001764930202625692, 0.00017674462287686765, 2.5160989025607705e-7 ]
{ "id": 4, "code_window": [ "\n", " it('should parse quoted expressions', () => { checkBinding('a:b', 'a:b'); });\n", "\n", " it('should ignore whitespace around quote prefix', () => { checkBinding(' a :b', 'a:b'); });\n", "\n", " it('should refuse prefixes that are not single identifiers', () => {\n", " expectBindingError('a + b:c').toThrowError();\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should not crash when prefix part is not tokenizable',\n", " () => { checkBinding('\"a:b\"', '\"a:b\"'); });\n", "\n" ], "file_path": "modules/angular2/test/core/change_detection/parser/parser_spec.ts", "type": "add", "edit_start_line_idx": 235 }
library bar; import 'package:angular2/src/core/metadata.dart'; import 'baz.dart'; @Component(selector: 'soup') @View(template: 'foo', directives: [Foo]) class MyComponent { MyComponent(); }
modules_dart/transform/test/transform/integration/directive_chain_files/bar.dart
0
https://github.com/angular/angular/commit/b90de665352aca95f8b82c510bc7a7856beb8821
[ 0.00017658073920756578, 0.0001749213261064142, 0.00017326189845334738, 0.0001749213261064142, 0.0000016594203771091998 ]
{ "id": 4, "code_window": [ "\n", " it('should parse quoted expressions', () => { checkBinding('a:b', 'a:b'); });\n", "\n", " it('should ignore whitespace around quote prefix', () => { checkBinding(' a :b', 'a:b'); });\n", "\n", " it('should refuse prefixes that are not single identifiers', () => {\n", " expectBindingError('a + b:c').toThrowError();\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should not crash when prefix part is not tokenizable',\n", " () => { checkBinding('\"a:b\"', '\"a:b\"'); });\n", "\n" ], "file_path": "modules/angular2/test/core/change_detection/parser/parser_spec.ts", "type": "add", "edit_start_line_idx": 235 }
name: angular2_material version: <%= packageJson.version %> authors: <%= Object.keys(packageJson.contributors).map(function(name) { return '- '+name+' <'+packageJson.contributors[name]+'>'; }).join('\n') %> description: Google material design components for Angular 2 homepage: <%= packageJson.homepage %> environment: sdk: '>=1.10.0 <2.0.0' dependencies: angular2: '^<%= packageJson.version %>' browser: '^0.10.0' dependency_overrides: angular2: path: ../angular2 dev_dependencies: guinness: '^0.1.17' transformers: - angular2
modules/angular2_material/pubspec.yaml
0
https://github.com/angular/angular/commit/b90de665352aca95f8b82c510bc7a7856beb8821
[ 0.00017454450426157564, 0.00017352447321172804, 0.0001727669732645154, 0.00017326189845334738, 7.490471602977777e-7 ]
{ "id": 0, "code_window": [ " </div>\n", " <QueryTable\n", " columns={[\n", " 'state', 'dbId', 'userId',\n", " 'progress', 'rows', 'sql', 'querylink',\n", " ]}\n", " onUserClicked={this.onUserClicked.bind(this)}\n", " onDbClicked={this.onDbClicked.bind(this)}\n", " queries={this.state.queriesArray}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'state', 'db', 'user',\n" ], "file_path": "caravel/assets/javascripts/SqlLab/components/QuerySearch.jsx", "type": "replace", "edit_start_line_idx": 128 }
import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as Actions from '../actions'; import moment from 'moment'; import { Table } from 'reactable'; import { ProgressBar } from 'react-bootstrap'; import Link from './Link'; import VisualizeModal from './VisualizeModal'; import SqlShrink from './SqlShrink'; import { STATE_BSSTYLE_MAP } from '../common'; import { fDuration } from '../../modules/dates'; import { getLink } from '../../../utils/common'; class QueryTable extends React.Component { constructor(props) { super(props); const uri = window.location.toString(); const cleanUri = uri.substring(0, uri.indexOf('#')); this.state = { cleanUri, showVisualizeModal: false, activeQuery: null, }; } getQueryLink(dbId, sql) { const params = ['dbid=' + dbId, 'sql=' + sql, 'title=Untitled Query']; return getLink(this.state.cleanUri, params); } hideVisualizeModal() { this.setState({ showVisualizeModal: false }); } showVisualizeModal(query) { this.setState({ showVisualizeModal: true }); this.setState({ activeQuery: query }); } restoreSql(query) { this.props.actions.queryEditorSetSql({ id: query.sqlEditorId }, query.sql); } notImplemented() { /* eslint no-alert: 0 */ alert('Not implemented yet!'); } render() { const data = this.props.queries.map((query) => { const q = Object.assign({}, query); if (q.endDttm) { q.duration = fDuration(q.startDttm, q.endDttm); } q.userId = ( <button className="btn btn-link btn-xs" onClick={this.props.onUserClicked.bind(this, q.userId)} > {q.userId} </button> ); q.dbId = ( <button className="btn btn-link btn-xs" onClick={this.props.onDbClicked.bind(this, q.dbId)} > {q.dbId} </button> ); q.started = moment(q.startDttm).format('HH:mm:ss'); const source = (q.ctas) ? q.executedSql : q.sql; q.sql = ( <SqlShrink sql={source} maxWidth={100} /> ); q.output = q.tempTable; q.progress = ( <ProgressBar style={{ width: '75px' }} striped now={q.progress} label={`${q.progress}%`} /> ); let errorTooltip; if (q.errorMessage) { errorTooltip = ( <Link tooltip={q.errorMessage}> <i className="fa fa-exclamation-circle text-danger" /> </Link> ); } q.state = ( <div> <span className={'m-r-3 label label-' + STATE_BSSTYLE_MAP[q.state]}> {q.state} </span> {errorTooltip} </div> ); q.actions = ( <div style={{ width: '75px' }}> <Link className="fa fa-line-chart m-r-3" tooltip="Visualize the data out of this query" onClick={this.showVisualizeModal.bind(this, query)} /> <Link className="fa fa-pencil m-r-3" onClick={this.restoreSql.bind(this, query)} tooltip="Overwrite text in editor with a query on this table" placement="top" /> <Link className="fa fa-plus-circle m-r-3" onClick={self.notImplemented} tooltip="Run query in a new tab" placement="top" /> <Link className="fa fa-trash m-r-3" tooltip="Remove query from log" onClick={this.props.actions.removeQuery.bind(this, query)} /> </div> ); q.querylink = ( <div style={{ width: '100px' }}> <a href={this.getQueryLink(q.dbId, source)} className="btn btn-primary btn-xs" > <i className="fa fa-external-link" />Open in SQL Editor </a> </div> ); return q; }).reverse(); return ( <div> <VisualizeModal show={this.state.showVisualizeModal} query={this.state.activeQuery} onHide={this.hideVisualizeModal.bind(this)} /> <Table columns={this.props.columns} className="table table-condensed" data={data} /> </div> ); } } QueryTable.propTypes = { columns: React.PropTypes.array, actions: React.PropTypes.object, queries: React.PropTypes.array, onUserClicked: React.PropTypes.func, onDbClicked: React.PropTypes.func, }; QueryTable.defaultProps = { columns: ['started', 'duration', 'rows'], queries: [], onUserClicked: () => {}, onDbClicked: () => {}, }; function mapStateToProps() { return {}; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(Actions, dispatch), }; } export default connect(mapStateToProps, mapDispatchToProps)(QueryTable);
caravel/assets/javascripts/SqlLab/components/QueryTable.jsx
1
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.9949628114700317, 0.060158953070640564, 0.00016572733875364065, 0.00021119161101523787, 0.22704197466373444 ]
{ "id": 0, "code_window": [ " </div>\n", " <QueryTable\n", " columns={[\n", " 'state', 'dbId', 'userId',\n", " 'progress', 'rows', 'sql', 'querylink',\n", " ]}\n", " onUserClicked={this.onUserClicked.bind(this)}\n", " onDbClicked={this.onDbClicked.bind(this)}\n", " queries={this.state.queriesArray}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'state', 'db', 'user',\n" ], "file_path": "caravel/assets/javascripts/SqlLab/components/QuerySearch.jsx", "type": "replace", "edit_start_line_idx": 128 }
"""Utility functions used across Caravel""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import object from datetime import date, datetime import decimal import functools import json import logging import numpy import signal import uuid import parsedatetime import sqlalchemy as sa from dateutil.parser import parse from flask import flash, Markup from flask_appbuilder.security.sqla import models as ab_models from markdown import markdown as md from sqlalchemy.types import TypeDecorator, TEXT from pydruid.utils.having import Having EPOCH = datetime(1970, 1, 1) class CaravelException(Exception): pass class CaravelTimeoutException(Exception): pass class CaravelSecurityException(CaravelException): pass class MetricPermException(Exception): pass def can_access(security_manager, permission_name, view_name): """Protecting from has_access failing from missing perms/view""" try: return security_manager.has_access(permission_name, view_name) except: pass return False def flasher(msg, severity=None): """Flask's flash if available, logging call if not""" try: flash(msg, severity) except RuntimeError: if severity == 'danger': logging.error(msg) else: logging.info(msg) class memoized(object): # noqa """Decorator that caches a function's return value each time it is called If called later with the same arguments, the cached value is returned, and not re-evaluated. """ def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): try: return self.cache[args] except KeyError: value = self.func(*args) self.cache[args] = value return value except TypeError: # uncachable -- for instance, passing a list as an argument. # Better to not cache than to blow up entirely. return self.func(*args) def __repr__(self): """Return the function's docstring.""" return self.func.__doc__ def __get__(self, obj, objtype): """Support instance methods.""" return functools.partial(self.__call__, obj) def get_or_create_main_db(caravel): db = caravel.db config = caravel.app.config DB = caravel.models.Database logging.info("Creating database reference") dbobj = db.session.query(DB).filter_by(database_name='main').first() if not dbobj: dbobj = DB(database_name="main") logging.info(config.get("SQLALCHEMY_DATABASE_URI")) dbobj.set_sqlalchemy_uri(config.get("SQLALCHEMY_DATABASE_URI")) dbobj.expose_in_sqllab = True dbobj.allow_run_sync = True db.session.add(dbobj) db.session.commit() return dbobj class DimSelector(Having): def __init__(self, **args): # Just a hack to prevent any exceptions Having.__init__(self, type='equalTo', aggregation=None, value=None) self.having = {'having': { 'type': 'dimSelector', 'dimension': args['dimension'], 'value': args['value'], }} def list_minus(l, minus): """Returns l without what is in minus >>> list_minus([1, 2, 3], [2]) [1, 3] """ return [o for o in l if o not in minus] def parse_human_datetime(s): """ Returns ``datetime.datetime`` from human readable strings >>> from datetime import date, timedelta >>> from dateutil.relativedelta import relativedelta >>> parse_human_datetime('2015-04-03') datetime.datetime(2015, 4, 3, 0, 0) >>> parse_human_datetime('2/3/1969') datetime.datetime(1969, 2, 3, 0, 0) >>> parse_human_datetime("now") <= datetime.now() True >>> parse_human_datetime("yesterday") <= datetime.now() True >>> date.today() - timedelta(1) == parse_human_datetime('yesterday').date() True >>> year_ago_1 = parse_human_datetime('one year ago').date() >>> year_ago_2 = (datetime.now() - relativedelta(years=1) ).date() >>> year_ago_1 == year_ago_2 True """ try: dttm = parse(s) except Exception: try: cal = parsedatetime.Calendar() dttm = dttm_from_timtuple(cal.parse(s)[0]) except Exception as e: logging.exception(e) raise ValueError("Couldn't parse date string [{}]".format(s)) return dttm def dttm_from_timtuple(d): return datetime( d.tm_year, d.tm_mon, d.tm_mday, d.tm_hour, d.tm_min, d.tm_sec) def merge_perm(sm, permission_name, view_menu_name): pv = sm.find_permission_view_menu(permission_name, view_menu_name) if not pv: sm.add_permission_view_menu(permission_name, view_menu_name) def parse_human_timedelta(s): """ Returns ``datetime.datetime`` from natural language time deltas >>> parse_human_datetime("now") <= datetime.now() True """ cal = parsedatetime.Calendar() dttm = dttm_from_timtuple(datetime.now().timetuple()) d = cal.parse(s, dttm)[0] d = datetime( d.tm_year, d.tm_mon, d.tm_mday, d.tm_hour, d.tm_min, d.tm_sec) return d - dttm class JSONEncodedDict(TypeDecorator): """Represents an immutable structure as a json-encoded string.""" impl = TEXT def process_bind_param(self, value, dialect): if value is not None: value = json.dumps(value) return value def process_result_value(self, value, dialect): if value is not None: value = json.loads(value) return value def init(caravel): """Inits the Caravel application with security roles and such""" ADMIN_ONLY_VIEW_MENUES = set([ 'ResetPasswordView', 'RoleModelView', 'Security', 'UserDBModelView', 'SQL Lab', 'AccessRequestsModelView', ]) ADMIN_ONLY_PERMISSIONS = set([ 'can_sync_druid_source', 'can_approve', ]) ALPHA_ONLY_PERMISSIONS = set([ 'all_datasource_access', 'can_add', 'can_download', 'can_delete', 'can_edit', 'can_save', 'datasource_access', 'database_access', 'muldelete', ]) db = caravel.db models = caravel.models config = caravel.app.config sm = caravel.appbuilder.sm alpha = sm.add_role("Alpha") admin = sm.add_role("Admin") get_or_create_main_db(caravel) merge_perm(sm, 'all_datasource_access', 'all_datasource_access') perms = db.session.query(ab_models.PermissionView).all() # set alpha and admin permissions for perm in perms: if ( perm.permission and perm.permission.name in ('datasource_access', 'database_access')): continue if ( perm.view_menu and perm.view_menu.name not in ADMIN_ONLY_VIEW_MENUES and perm.permission and perm.permission.name not in ADMIN_ONLY_PERMISSIONS): sm.add_permission_role(alpha, perm) sm.add_permission_role(admin, perm) gamma = sm.add_role("Gamma") public_role = sm.find_role("Public") public_role_like_gamma = \ public_role and config.get('PUBLIC_ROLE_LIKE_GAMMA', False) # set gamma permissions for perm in perms: if ( perm.view_menu and perm.view_menu.name not in ADMIN_ONLY_VIEW_MENUES and perm.permission and perm.permission.name not in ADMIN_ONLY_PERMISSIONS and perm.permission.name not in ALPHA_ONLY_PERMISSIONS): sm.add_permission_role(gamma, perm) if public_role_like_gamma: sm.add_permission_role(public_role, perm) session = db.session() table_perms = [ table.perm for table in session.query(models.SqlaTable).all()] table_perms += [ table.perm for table in session.query(models.DruidDatasource).all()] for table_perm in table_perms: merge_perm(sm, 'datasource_access', table_perm) db_perms = [db.perm for db in session.query(models.Database).all()] for db_perm in db_perms: merge_perm(sm, 'database_access', db_perm) init_metrics_perm(caravel) def init_metrics_perm(caravel, metrics=None): """Create permissions for restricted metrics :param metrics: a list of metrics to be processed, if not specified, all metrics are processed :type metrics: models.SqlMetric or models.DruidMetric """ db = caravel.db models = caravel.models sm = caravel.appbuilder.sm if not metrics: metrics = [] for model in [models.SqlMetric, models.DruidMetric]: metrics += list(db.session.query(model).all()) for metric in metrics: if metric.is_restricted and metric.perm: merge_perm(sm, 'metric_access', metric.perm) def datetime_f(dttm): """Formats datetime to take less room when it is recent""" if dttm: dttm = dttm.isoformat() now_iso = datetime.now().isoformat() if now_iso[:10] == dttm[:10]: dttm = dttm[11:] elif now_iso[:4] == dttm[:4]: dttm = dttm[5:] return "<nobr>{}</nobr>".format(dttm) def base_json_conv(obj): if isinstance(obj, numpy.int64): return int(obj) elif isinstance(obj, set): return list(obj) elif isinstance(obj, decimal.Decimal): return float(obj) elif isinstance(obj, uuid.UUID): return str(obj) def json_iso_dttm_ser(obj): """ json serializer that deals with dates >>> dttm = datetime(1970, 1, 1) >>> json.dumps({'dttm': dttm}, default=json_iso_dttm_ser) '{"dttm": "1970-01-01T00:00:00"}' """ val = base_json_conv(obj) if val is not None: return val if isinstance(obj, datetime): obj = obj.isoformat() elif isinstance(obj, date): obj = obj.isoformat() else: raise TypeError( "Unserializable object {} of type {}".format(obj, type(obj)) ) return obj def datetime_to_epoch(dttm): return (dttm - EPOCH).total_seconds() * 1000 def now_as_float(): return datetime_to_epoch(datetime.utcnow()) def json_int_dttm_ser(obj): """json serializer that deals with dates""" val = base_json_conv(obj) if val is not None: return val if isinstance(obj, datetime): obj = datetime_to_epoch(obj) elif isinstance(obj, date): obj = (obj - EPOCH.date()).total_seconds() * 1000 else: raise TypeError( "Unserializable object {} of type {}".format(obj, type(obj)) ) return obj def error_msg_from_exception(e): """Translate exception into error message Database have different ways to handle exception. This function attempts to make sense of the exception object and construct a human readable sentence. TODO(bkyryliuk): parse the Presto error message from the connection created via create_engine. engine = create_engine('presto://localhost:3506/silver') - gives an e.message as the str(dict) presto.connect("localhost", port=3506, catalog='silver') - as a dict. The latter version is parsed correctly by this function. """ msg = '' if hasattr(e, 'message'): if type(e.message) is dict: msg = e.message.get('message') elif e.message: msg = "{}".format(e.message) return msg or '{}'.format(e) def markdown(s, markup_wrap=False): s = s or '' s = md(s, [ 'markdown.extensions.tables', 'markdown.extensions.fenced_code', 'markdown.extensions.codehilite', ]) if markup_wrap: s = Markup(s) return s def readfile(filepath): with open(filepath) as f: content = f.read() return content def generic_find_constraint_name(table, columns, referenced, db): """Utility to find a constraint name in alembic migrations""" t = sa.Table(table, db.metadata, autoload=True, autoload_with=db.engine) for fk in t.foreign_key_constraints: if ( fk.referred_table.name == referenced and set(fk.column_keys) == columns): return fk.name def validate_json(obj): if obj: try: json.loads(obj) except Exception: raise CaravelException("JSON is not valid") def table_has_constraint(table, name, db): """Utility to find a constraint name in alembic migrations""" t = sa.Table(table, db.metadata, autoload=True, autoload_with=db.engine) for c in t.constraints: if c.name == name: return True return False class timeout(object): """ To be used in a ``with`` block and timeout its content. """ def __init__(self, seconds=1, error_message='Timeout'): self.seconds = seconds self.error_message = error_message def handle_timeout(self, signum, frame): logging.error("Process timed out") raise CaravelTimeoutException(self.error_message) def __enter__(self): try: signal.signal(signal.SIGALRM, self.handle_timeout) signal.alarm(self.seconds) except ValueError as e: logging.warning("timeout can't be used in the current context") logging.exception(e) def __exit__(self, type, value, traceback): try: signal.alarm(0) except ValueError as e: logging.warning("timeout can't be used in the current context") logging.exception(e)
caravel/utils.py
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.0005800082581117749, 0.0001854231086326763, 0.00016543619858566672, 0.00017086934531107545, 0.00006159453187137842 ]
{ "id": 0, "code_window": [ " </div>\n", " <QueryTable\n", " columns={[\n", " 'state', 'dbId', 'userId',\n", " 'progress', 'rows', 'sql', 'querylink',\n", " ]}\n", " onUserClicked={this.onUserClicked.bind(this)}\n", " onDbClicked={this.onDbClicked.bind(this)}\n", " queries={this.state.queriesArray}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'state', 'db', 'user',\n" ], "file_path": "caravel/assets/javascripts/SqlLab/components/QuerySearch.jsx", "type": "replace", "edit_start_line_idx": 128 }
body { padding-top: 0px; } div.navbar { margin-bottom: 0px; } p { margin-top: 5px; margin-bottom: 15px; } #tutorial img { border: 1px solid gray; box-shadow: 5px 5px 5px #888888; margin-bottom: 10px; } #gallery img { border: 1px solid gray; box-shadow: 5px 5px 5px #888888; margin: 10px; } .carousel img { max-height: 500px; } .carousel { overflow: hidden; height: 500px; } .carousel-caption h1 { font-size: 80px; } .carousel-caption p { font-size: 20px; } div.carousel-caption{ background: rgba(0,0,0,0.5); border-radius: 20px; top: 150px; bottom: auto !important; } .carousel-inner > .item > img { margin: 0 auto; } { margin: -20px; } .carousel-indicators li { background-color: #AAA; border: 1px solid black; } .carousel-indicators .active { background-color: #000; border: 5px solid black; }
docs/_static/docs.css
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.00017469700833316892, 0.00017146021127700806, 0.0001662829308770597, 0.00017166408360935748, 0.0000028123276933911256 ]
{ "id": 0, "code_window": [ " </div>\n", " <QueryTable\n", " columns={[\n", " 'state', 'dbId', 'userId',\n", " 'progress', 'rows', 'sql', 'querylink',\n", " ]}\n", " onUserClicked={this.onUserClicked.bind(this)}\n", " onDbClicked={this.onDbClicked.bind(this)}\n", " queries={this.state.queriesArray}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'state', 'db', 'user',\n" ], "file_path": "caravel/assets/javascripts/SqlLab/components/QuerySearch.jsx", "type": "replace", "edit_start_line_idx": 128 }
.codehilite .hll { background-color: #ffffcc } .codehilite { background: #f8f8f8; } .codehilite .c { color: #408080; font-style: italic } /* Comment */ .codehilite .err { border: 1px solid #FF0000 } /* Error */ .codehilite .k { color: #008000; font-weight: bold } /* Keyword */ .codehilite .o { color: #666666 } /* Operator */ .codehilite .cm { color: #408080; font-style: italic } /* Comment.Multiline */ .codehilite .cp { color: #BC7A00 } /* Comment.Preproc */ .codehilite .c1 { color: #408080; font-style: italic } /* Comment.Single */ .codehilite .cs { color: #408080; font-style: italic } /* Comment.Special */ .codehilite .gd { color: #A00000 } /* Generic.Deleted */ .codehilite .ge { font-style: italic } /* Generic.Emph */ .codehilite .gr { color: #FF0000 } /* Generic.Error */ .codehilite .gh { color: #000080; font-weight: bold } /* Generic.Heading */ .codehilite .gi { color: #00A000 } /* Generic.Inserted */ .codehilite .go { color: #808080 } /* Generic.Output */ .codehilite .gp { color: #000080; font-weight: bold } /* Generic.Prompt */ .codehilite .gs { font-weight: bold } /* Generic.Strong */ .codehilite .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ .codehilite .gt { color: #0040D0 } /* Generic.Traceback */ .codehilite .kc { color: #008000; font-weight: bold } /* Keyword.Constant */ .codehilite .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */ .codehilite .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */ .codehilite .kp { color: #008000 } /* Keyword.Pseudo */ .codehilite .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */ .codehilite .kt { color: #B00040 } /* Keyword.Type */ .codehilite .m { color: #666666 } /* Literal.Number */ .codehilite .s { color: #BA2121 } /* Literal.String */ .codehilite .na { color: #7D9029 } /* Name.Attribute */ .codehilite .nb { color: #008000 } /* Name.Builtin */ .codehilite .nc { color: #0000FF; font-weight: bold } /* Name.Class */ .codehilite .no { color: #880000 } /* Name.Constant */ .codehilite .nd { color: #AA22FF } /* Name.Decorator */ .codehilite .ni { color: #999999; font-weight: bold } /* Name.Entity */ .codehilite .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ .codehilite .nf { color: #0000FF } /* Name.Function */ .codehilite .nl { color: #A0A000 } /* Name.Label */ .codehilite .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ .codehilite .nt { color: #008000; font-weight: bold } /* Name.Tag */ .codehilite .nv { color: #19177C } /* Name.Variable */ .codehilite .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ .codehilite .w { color: #bbbbbb } /* Text.Whitespace */ .codehilite .mf { color: #666666 } /* Literal.Number.Float */ .codehilite .mh { color: #666666 } /* Literal.Number.Hex */ .codehilite .mi { color: #666666 } /* Literal.Number.Integer */ .codehilite .mo { color: #666666 } /* Literal.Number.Oct */ .codehilite .sb { color: #BA2121 } /* Literal.String.Backtick */ .codehilite .sc { color: #BA2121 } /* Literal.String.Char */ .codehilite .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */ .codehilite .s2 { color: #BA2121 } /* Literal.String.Double */ .codehilite .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ .codehilite .sh { color: #BA2121 } /* Literal.String.Heredoc */ .codehilite .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ .codehilite .sx { color: #008000 } /* Literal.String.Other */ .codehilite .sr { color: #BB6688 } /* Literal.String.Regex */ .codehilite .s1 { color: #BA2121 } /* Literal.String.Single */ .codehilite .ss { color: #19177C } /* Literal.String.Symbol */ .codehilite .bp { color: #008000 } /* Name.Builtin.Pseudo */ .codehilite .vc { color: #19177C } /* Name.Variable.Class */ .codehilite .vg { color: #19177C } /* Name.Variable.Global */ .codehilite .vi { color: #19177C } /* Name.Variable.Instance */ .codehilite .il { color: #666666 } /* Literal.Number.Integer.Long */
caravel/assets/vendor/pygments.css
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.0001779187732608989, 0.00017663631297182292, 0.00017472532636020333, 0.00017662080063018948, 9.61070895755256e-7 ]
{ "id": 1, "code_window": [ " };\n", " }\n", " getQueryLink(dbId, sql) {\n", " const params = ['dbid=' + dbId, 'sql=' + sql, 'title=Untitled Query'];\n", " return getLink(this.state.cleanUri, params);\n", " }\n", " hideVisualizeModal() {\n", " this.setState({ showVisualizeModal: false });\n", " }\n", " showVisualizeModal(query) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const link = getLink(this.state.cleanUri, params);\n", " return encodeURI(link);\n" ], "file_path": "caravel/assets/javascripts/SqlLab/components/QueryTable.jsx", "type": "replace", "edit_start_line_idx": 30 }
const $ = window.$ = require('jquery'); import React from 'react'; import { Button } from 'react-bootstrap'; import Select from 'react-select'; import QueryTable from './QueryTable'; import DatabaseSelect from './DatabaseSelect'; import { STATUS_OPTIONS } from '../common'; class QuerySearch extends React.Component { constructor(props) { super(props); this.state = { userLoading: false, userOptions: [], databaseId: null, userId: null, searchText: null, status: 'success', queriesArray: [], }; } componentWillMount() { this.fetchUsers(); this.refreshQueries(); } onUserClicked(userId) { this.setState({ userId }, () => { this.refreshQueries(); }); } onDbClicked(dbId) { this.setState({ databaseId: dbId }, () => { this.refreshQueries(); }); } onChange(db) { const val = (db) ? db.value : null; this.setState({ databaseId: val }); } insertParams(baseUrl, params) { return baseUrl + '?' + params.join('&'); } changeUser(user) { const val = (user) ? user.value : null; this.setState({ userId: val }); } changeStatus(status) { const val = (status) ? status.value : null; this.setState({ status: val }); } changeSearch(event) { this.setState({ searchText: event.target.value }); } fetchUsers() { this.setState({ userLoading: true }); const url = '/users/api/read'; $.getJSON(url, (data, status) => { if (status === 'success') { const options = []; for (let i = 0; i < data.pks.length; i++) { options.push({ value: data.pks[i], label: data.result[i].username }); } this.setState({ userOptions: options, userLoading: false }); } }); } refreshQueries() { const params = [ `userId=${this.state.userId}`, `databaseId=${this.state.databaseId}`, `searchText=${this.state.searchText}`, `status=${this.state.status}`, ]; const url = this.insertParams('/caravel/search_queries', params); $.getJSON(url, (data, status) => { if (status === 'success') { const newQueriesArray = []; for (const id in data) { newQueriesArray.push(data[id]); } this.setState({ queriesArray: newQueriesArray }); } }); } render() { return ( <div> <div className="row space-1"> <div className="col-sm-2"> <Select name="select-user" placeholder="[User]" options={this.state.userOptions} value={this.state.userId} isLoading={this.state.userLoading} autosize={false} onChange={this.changeUser.bind(this)} /> </div> <div className="col-sm-2"> <DatabaseSelect onChange={this.onChange.bind(this)} databaseId={this.state.databaseId} /> </div> <div className="col-sm-4"> <input type="text" onChange={this.changeSearch.bind(this)} className="form-control input-sm" placeholder="Search Results" /> </div> <div className="col-sm-2"> <Select name="select-state" placeholder="[Query Status]" options={STATUS_OPTIONS.map((s) => ({ value: s, label: s }))} value={this.state.status} isLoading={false} autosize={false} onChange={this.changeStatus.bind(this)} /> </div> <Button bsSize="small" bsStyle="success" onClick={this.refreshQueries.bind(this)}> Search </Button> </div> <QueryTable columns={[ 'state', 'dbId', 'userId', 'progress', 'rows', 'sql', 'querylink', ]} onUserClicked={this.onUserClicked.bind(this)} onDbClicked={this.onDbClicked.bind(this)} queries={this.state.queriesArray} /> </div> ); } } export default QuerySearch;
caravel/assets/javascripts/SqlLab/components/QuerySearch.jsx
1
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.31407010555267334, 0.021633589640259743, 0.00016000191681087017, 0.00017443535034544766, 0.07817427068948746 ]
{ "id": 1, "code_window": [ " };\n", " }\n", " getQueryLink(dbId, sql) {\n", " const params = ['dbid=' + dbId, 'sql=' + sql, 'title=Untitled Query'];\n", " return getLink(this.state.cleanUri, params);\n", " }\n", " hideVisualizeModal() {\n", " this.setState({ showVisualizeModal: false });\n", " }\n", " showVisualizeModal(query) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const link = getLink(this.state.cleanUri, params);\n", " return encodeURI(link);\n" ], "file_path": "caravel/assets/javascripts/SqlLab/components/QueryTable.jsx", "type": "replace", "edit_start_line_idx": 30 }
.dashboard a i { cursor: pointer; } .dashboard i.drag { cursor: move !important; } .dashboard .slice-grid .preview-holder { z-index: 1; position: absolute; background-color: #AAA; border-color: #AAA; opacity: 0.3; } div.widget .chart-controls { background-clip: content-box; position: absolute; z-index: 100; right: 0; left: 0; top: 5px; padding: 5px 5px; opacity: 0.75; display: none; } .slice-grid div.widget { border-radius: 0; border: 0px; box-shadow: none; background-color: #fff; overflow: visible; } .dashboard .slice-grid .dragging, .dashboard .slice-grid .resizing { opacity: 0.5; } .dashboard img.loading { width: 20px; margin: 5px; position: absolute; } .dashboard .slice_title { text-align: center; font-weight: bold; font-size: 14px; padding: 5px; } .dashboard div.slice_content { width: 100%; height: 100%; } .modal img.loading { width: 50px; margin: 0; position: relative; } .react-bs-container-body { max-height: 400px; overflow-y: auto; } .hidden, #pageDropDown { display: none; } .slice-grid div.separator.widget { border: 1px solid transparent; box-shadow: none; z-index: 1; } .slice-grid div.separator.widget:hover { border: 1px solid #EEE; } .slice-grid div.separator.widget .chart-header { background-color: transparent; color: transparent; } .slice-grid div.separator.widget h1,h2,h3,h4 { margin-top: 0px; } .dashboard .separator.widget .slice_container { padding: 0px; overflow: visible; } .dashboard .separator.widget .slice_container hr { margin-top: 5px; margin-bottom: 5px; } .separator .chart-container { position: absolute; left: 0; right: 0; top: 0; bottom: 0; } .dashboard .title { margin: 0 20px; } .dashboard .title .favstar { font-size: 20px; } .chart-header .header { font-size: 16px; }
caravel/assets/stylesheets/dashboard.css
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.00017844424291979522, 0.00017569785995874554, 0.00016962749941740185, 0.000176189947524108, 0.000002185788389397203 ]
{ "id": 1, "code_window": [ " };\n", " }\n", " getQueryLink(dbId, sql) {\n", " const params = ['dbid=' + dbId, 'sql=' + sql, 'title=Untitled Query'];\n", " return getLink(this.state.cleanUri, params);\n", " }\n", " hideVisualizeModal() {\n", " this.setState({ showVisualizeModal: false });\n", " }\n", " showVisualizeModal(query) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const link = getLink(this.state.cleanUri, params);\n", " return encodeURI(link);\n" ], "file_path": "caravel/assets/javascripts/SqlLab/components/QueryTable.jsx", "type": "replace", "edit_start_line_idx": 30 }
"""database options for sql lab Revision ID: 41f6a59a61f2 Revises: 3c3ffe173e4f Create Date: 2016-08-31 10:26:37.969107 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '41f6a59a61f2' down_revision = '3c3ffe173e4f' def upgrade(): op.add_column('dbs', sa.Column('allow_ctas', sa.Boolean(), nullable=True)) op.add_column( 'dbs', sa.Column('expose_in_sqllab', sa.Boolean(), nullable=True)) op.add_column( 'dbs', sa.Column('force_ctas_schema', sa.String(length=250), nullable=True)) def downgrade(): op.drop_column('dbs', 'force_ctas_schema') op.drop_column('dbs', 'expose_in_sqllab') op.drop_column('dbs', 'allow_ctas')
caravel/migrations/versions/41f6a59a61f2_database_options_for_sql_lab.py
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.0001780163438525051, 0.00017241710156667978, 0.00016189832240343094, 0.00017733665299601853, 0.000007443077720381552 ]
{ "id": 1, "code_window": [ " };\n", " }\n", " getQueryLink(dbId, sql) {\n", " const params = ['dbid=' + dbId, 'sql=' + sql, 'title=Untitled Query'];\n", " return getLink(this.state.cleanUri, params);\n", " }\n", " hideVisualizeModal() {\n", " this.setState({ showVisualizeModal: false });\n", " }\n", " showVisualizeModal(query) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const link = getLink(this.state.cleanUri, params);\n", " return encodeURI(link);\n" ], "file_path": "caravel/assets/javascripts/SqlLab/components/QueryTable.jsx", "type": "replace", "edit_start_line_idx": 30 }
import React from 'react'; import { expect } from 'chai'; import { describe, it } from 'mocha'; import ModalTrigger from '../../../javascripts/components/ModalTrigger'; describe('ModalTrigger', () => { const defaultProps = { triggerNode: <i className="fa fa-link" />, modalTitle: 'My Modal Title', modalBody: <div>Modal Body</div>, }; it('renders', () => { expect( React.isValidElement(<ModalTrigger {...defaultProps} />) ).to.equal(true); }); });
caravel/assets/spec/javascripts/components/ModalTrigger_spec.jsx
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.00017663749167695642, 0.00017521160771138966, 0.00017378573829773813, 0.00017521160771138966, 0.0000014258766896091402 ]
{ "id": 2, "code_window": [ " if (q.endDttm) {\n", " q.duration = fDuration(q.startDttm, q.endDttm);\n", " }\n", " q.userId = (\n", " <button\n", " className=\"btn btn-link btn-xs\"\n", " onClick={this.props.onUserClicked.bind(this, q.userId)}\n", " >\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " q.user = (\n" ], "file_path": "caravel/assets/javascripts/SqlLab/components/QueryTable.jsx", "type": "replace", "edit_start_line_idx": 52 }
import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as Actions from '../actions'; import moment from 'moment'; import { Table } from 'reactable'; import { ProgressBar } from 'react-bootstrap'; import Link from './Link'; import VisualizeModal from './VisualizeModal'; import SqlShrink from './SqlShrink'; import { STATE_BSSTYLE_MAP } from '../common'; import { fDuration } from '../../modules/dates'; import { getLink } from '../../../utils/common'; class QueryTable extends React.Component { constructor(props) { super(props); const uri = window.location.toString(); const cleanUri = uri.substring(0, uri.indexOf('#')); this.state = { cleanUri, showVisualizeModal: false, activeQuery: null, }; } getQueryLink(dbId, sql) { const params = ['dbid=' + dbId, 'sql=' + sql, 'title=Untitled Query']; return getLink(this.state.cleanUri, params); } hideVisualizeModal() { this.setState({ showVisualizeModal: false }); } showVisualizeModal(query) { this.setState({ showVisualizeModal: true }); this.setState({ activeQuery: query }); } restoreSql(query) { this.props.actions.queryEditorSetSql({ id: query.sqlEditorId }, query.sql); } notImplemented() { /* eslint no-alert: 0 */ alert('Not implemented yet!'); } render() { const data = this.props.queries.map((query) => { const q = Object.assign({}, query); if (q.endDttm) { q.duration = fDuration(q.startDttm, q.endDttm); } q.userId = ( <button className="btn btn-link btn-xs" onClick={this.props.onUserClicked.bind(this, q.userId)} > {q.userId} </button> ); q.dbId = ( <button className="btn btn-link btn-xs" onClick={this.props.onDbClicked.bind(this, q.dbId)} > {q.dbId} </button> ); q.started = moment(q.startDttm).format('HH:mm:ss'); const source = (q.ctas) ? q.executedSql : q.sql; q.sql = ( <SqlShrink sql={source} maxWidth={100} /> ); q.output = q.tempTable; q.progress = ( <ProgressBar style={{ width: '75px' }} striped now={q.progress} label={`${q.progress}%`} /> ); let errorTooltip; if (q.errorMessage) { errorTooltip = ( <Link tooltip={q.errorMessage}> <i className="fa fa-exclamation-circle text-danger" /> </Link> ); } q.state = ( <div> <span className={'m-r-3 label label-' + STATE_BSSTYLE_MAP[q.state]}> {q.state} </span> {errorTooltip} </div> ); q.actions = ( <div style={{ width: '75px' }}> <Link className="fa fa-line-chart m-r-3" tooltip="Visualize the data out of this query" onClick={this.showVisualizeModal.bind(this, query)} /> <Link className="fa fa-pencil m-r-3" onClick={this.restoreSql.bind(this, query)} tooltip="Overwrite text in editor with a query on this table" placement="top" /> <Link className="fa fa-plus-circle m-r-3" onClick={self.notImplemented} tooltip="Run query in a new tab" placement="top" /> <Link className="fa fa-trash m-r-3" tooltip="Remove query from log" onClick={this.props.actions.removeQuery.bind(this, query)} /> </div> ); q.querylink = ( <div style={{ width: '100px' }}> <a href={this.getQueryLink(q.dbId, source)} className="btn btn-primary btn-xs" > <i className="fa fa-external-link" />Open in SQL Editor </a> </div> ); return q; }).reverse(); return ( <div> <VisualizeModal show={this.state.showVisualizeModal} query={this.state.activeQuery} onHide={this.hideVisualizeModal.bind(this)} /> <Table columns={this.props.columns} className="table table-condensed" data={data} /> </div> ); } } QueryTable.propTypes = { columns: React.PropTypes.array, actions: React.PropTypes.object, queries: React.PropTypes.array, onUserClicked: React.PropTypes.func, onDbClicked: React.PropTypes.func, }; QueryTable.defaultProps = { columns: ['started', 'duration', 'rows'], queries: [], onUserClicked: () => {}, onDbClicked: () => {}, }; function mapStateToProps() { return {}; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(Actions, dispatch), }; } export default connect(mapStateToProps, mapDispatchToProps)(QueryTable);
caravel/assets/javascripts/SqlLab/components/QueryTable.jsx
1
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.9977460503578186, 0.060550425201654434, 0.0001665744639467448, 0.000986083410680294, 0.22750383615493774 ]
{ "id": 2, "code_window": [ " if (q.endDttm) {\n", " q.duration = fDuration(q.startDttm, q.endDttm);\n", " }\n", " q.userId = (\n", " <button\n", " className=\"btn btn-link btn-xs\"\n", " onClick={this.props.onUserClicked.bind(this, q.userId)}\n", " >\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " q.user = (\n" ], "file_path": "caravel/assets/javascripts/SqlLab/components/QueryTable.jsx", "type": "replace", "edit_start_line_idx": 52 }
import React from 'react'; import { DropdownButton, MenuItem, Tab, Tabs } from 'react-bootstrap'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as Actions from '../actions'; import SqlEditor from './SqlEditor'; import shortid from 'shortid'; import { getParamFromQuery, getLink } from '../../../utils/common'; import CopyQueryTabUrl from './CopyQueryTabUrl'; let queryCount = 1; class TabbedSqlEditors extends React.Component { constructor(props) { super(props); const uri = window.location.toString(); const search = window.location.search; const cleanUri = search ? uri.substring(0, uri.indexOf('?')) : uri; const query = search.substring(1); this.state = { uri, cleanUri, query, }; } componentWillMount() { if (this.state.query) { queryCount++; const queryEditorProps = { id: shortid.generate(), title: getParamFromQuery(this.state.query, 'title'), dbId: getParamFromQuery(this.state.query, 'dbid'), schema: getParamFromQuery(this.state.query, 'schema'), autorun: getParamFromQuery(this.state.query, 'autorun'), sql: getParamFromQuery(this.state.query, 'sql'), }; this.props.actions.addQueryEditor(queryEditorProps); // Clean the url in browser history window.history.replaceState({}, document.title, this.state.cleanUri); } } getQueryLink(qe) { const params = []; if (qe.dbId) params.push('dbid=' + qe.dbId); if (qe.title) params.push('title=' + qe.title); if (qe.schema) params.push('schema=' + qe.schema); if (qe.autorun) params.push('autorun=' + qe.autorun); if (qe.sql) params.push('sql=' + qe.sql); return getLink(this.state.cleanUri, params); } renameTab(qe) { /* eslint no-alert: 0 */ const newTitle = prompt('Enter a new title for the tab'); if (newTitle) { this.props.actions.queryEditorSetTitle(qe, newTitle); } } activeQueryEditor() { const qeid = this.props.tabHistory[this.props.tabHistory.length - 1]; for (let i = 0; i < this.props.queryEditors.length; i++) { const qe = this.props.queryEditors[i]; if (qe.id === qeid) { return qe; } } return null; } newQueryEditor() { queryCount++; const activeQueryEditor = this.activeQueryEditor(); const qe = { id: shortid.generate(), title: `Untitled Query ${queryCount}`, dbId: (activeQueryEditor) ? activeQueryEditor.dbId : null, schema: (activeQueryEditor) ? activeQueryEditor.schema : null, autorun: false, sql: 'SELECT ...', }; this.props.actions.addQueryEditor(qe); } handleSelect(key) { if (key === 'add_tab') { this.newQueryEditor(); } else { this.props.actions.setActiveQueryEditor({ id: key }); } } render() { const editors = this.props.queryEditors.map((qe, i) => { let latestQuery = this.props.queries[qe.latestQueryId]; const database = this.props.databases[qe.dbId]; const state = (latestQuery) ? latestQuery.state : ''; const tabTitle = ( <div> <div className={'circle ' + state} /> {qe.title} {' '} <DropdownButton bsSize="small" id={'ddbtn-tab-' + i} title="" > <MenuItem eventKey="1" onClick={this.props.actions.removeQueryEditor.bind(this, qe)}> <i className="fa fa-close" /> close tab </MenuItem> <MenuItem eventKey="2" onClick={this.renameTab.bind(this, qe)}> <i className="fa fa-i-cursor" /> rename tab </MenuItem> <MenuItem eventKey="3"> <i className="fa fa-clipboard" /> <CopyQueryTabUrl qe={qe} /> </MenuItem> </DropdownButton> </div> ); return ( <Tab key={qe.id} title={tabTitle} eventKey={qe.id} id={`a11y-query-editor-${qe.id}`} > <div className="panel panel-default"> <div className="panel-body"> <SqlEditor queryEditor={qe} latestQuery={latestQuery} database={database} /> </div> </div> </Tab>); }); return ( <Tabs bsStyle="tabs" activeKey={this.props.tabHistory[this.props.tabHistory.length - 1]} onSelect={this.handleSelect.bind(this)} id="a11y-query-editor-tabs" > {editors} <Tab title={<div><i className="fa fa-plus-circle" />&nbsp;</div>} eventKey="add_tab" /> </Tabs> ); } } TabbedSqlEditors.propTypes = { actions: React.PropTypes.object, databases: React.PropTypes.object, queries: React.PropTypes.object, queryEditors: React.PropTypes.array, tabHistory: React.PropTypes.array, }; TabbedSqlEditors.defaultProps = { tabHistory: [], queryEditors: [], }; function mapStateToProps(state) { return { databases: state.databases, queryEditors: state.queryEditors, queries: state.queries, tabHistory: state.tabHistory, }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(Actions, dispatch), }; } export default connect(mapStateToProps, mapDispatchToProps)(TabbedSqlEditors);
caravel/assets/javascripts/SqlLab/components/TabbedSqlEditors.jsx
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.009243491105735302, 0.0015456771943718195, 0.0001581426477059722, 0.00017080512770917267, 0.002803987357765436 ]
{ "id": 2, "code_window": [ " if (q.endDttm) {\n", " q.duration = fDuration(q.startDttm, q.endDttm);\n", " }\n", " q.userId = (\n", " <button\n", " className=\"btn btn-link btn-xs\"\n", " onClick={this.props.onUserClicked.bind(this, q.userId)}\n", " >\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " q.user = (\n" ], "file_path": "caravel/assets/javascripts/SqlLab/components/QueryTable.jsx", "type": "replace", "edit_start_line_idx": 52 }
class SourceRegistry(object): """ Central Registry for all available datasource engines""" sources = {} @classmethod def register_sources(cls, datasource_config): for module_name, class_names in datasource_config.items(): module_obj = __import__(module_name, fromlist=class_names) for class_name in class_names: source_class = getattr(module_obj, class_name) cls.sources[source_class.type] = source_class
caravel/source_registry.py
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.00016663307906128466, 0.00016604686970822513, 0.0001654606603551656, 0.00016604686970822513, 5.862093530595303e-7 ]
{ "id": 2, "code_window": [ " if (q.endDttm) {\n", " q.duration = fDuration(q.startDttm, q.endDttm);\n", " }\n", " q.userId = (\n", " <button\n", " className=\"btn btn-link btn-xs\"\n", " onClick={this.props.onUserClicked.bind(this, q.userId)}\n", " >\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " q.user = (\n" ], "file_path": "caravel/assets/javascripts/SqlLab/components/QueryTable.jsx", "type": "replace", "edit_start_line_idx": 52 }
{% extends "!layout.html" %} {% set bootswatch_css_custom = ['_static/docs.css'] %} {%- block content %} {{ navBar() }} {% if pagename == 'index' %} <div id="carousel" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#carousel" data-slide-to="0" class="active"></li> <li data-target="#carousel" data-slide-to="1"></li> <li data-target="#carousel" data-slide-to="2"></li> <li data-target="#carousel" data-slide-to="3"></li> <li data-target="#carousel" data-slide-to="4"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> <div class="item active text-center"> <img src="_static/img/dash.png"> <div class="carousel-caption"> <div> <h1>Caravel</h1> <p> an open source data visualization platform </p> </div> </div> </div> <div class="item"> <img src="_static/img/bubble.png"> <div class="carousel-caption"> <h2>Explore your data </h2> <p> Intuitively navigate your data while slicing, dicing, and visualizing through a rich set of widgets </p> </div> </div> <div class="item"> <img src="_static/img/dash.png"> <div class="carousel-caption"> <h2>Create and share dashboards</h2> <p>Assemble many data visualization "slices" into a rich collection</p> </div> </div> <div class="item"> <img src="_static/img/cloud.png"> <div class="carousel-caption"> <h2>Extend</h2> <p>Join the community and take part in extending the widget library</p> </div> </div> <div class="item"> <img src="_static/img/servers.jpg"> <div class="carousel-caption"> <h2>Connect</h2> <p> Access data from MySql, Presto.db, Postgres, RedShift, Oracle, MsSql, SQLite, and more through the SqlAlchemy integration. You can also query realtime data blazingly fast out of Druid.io </p> </div> </div> </div> <!-- Controls --> <div> <a class="left carousel-control" href="#carousel" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#carousel" role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> <hr/> <div class="container"> <div class="jumbotron"> <h1>Caravel</h1> <p> is an open source data visualization platform that provides easy exploration of your data and allows you to create and share beautiful charts and dashboards </p> </div> </div> {% endif %} <div class="container mainbody"> {% block body %}{% endblock %} </div> {%- endblock %}
docs/_templates/layout.html
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.00017191984807141125, 0.0001679307606536895, 0.00016360878362320364, 0.00016855643480084836, 0.000002583475861683837 ]
{ "id": 3, "code_window": [ " <button\n", " className=\"btn btn-link btn-xs\"\n", " onClick={this.props.onUserClicked.bind(this, q.userId)}\n", " >\n", " {q.userId}\n", " </button>\n", " );\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " {q.user}\n" ], "file_path": "caravel/assets/javascripts/SqlLab/components/QueryTable.jsx", "type": "replace", "edit_start_line_idx": 57 }
import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as Actions from '../actions'; import moment from 'moment'; import { Table } from 'reactable'; import { ProgressBar } from 'react-bootstrap'; import Link from './Link'; import VisualizeModal from './VisualizeModal'; import SqlShrink from './SqlShrink'; import { STATE_BSSTYLE_MAP } from '../common'; import { fDuration } from '../../modules/dates'; import { getLink } from '../../../utils/common'; class QueryTable extends React.Component { constructor(props) { super(props); const uri = window.location.toString(); const cleanUri = uri.substring(0, uri.indexOf('#')); this.state = { cleanUri, showVisualizeModal: false, activeQuery: null, }; } getQueryLink(dbId, sql) { const params = ['dbid=' + dbId, 'sql=' + sql, 'title=Untitled Query']; return getLink(this.state.cleanUri, params); } hideVisualizeModal() { this.setState({ showVisualizeModal: false }); } showVisualizeModal(query) { this.setState({ showVisualizeModal: true }); this.setState({ activeQuery: query }); } restoreSql(query) { this.props.actions.queryEditorSetSql({ id: query.sqlEditorId }, query.sql); } notImplemented() { /* eslint no-alert: 0 */ alert('Not implemented yet!'); } render() { const data = this.props.queries.map((query) => { const q = Object.assign({}, query); if (q.endDttm) { q.duration = fDuration(q.startDttm, q.endDttm); } q.userId = ( <button className="btn btn-link btn-xs" onClick={this.props.onUserClicked.bind(this, q.userId)} > {q.userId} </button> ); q.dbId = ( <button className="btn btn-link btn-xs" onClick={this.props.onDbClicked.bind(this, q.dbId)} > {q.dbId} </button> ); q.started = moment(q.startDttm).format('HH:mm:ss'); const source = (q.ctas) ? q.executedSql : q.sql; q.sql = ( <SqlShrink sql={source} maxWidth={100} /> ); q.output = q.tempTable; q.progress = ( <ProgressBar style={{ width: '75px' }} striped now={q.progress} label={`${q.progress}%`} /> ); let errorTooltip; if (q.errorMessage) { errorTooltip = ( <Link tooltip={q.errorMessage}> <i className="fa fa-exclamation-circle text-danger" /> </Link> ); } q.state = ( <div> <span className={'m-r-3 label label-' + STATE_BSSTYLE_MAP[q.state]}> {q.state} </span> {errorTooltip} </div> ); q.actions = ( <div style={{ width: '75px' }}> <Link className="fa fa-line-chart m-r-3" tooltip="Visualize the data out of this query" onClick={this.showVisualizeModal.bind(this, query)} /> <Link className="fa fa-pencil m-r-3" onClick={this.restoreSql.bind(this, query)} tooltip="Overwrite text in editor with a query on this table" placement="top" /> <Link className="fa fa-plus-circle m-r-3" onClick={self.notImplemented} tooltip="Run query in a new tab" placement="top" /> <Link className="fa fa-trash m-r-3" tooltip="Remove query from log" onClick={this.props.actions.removeQuery.bind(this, query)} /> </div> ); q.querylink = ( <div style={{ width: '100px' }}> <a href={this.getQueryLink(q.dbId, source)} className="btn btn-primary btn-xs" > <i className="fa fa-external-link" />Open in SQL Editor </a> </div> ); return q; }).reverse(); return ( <div> <VisualizeModal show={this.state.showVisualizeModal} query={this.state.activeQuery} onHide={this.hideVisualizeModal.bind(this)} /> <Table columns={this.props.columns} className="table table-condensed" data={data} /> </div> ); } } QueryTable.propTypes = { columns: React.PropTypes.array, actions: React.PropTypes.object, queries: React.PropTypes.array, onUserClicked: React.PropTypes.func, onDbClicked: React.PropTypes.func, }; QueryTable.defaultProps = { columns: ['started', 'duration', 'rows'], queries: [], onUserClicked: () => {}, onDbClicked: () => {}, }; function mapStateToProps() { return {}; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(Actions, dispatch), }; } export default connect(mapStateToProps, mapDispatchToProps)(QueryTable);
caravel/assets/javascripts/SqlLab/components/QueryTable.jsx
1
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.9107832312583923, 0.053428590297698975, 0.00016375017003156245, 0.0003811485948972404, 0.20799195766448975 ]
{ "id": 3, "code_window": [ " <button\n", " className=\"btn btn-link btn-xs\"\n", " onClick={this.props.onUserClicked.bind(this, q.userId)}\n", " >\n", " {q.userId}\n", " </button>\n", " );\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " {q.user}\n" ], "file_path": "caravel/assets/javascripts/SqlLab/components/QueryTable.jsx", "type": "replace", "edit_start_line_idx": 57 }
# -*- coding: utf-8 -*- # # caravel documentation build configuration file, created by # sphinx-quickstart on Thu Dec 17 15:42:06 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import shlex import sphinx_bootstrap_theme # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinxcontrib.youtube', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'caravel' copyright = u'2015, Maxime Beauchemin, Airbnb' author = u'Maxime Beauchemin' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. #version = u'1.0' # The full version, including alpha/beta/rc tags. #release = u'1.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'bootstrap' html_theme_path = sphinx_bootstrap_theme.get_html_theme_path() # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { # 'bootswatch_theme': 'cosmo', 'navbar_title': 'Caravel Documentation', 'navbar_fixed_top': "false", 'navbar_sidebarrel': False, 'navbar_site_name': "Topics", #'navbar_class': "navbar navbar-left", } # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. html_show_sourcelink = False # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. html_show_copyright = False # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'caraveldoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'caravel.tex', u'Caravel Documentation', u'Maxime Beauchemin', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'Caravel', u'caravel Documentation', [author], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'Caravel', u'Caravel Documentation', author, 'Caravel', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
docs/conf.py
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.0012303640833124518, 0.00024986336939036846, 0.00016031006816774607, 0.0001693346130196005, 0.00023501970281358808 ]
{ "id": 3, "code_window": [ " <button\n", " className=\"btn btn-link btn-xs\"\n", " onClick={this.props.onUserClicked.bind(this, q.userId)}\n", " >\n", " {q.userId}\n", " </button>\n", " );\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " {q.user}\n" ], "file_path": "caravel/assets/javascripts/SqlLab/components/QueryTable.jsx", "type": "replace", "edit_start_line_idx": 57 }
import React from 'react'; import { Alert, Button, Col, Modal } from 'react-bootstrap'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as Actions from '../actions'; import Select from 'react-select'; import { Table } from 'reactable'; import shortid from 'shortid'; const CHART_TYPES = [ { value: 'dist_bar', label: 'Distribution - Bar Chart', requiresTime: false }, { value: 'pie', label: 'Pie Chart', requiresTime: false }, { value: 'line', label: 'Time Series - Line Chart', requiresTime: true }, { value: 'bar', label: 'Time Series - Bar Chart', requiresTime: true }, ]; class VisualizeModal extends React.Component { constructor(props) { super(props); const uniqueId = shortid.generate(); this.state = { chartType: CHART_TYPES[0], datasourceName: uniqueId, columns: {}, hints: [], }; // update columns if possible this.setStateFromProps(); } componentWillMount() { this.setStateFromProps(); } componentDidMount() { this.validate(); } setStateFromProps() { if (!this.props.query || !this.props.query.results.columns) { return; } const columns = {}; this.props.query.results.columns.forEach((col) => { columns[col.name] = col; }); this.setState({ columns }); } validate() { const hints = []; const cols = this.mergedColumns(); const re = /^\w+$/; Object.keys(cols).forEach((colName) => { if (!re.test(colName)) { hints.push( <div> "{colName}" is not right as a column name, please alias it (as in SELECT count(*) <strong>AS my_alias</strong>) using only alphanumeric characters and underscores </div>); } }); if (this.state.chartType === null) { hints.push('Pick a chart type!'); } else if (this.state.chartType.requiresTime) { let hasTime = false; for (const colName in cols) { const col = cols[colName]; if (col.hasOwnProperty('is_date') && col.is_date) { hasTime = true; } } if (!hasTime) { hints.push('To use this chart type you need at least one column flagged as a date'); } } this.setState({ hints }); } changeChartType(option) { this.setState({ chartType: option }, this.validate); } mergedColumns() { const columns = Object.assign({}, this.state.columns); if (this.props.query && this.props.query.results.columns) { this.props.query.results.columns.forEach((col) => { if (columns[col.name] === undefined) { columns[col.name] = col; } }); } return columns; } visualize() { const vizOptions = { chartType: this.state.chartType.value, datasourceName: this.state.datasourceName, columns: this.state.columns, sql: this.props.query.sql, dbId: this.props.query.dbId, }; window.open('/caravel/sqllab_viz/?data=' + JSON.stringify(vizOptions)); } changeDatasourceName(event) { this.setState({ datasourceName: event.target.value }); this.validate(); } changeCheckbox(attr, columnName, event) { let columns = this.mergedColumns(); const column = Object.assign({}, columns[columnName], { [attr]: event.target.checked }); columns = Object.assign({}, columns, { [columnName]: column }); this.setState({ columns }, this.validate); } changeAggFunction(columnName, option) { let columns = this.mergedColumns(); const val = (option) ? option.value : null; const column = Object.assign({}, columns[columnName], { agg: val }); columns = Object.assign({}, columns, { [columnName]: column }); this.setState({ columns }, this.validate); } render() { if (!(this.props.query)) { return <div />; } const tableData = this.props.query.results.columns.map((col) => ({ column: col.name, is_dimension: ( <input type="checkbox" onChange={this.changeCheckbox.bind(this, 'is_dim', col.name)} checked={(this.state.columns[col.name]) ? this.state.columns[col.name].is_dim : false} className="form-control" /> ), is_date: ( <input type="checkbox" className="form-control" onChange={this.changeCheckbox.bind(this, 'is_date', col.name)} checked={(this.state.columns[col.name]) ? this.state.columns[col.name].is_date : false} /> ), agg_func: ( <Select options={[ { value: 'sum', label: 'SUM(x)' }, { value: 'min', label: 'MIN(x)' }, { value: 'max', label: 'MAX(x)' }, { value: 'avg', label: 'AVG(x)' }, { value: 'count_distinct', label: 'COUNT(DISTINCT x)' }, ]} onChange={this.changeAggFunction.bind(this, col.name)} value={(this.state.columns[col.name]) ? this.state.columns[col.name].agg : null} /> ), })); const alerts = this.state.hints.map((hint, i) => ( <Alert bsStyle="warning" key={i}>{hint}</Alert> )); const modal = ( <div className="VisualizeModal"> <Modal show={this.props.show} onHide={this.props.onHide}> <Modal.Header closeButton> <Modal.Title>Visualize</Modal.Title> </Modal.Header> <Modal.Body> {alerts} <div className="row"> <Col md={6}> Chart Type <Select name="select-chart-type" placeholder="[Chart Type]" options={CHART_TYPES} value={(this.state.chartType) ? this.state.chartType.value : null} autosize={false} onChange={this.changeChartType.bind(this)} /> </Col> <Col md={6}> Datasource Name <input type="text" className="form-control input-sm" placeholder="datasource name" onChange={this.changeDatasourceName.bind(this)} value={this.state.datasourceName} /> </Col> </div> <hr /> <Table className="table table-condensed" columns={['column', 'is_dimension', 'is_date', 'agg_func']} data={tableData} /> <Button onClick={this.visualize.bind(this)} bsStyle="primary" disabled={(this.state.hints.length > 0)} > Visualize </Button> </Modal.Body> </Modal> </div> ); return modal; } } VisualizeModal.propTypes = { query: React.PropTypes.object, show: React.PropTypes.bool, onHide: React.PropTypes.func, }; VisualizeModal.defaultProps = { show: false, onHide: () => {}, }; function mapStateToProps() { return {}; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(Actions, dispatch), }; } export default connect(mapStateToProps, mapDispatchToProps)(VisualizeModal);
caravel/assets/javascripts/SqlLab/components/VisualizeModal.jsx
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.0017813040176406503, 0.00027957549900747836, 0.0001649194600759074, 0.0001770468952599913, 0.000325565692037344 ]
{ "id": 3, "code_window": [ " <button\n", " className=\"btn btn-link btn-xs\"\n", " onClick={this.props.onUserClicked.bind(this, q.userId)}\n", " >\n", " {q.userId}\n", " </button>\n", " );\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " {q.user}\n" ], "file_path": "caravel/assets/javascripts/SqlLab/components/QueryTable.jsx", "type": "replace", "edit_start_line_idx": 57 }
import React from 'react'; import SyntaxHighlighter from 'react-syntax-highlighter'; import { github } from 'react-syntax-highlighter/dist/styles'; const SqlShrink = (props) => { const sql = props.sql || ''; let lines = sql.split('\n'); if (lines.length >= props.maxLines) { lines = lines.slice(0, props.maxLines); lines.push('{...}'); } const shrunk = lines.map((line) => { if (line.length > props.maxWidth) { return line.slice(0, props.maxWidth) + '{...}'; } return line; }) .join('\n'); return ( <div> <SyntaxHighlighter language="sql" style={github}> {shrunk} </SyntaxHighlighter> </div> ); }; SqlShrink.defaultProps = { maxWidth: 60, maxLines: 6, }; SqlShrink.propTypes = { sql: React.PropTypes.string, maxWidth: React.PropTypes.number, maxLines: React.PropTypes.number, }; export default SqlShrink;
caravel/assets/javascripts/SqlLab/components/SqlShrink.jsx
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.00023361669445876032, 0.00018822355195879936, 0.00016978413623292, 0.00017474667401984334, 0.000026454370527062565 ]
{ "id": 4, "code_window": [ " </button>\n", " );\n", " q.dbId = (\n", " <button\n", " className=\"btn btn-link btn-xs\"\n", " onClick={this.props.onDbClicked.bind(this, q.dbId)}\n", " >\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " q.db = (\n" ], "file_path": "caravel/assets/javascripts/SqlLab/components/QueryTable.jsx", "type": "replace", "edit_start_line_idx": 60 }
const $ = window.$ = require('jquery'); import React from 'react'; import { Button } from 'react-bootstrap'; import Select from 'react-select'; import QueryTable from './QueryTable'; import DatabaseSelect from './DatabaseSelect'; import { STATUS_OPTIONS } from '../common'; class QuerySearch extends React.Component { constructor(props) { super(props); this.state = { userLoading: false, userOptions: [], databaseId: null, userId: null, searchText: null, status: 'success', queriesArray: [], }; } componentWillMount() { this.fetchUsers(); this.refreshQueries(); } onUserClicked(userId) { this.setState({ userId }, () => { this.refreshQueries(); }); } onDbClicked(dbId) { this.setState({ databaseId: dbId }, () => { this.refreshQueries(); }); } onChange(db) { const val = (db) ? db.value : null; this.setState({ databaseId: val }); } insertParams(baseUrl, params) { return baseUrl + '?' + params.join('&'); } changeUser(user) { const val = (user) ? user.value : null; this.setState({ userId: val }); } changeStatus(status) { const val = (status) ? status.value : null; this.setState({ status: val }); } changeSearch(event) { this.setState({ searchText: event.target.value }); } fetchUsers() { this.setState({ userLoading: true }); const url = '/users/api/read'; $.getJSON(url, (data, status) => { if (status === 'success') { const options = []; for (let i = 0; i < data.pks.length; i++) { options.push({ value: data.pks[i], label: data.result[i].username }); } this.setState({ userOptions: options, userLoading: false }); } }); } refreshQueries() { const params = [ `userId=${this.state.userId}`, `databaseId=${this.state.databaseId}`, `searchText=${this.state.searchText}`, `status=${this.state.status}`, ]; const url = this.insertParams('/caravel/search_queries', params); $.getJSON(url, (data, status) => { if (status === 'success') { const newQueriesArray = []; for (const id in data) { newQueriesArray.push(data[id]); } this.setState({ queriesArray: newQueriesArray }); } }); } render() { return ( <div> <div className="row space-1"> <div className="col-sm-2"> <Select name="select-user" placeholder="[User]" options={this.state.userOptions} value={this.state.userId} isLoading={this.state.userLoading} autosize={false} onChange={this.changeUser.bind(this)} /> </div> <div className="col-sm-2"> <DatabaseSelect onChange={this.onChange.bind(this)} databaseId={this.state.databaseId} /> </div> <div className="col-sm-4"> <input type="text" onChange={this.changeSearch.bind(this)} className="form-control input-sm" placeholder="Search Results" /> </div> <div className="col-sm-2"> <Select name="select-state" placeholder="[Query Status]" options={STATUS_OPTIONS.map((s) => ({ value: s, label: s }))} value={this.state.status} isLoading={false} autosize={false} onChange={this.changeStatus.bind(this)} /> </div> <Button bsSize="small" bsStyle="success" onClick={this.refreshQueries.bind(this)}> Search </Button> </div> <QueryTable columns={[ 'state', 'dbId', 'userId', 'progress', 'rows', 'sql', 'querylink', ]} onUserClicked={this.onUserClicked.bind(this)} onDbClicked={this.onDbClicked.bind(this)} queries={this.state.queriesArray} /> </div> ); } } export default QuerySearch;
caravel/assets/javascripts/SqlLab/components/QuerySearch.jsx
1
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.013426415622234344, 0.0018189229303970933, 0.0001621504343347624, 0.00017949767061509192, 0.004103796556591988 ]
{ "id": 4, "code_window": [ " </button>\n", " );\n", " q.dbId = (\n", " <button\n", " className=\"btn btn-link btn-xs\"\n", " onClick={this.props.onDbClicked.bind(this, q.dbId)}\n", " >\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " q.db = (\n" ], "file_path": "caravel/assets/javascripts/SqlLab/components/QueryTable.jsx", "type": "replace", "edit_start_line_idx": 60 }
import React, { PropTypes } from 'react'; import CopyToClipboard from './../../components/CopyToClipboard'; import { Popover, OverlayTrigger } from 'react-bootstrap'; const propTypes = { slice: PropTypes.object.isRequired, }; export default class EmbedCodeButton extends React.Component { constructor(props) { super(props); this.state = { height: '400', width: '600', srcLink: window.location.origin + props.slice.data.standalone_endpoint, }; this.handleInputChange = this.handleInputChange.bind(this); } handleInputChange(e) { const value = e.currentTarget.value; const name = e.currentTarget.name; const data = {}; data[name] = value; this.setState(data); } generateEmbedHTML() { const { width, height, srcLink } = this.state; /* eslint max-len: 0 */ const embedHTML = `<iframe src="${srcLink}" width="${width}" height="${height}" seamless frameBorder="0" scrolling="no"></iframe>`; return embedHTML; } renderPopover() { const html = this.generateEmbedHTML(); return ( <Popover id="embed-code-popover"> <div> <div className="row"> <div className="col-sm-10"> <textarea name="embedCode" value={html} rows="4" readOnly className="form-control input-sm"></textarea> </div> <div className="col-sm-2"> <CopyToClipboard shouldShowText={false} text={html} copyNode={<i className="fa fa-clipboard" title="Copy to clipboard"></i>} /> </div> </div> <br /> <div className="row"> <div className="col-md-6 col-sm-12"> <div className="form-group"> <small> <label className="control-label" htmlFor="embed-height">Height</label> </small> <input className="form-control input-sm" type="text" defaultValue={this.state.height} name="height" onChange={this.handleInputChange} /> </div> </div> <div className="col-md-6 col-sm-12"> <div className="form-group"> <small> <label className="control-label" htmlFor="embed-width">Width</label> </small> <input className="form-control input-sm" type="text" defaultValue={this.state.width} name="width" onChange={this.handleInputChange} id="embed-width" /> </div> </div> </div> </div> </Popover> ); } render() { return ( <OverlayTrigger trigger="click" rootClose placement="left" overlay={this.renderPopover()} > <span className="btn btn-default btn-sm"> <i className="fa fa-code"></i>&nbsp; </span> </OverlayTrigger> ); } } EmbedCodeButton.propTypes = propTypes;
caravel/assets/javascripts/explore/components/EmbedCodeButton.jsx
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.0004860561457462609, 0.00020058848895132542, 0.0001634997606743127, 0.0001730269577819854, 0.00009056740236701444 ]
{ "id": 4, "code_window": [ " </button>\n", " );\n", " q.dbId = (\n", " <button\n", " className=\"btn btn-link btn-xs\"\n", " onClick={this.props.onDbClicked.bind(this, q.dbId)}\n", " >\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " q.db = (\n" ], "file_path": "caravel/assets/javascripts/SqlLab/components/QueryTable.jsx", "type": "replace", "edit_start_line_idx": 60 }
"""adjusting key length Revision ID: 956a063c52b3 Revises: f0fbf6129e13 Create Date: 2016-05-11 17:28:32.407340 """ # revision identifiers, used by Alembic. revision = '956a063c52b3' down_revision = 'f0fbf6129e13' from alembic import op import sqlalchemy as sa def upgrade(): with op.batch_alter_table('clusters', schema=None) as batch_op: batch_op.alter_column('broker_endpoint', existing_type=sa.VARCHAR(length=256), type_=sa.String(length=255), existing_nullable=True) batch_op.alter_column('broker_host', existing_type=sa.VARCHAR(length=256), type_=sa.String(length=255), existing_nullable=True) batch_op.alter_column('coordinator_endpoint', existing_type=sa.VARCHAR(length=256), type_=sa.String(length=255), existing_nullable=True) batch_op.alter_column('coordinator_host', existing_type=sa.VARCHAR(length=256), type_=sa.String(length=255), existing_nullable=True) with op.batch_alter_table('columns', schema=None) as batch_op: batch_op.alter_column('column_name', existing_type=sa.VARCHAR(length=256), type_=sa.String(length=255), existing_nullable=True) with op.batch_alter_table('datasources', schema=None) as batch_op: batch_op.alter_column('datasource_name', existing_type=sa.VARCHAR(length=256), type_=sa.String(length=255), existing_nullable=True) with op.batch_alter_table('table_columns', schema=None) as batch_op: batch_op.alter_column('column_name', existing_type=sa.VARCHAR(length=256), type_=sa.String(length=255), existing_nullable=True) with op.batch_alter_table('tables', schema=None) as batch_op: batch_op.alter_column('schema', existing_type=sa.VARCHAR(length=256), type_=sa.String(length=255), existing_nullable=True) def downgrade(): with op.batch_alter_table('tables', schema=None) as batch_op: batch_op.alter_column('schema', existing_type=sa.String(length=255), type_=sa.VARCHAR(length=256), existing_nullable=True) with op.batch_alter_table('table_columns', schema=None) as batch_op: batch_op.alter_column('column_name', existing_type=sa.String(length=255), type_=sa.VARCHAR(length=256), existing_nullable=True) with op.batch_alter_table('datasources', schema=None) as batch_op: batch_op.alter_column('datasource_name', existing_type=sa.String(length=255), type_=sa.VARCHAR(length=256), existing_nullable=True) with op.batch_alter_table('columns', schema=None) as batch_op: batch_op.alter_column('column_name', existing_type=sa.String(length=255), type_=sa.VARCHAR(length=256), existing_nullable=True) with op.batch_alter_table('clusters', schema=None) as batch_op: batch_op.alter_column('coordinator_host', existing_type=sa.String(length=255), type_=sa.VARCHAR(length=256), existing_nullable=True) batch_op.alter_column('coordinator_endpoint', existing_type=sa.String(length=255), type_=sa.VARCHAR(length=256), existing_nullable=True) batch_op.alter_column('broker_host', existing_type=sa.String(length=255), type_=sa.VARCHAR(length=256), existing_nullable=True) batch_op.alter_column('broker_endpoint', existing_type=sa.String(length=255), type_=sa.VARCHAR(length=256), existing_nullable=True)
caravel/migrations/versions/956a063c52b3_adjusting_key_length.py
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.0001728103234199807, 0.0001709361677058041, 0.0001670430356170982, 0.0001710829237708822, 0.0000016227064634222188 ]
{ "id": 4, "code_window": [ " </button>\n", " );\n", " q.dbId = (\n", " <button\n", " className=\"btn btn-link btn-xs\"\n", " onClick={this.props.onDbClicked.bind(this, q.dbId)}\n", " >\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " q.db = (\n" ], "file_path": "caravel/assets/javascripts/SqlLab/components/QueryTable.jsx", "type": "replace", "edit_start_line_idx": 60 }
import React from 'react'; import { expect } from 'chai'; import { shallow } from 'enzyme'; import QueryAndSaveButtons from '../../../../javascripts/explore/components/QueryAndSaveBtns'; describe('QueryAndSaveButtons', () => { let defaultProps = { canAdd: 'True', onQuery: () => {} }; // It must render it('renders', () => { expect(React.isValidElement(<QueryAndSaveButtons {...defaultProps} />)).to.equal(true); }); // Test the output describe('output', () => { let wrapper; beforeEach(() => { wrapper = shallow(<QueryAndSaveButtons {...defaultProps} />); }); it('renders 2 buttons', () => { expect(wrapper.find('button')).to.have.lengthOf(2); }); it('renders buttons with correct text', () => { expect(wrapper.find('button').contains(' Query')).to.eql(true); expect(wrapper.find('button').contains(' Save as')).to.eql(true); }); }); });
caravel/assets/spec/javascripts/explore/components/QueryAndSaveBtns_spec.jsx
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.00023843917006161064, 0.00018753654148895293, 0.00016729056369513273, 0.00017220823792740703, 0.00002948192741314415 ]
{ "id": 5, "code_window": [ " <button\n", " className=\"btn btn-link btn-xs\"\n", " onClick={this.props.onDbClicked.bind(this, q.dbId)}\n", " >\n", " {q.dbId}\n", " </button>\n", " );\n", " q.started = moment(q.startDttm).format('HH:mm:ss');\n", " const source = (q.ctas) ? q.executedSql : q.sql;\n", " q.sql = (\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " {q.db}\n" ], "file_path": "caravel/assets/javascripts/SqlLab/components/QueryTable.jsx", "type": "replace", "edit_start_line_idx": 65 }
import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as Actions from '../actions'; import moment from 'moment'; import { Table } from 'reactable'; import { ProgressBar } from 'react-bootstrap'; import Link from './Link'; import VisualizeModal from './VisualizeModal'; import SqlShrink from './SqlShrink'; import { STATE_BSSTYLE_MAP } from '../common'; import { fDuration } from '../../modules/dates'; import { getLink } from '../../../utils/common'; class QueryTable extends React.Component { constructor(props) { super(props); const uri = window.location.toString(); const cleanUri = uri.substring(0, uri.indexOf('#')); this.state = { cleanUri, showVisualizeModal: false, activeQuery: null, }; } getQueryLink(dbId, sql) { const params = ['dbid=' + dbId, 'sql=' + sql, 'title=Untitled Query']; return getLink(this.state.cleanUri, params); } hideVisualizeModal() { this.setState({ showVisualizeModal: false }); } showVisualizeModal(query) { this.setState({ showVisualizeModal: true }); this.setState({ activeQuery: query }); } restoreSql(query) { this.props.actions.queryEditorSetSql({ id: query.sqlEditorId }, query.sql); } notImplemented() { /* eslint no-alert: 0 */ alert('Not implemented yet!'); } render() { const data = this.props.queries.map((query) => { const q = Object.assign({}, query); if (q.endDttm) { q.duration = fDuration(q.startDttm, q.endDttm); } q.userId = ( <button className="btn btn-link btn-xs" onClick={this.props.onUserClicked.bind(this, q.userId)} > {q.userId} </button> ); q.dbId = ( <button className="btn btn-link btn-xs" onClick={this.props.onDbClicked.bind(this, q.dbId)} > {q.dbId} </button> ); q.started = moment(q.startDttm).format('HH:mm:ss'); const source = (q.ctas) ? q.executedSql : q.sql; q.sql = ( <SqlShrink sql={source} maxWidth={100} /> ); q.output = q.tempTable; q.progress = ( <ProgressBar style={{ width: '75px' }} striped now={q.progress} label={`${q.progress}%`} /> ); let errorTooltip; if (q.errorMessage) { errorTooltip = ( <Link tooltip={q.errorMessage}> <i className="fa fa-exclamation-circle text-danger" /> </Link> ); } q.state = ( <div> <span className={'m-r-3 label label-' + STATE_BSSTYLE_MAP[q.state]}> {q.state} </span> {errorTooltip} </div> ); q.actions = ( <div style={{ width: '75px' }}> <Link className="fa fa-line-chart m-r-3" tooltip="Visualize the data out of this query" onClick={this.showVisualizeModal.bind(this, query)} /> <Link className="fa fa-pencil m-r-3" onClick={this.restoreSql.bind(this, query)} tooltip="Overwrite text in editor with a query on this table" placement="top" /> <Link className="fa fa-plus-circle m-r-3" onClick={self.notImplemented} tooltip="Run query in a new tab" placement="top" /> <Link className="fa fa-trash m-r-3" tooltip="Remove query from log" onClick={this.props.actions.removeQuery.bind(this, query)} /> </div> ); q.querylink = ( <div style={{ width: '100px' }}> <a href={this.getQueryLink(q.dbId, source)} className="btn btn-primary btn-xs" > <i className="fa fa-external-link" />Open in SQL Editor </a> </div> ); return q; }).reverse(); return ( <div> <VisualizeModal show={this.state.showVisualizeModal} query={this.state.activeQuery} onHide={this.hideVisualizeModal.bind(this)} /> <Table columns={this.props.columns} className="table table-condensed" data={data} /> </div> ); } } QueryTable.propTypes = { columns: React.PropTypes.array, actions: React.PropTypes.object, queries: React.PropTypes.array, onUserClicked: React.PropTypes.func, onDbClicked: React.PropTypes.func, }; QueryTable.defaultProps = { columns: ['started', 'duration', 'rows'], queries: [], onUserClicked: () => {}, onDbClicked: () => {}, }; function mapStateToProps() { return {}; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(Actions, dispatch), }; } export default connect(mapStateToProps, mapDispatchToProps)(QueryTable);
caravel/assets/javascripts/SqlLab/components/QueryTable.jsx
1
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.9984009861946106, 0.2184126079082489, 0.00016417856386397034, 0.0003407102485653013, 0.4018385708332062 ]
{ "id": 5, "code_window": [ " <button\n", " className=\"btn btn-link btn-xs\"\n", " onClick={this.props.onDbClicked.bind(this, q.dbId)}\n", " >\n", " {q.dbId}\n", " </button>\n", " );\n", " q.started = moment(q.startDttm).format('HH:mm:ss');\n", " const source = (q.ctas) ? q.executedSql : q.sql;\n", " q.sql = (\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " {q.db}\n" ], "file_path": "caravel/assets/javascripts/SqlLab/components/QueryTable.jsx", "type": "replace", "edit_start_line_idx": 65 }
const $ = require('jquery'); function iframeWidget(slice) { function refresh() { $('#code').attr('rows', '15'); $.getJSON(slice.jsonEndpoint(), function (payload) { const url = slice.render_template(payload.form_data.url); slice.container.html('<iframe style="width:100%;"></iframe>'); const iframe = slice.container.find('iframe'); iframe.css('height', slice.height()); iframe.attr('src', url); slice.done(payload); }) .fail(function (xhr) { slice.error(xhr.responseText, xhr); }); } return { render: refresh, resize: refresh, }; } module.exports = iframeWidget;
caravel/assets/visualizations/iframe.js
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.00017275827121920884, 0.00017131779168266803, 0.00017019065853673965, 0.00017100447439588606, 0.0000010713819165175664 ]
{ "id": 5, "code_window": [ " <button\n", " className=\"btn btn-link btn-xs\"\n", " onClick={this.props.onDbClicked.bind(this, q.dbId)}\n", " >\n", " {q.dbId}\n", " </button>\n", " );\n", " q.started = moment(q.startDttm).format('HH:mm:ss');\n", " const source = (q.ctas) ? q.executedSql : q.sql;\n", " q.sql = (\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " {q.db}\n" ], "file_path": "caravel/assets/javascripts/SqlLab/components/QueryTable.jsx", "type": "replace", "edit_start_line_idx": 65 }
.directed_force path.link { fill: none; stroke: #000; stroke-width: 1.5px; } .directed_force circle { fill: #ccc; stroke: #000; stroke-width: 1.5px; stroke-opacity: 1; opacity: 0.75; } .directed_force text { fill: #000; font: 10px sans-serif; pointer-events: none; }
caravel/assets/visualizations/directed_force.css
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.00017074232164304703, 0.000168498998391442, 0.00016625567513983697, 0.000168498998391442, 0.000002243323251605034 ]
{ "id": 5, "code_window": [ " <button\n", " className=\"btn btn-link btn-xs\"\n", " onClick={this.props.onDbClicked.bind(this, q.dbId)}\n", " >\n", " {q.dbId}\n", " </button>\n", " );\n", " q.started = moment(q.startDttm).format('HH:mm:ss');\n", " const source = (q.ctas) ? q.executedSql : q.sql;\n", " q.sql = (\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " {q.db}\n" ], "file_path": "caravel/assets/javascripts/SqlLab/components/QueryTable.jsx", "type": "replace", "edit_start_line_idx": 65 }
/* eslint-disable no-shadow, no-param-reassign, no-underscore-dangle, no-use-before-define*/ import d3 from 'd3'; import { category21 } from '../javascripts/modules/colors'; require('./treemap.css'); /* Modified from http://bl.ocks.org/ganeshv/6a8e9ada3ab7f2d88022 */ function treemap(slice) { const div = d3.select(slice.selector); const _draw = function (data, eltWidth, eltHeight, formData) { const margin = { top: 0, right: 0, bottom: 0, left: 0 }; const navBarHeight = 36; const navBarTitleSize = navBarHeight / 3; const navBarBuffer = 10; const width = eltWidth - margin.left - margin.right; const height = (eltHeight - navBarHeight - navBarBuffer - margin.top - margin.bottom); const formatNumber = d3.format(formData.number_format); let transitioning; const x = d3.scale.linear() .domain([0, width]) .range([0, width]); const y = d3.scale.linear() .domain([0, height]) .range([0, height]); const treemap = d3.layout.treemap() .children(function (d, depth) { return depth ? null : d._children; }) .sort(function (a, b) { return a.value - b.value; }) .ratio(formData.treemap_ratio) .mode('squarify') .round(false); const svg = div.append('svg') .attr('width', eltWidth) .attr('height', eltHeight); const chartContainer = svg.append('g') .attr('transform', 'translate(' + margin.left + ',' + (margin.top + navBarHeight + navBarBuffer) + ')') .style('shape-rendering', 'crispEdges'); const grandparent = svg.append('g') .attr('class', 'grandparent') .attr('transform', 'translate(0,' + (margin.top + navBarBuffer / 2) + ')'); grandparent.append('rect') .attr('width', width) .attr('height', navBarHeight); grandparent.append('text') .attr('x', width / 2) .attr('y', navBarHeight / 2 + navBarTitleSize / 2) .style('font-size', navBarTitleSize + 'px') .style('text-anchor', 'middle'); const initialize = function (root) { root.x = root.y = 0; root.dx = width; root.dy = height; root.depth = 0; }; // Aggregate the values for internal nodes. This is normally done by the // treemap layout, but not here because of our custom implementation. // We also take a snapshot of the original children (_children) to avoid // the children being overwritten when when layout is computed. const accumulate = function (d) { d._children = d.children; if (d._children) { d.value = d.children.reduce(function (p, v) { return p + accumulate(v); }, 0); } return d.value; }; // Compute the treemap layout recursively such that each group of siblings // uses the same size (1x1) rather than the dimensions of the parent cell. // This optimizes the layout for the current zoom state. Note that a wrapper // object is created for the parent node for each group of siblings so that // the parents dimensions are not discarded as we recurse. Since each group // of sibling was laid out in 1x1, we must rescale to fit using absolute // coordinates. This lets us use a viewport to zoom. const layout = function (d) { if (d._children) { treemap.nodes({ _children: d._children }); d._children.forEach(function (c) { c.x = d.x + c.x * d.dx; c.y = d.y + c.y * d.dy; c.dx *= d.dx; c.dy *= d.dy; c.parent = d; layout(c); }); } }; const display = function (d) { const transition = function (d) { if (transitioning || !d) { return; } transitioning = true; const g2 = display(d); const t1 = g1.transition().duration(750); const t2 = g2.transition().duration(750); // Update the domain only after entering new elements. x.domain([d.x, d.x + d.dx]); y.domain([d.y, d.y + d.dy]); // Enable anti-aliasing during the transition. chartContainer.style('shape-rendering', null); // Draw child nodes on top of parent nodes. chartContainer.selectAll('.depth').sort(function (a, b) { return a.depth - b.depth; }); // Fade-in entering text. g2.selectAll('text').style('fill-opacity', 0); // Transition to the new view. t1.selectAll('.ptext').call(text).style('fill-opacity', 0); t1.selectAll('.ctext').call(text2).style('fill-opacity', 0); t2.selectAll('.ptext').call(text).style('fill-opacity', 1); t2.selectAll('.ctext').call(text2).style('fill-opacity', 1); t1.selectAll('rect').call(rect); t2.selectAll('rect').call(rect); // Remove the old node when the transition is finished. t1.remove().each('end', function () { chartContainer.style('shape-rendering', 'crispEdges'); transitioning = false; }); }; grandparent .datum(d.parent) .on('click', transition) .select('text') .text(name(d)); const g1 = chartContainer.append('g') .datum(d) .attr('class', 'depth'); const g = g1.selectAll('g') .data(d._children) .enter() .append('g'); g.filter(function (d) { return d._children; }) .classed('children', true) .on('click', transition); const children = g.selectAll('.child') .data(function (d) { return d._children || [d]; }) .enter() .append('g'); children.append('rect') .attr('class', 'child') .call(rect) .append('title') .text(function (d) { return d.name + ' (' + formatNumber(d.value) + ')'; }); children.append('text') .attr('class', 'ctext') .text(function (d) { return d.name; }) .call(text2); g.append('rect') .attr('class', 'parent') .call(rect); const t = g.append('text') .attr('class', 'ptext') .attr('dy', '.75em'); t.append('tspan') .text(function (d) { return d.name; }); t.append('tspan') .attr('dy', '1.0em') .text(function (d) { return formatNumber(d.value); }); t.call(text); g.selectAll('rect') .style('fill', function (d) { return category21(d.name); }); return g; }; const text = function (selection) { selection.selectAll('tspan') .attr('x', function (d) { return x(d.x) + 6; }); selection.attr('x', function (d) { return x(d.x) + 6; }) .attr('y', function (d) { return y(d.y) + 6; }) .style('opacity', function (d) { return this.getComputedTextLength() < x(d.x + d.dx) - x(d.x) ? 1 : 0; }); }; const text2 = function (selection) { selection.attr('x', function (d) { return x(d.x + d.dx) - this.getComputedTextLength() - 6; }) .attr('y', function (d) { return y(d.y + d.dy) - 6; }) .style('opacity', function (d) { return this.getComputedTextLength() < x(d.x + d.dx) - x(d.x) ? 1 : 0; }); }; const rect = function (selection) { selection.attr('x', function (d) { return x(d.x); }) .attr('y', function (d) { return y(d.y); }) .attr('width', function (d) { return x(d.x + d.dx) - x(d.x); }) .attr('height', function (d) { return y(d.y + d.dy) - y(d.y); }); }; const name = function (d) { return d.parent ? name(d.parent) + ' / ' + d.name + ' (' + formatNumber(d.value) + ')' : d.name + ' (' + formatNumber(d.value) + ')'; }; initialize(data); accumulate(data); layout(data); display(data); }; const render = function () { d3.json(slice.jsonEndpoint(), function (error, json) { if (error !== null) { slice.error(error.responseText, error); return; } div.selectAll('*').remove(); const width = slice.width(); // facet muliple metrics (no sense in combining) const height = slice.height() / json.data.length; for (let i = 0, l = json.data.length; i < l; i ++) { _draw(json.data[i], width, height, json.form_data); } slice.done(json); }); }; return { render, resize: render, }; } module.exports = treemap;
caravel/assets/visualizations/treemap.js
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.0001749328657751903, 0.00017145472520496696, 0.0001660121779423207, 0.00017192927771247923, 0.00000219246089727676 ]
{ "id": 6, "code_window": [ " DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=True)\n", "\n", " database = relationship(\n", " 'Database', foreign_keys=[database_id], backref='queries')\n", "\n", " __table_args__ = (\n", " sqla.Index('ti_user_id_changed_on', user_id, changed_on),\n", " )\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " user = relationship('User', backref='queries', foreign_keys=[user_id])\n" ], "file_path": "caravel/models.py", "type": "add", "edit_start_line_idx": 1000 }
import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as Actions from '../actions'; import moment from 'moment'; import { Table } from 'reactable'; import { ProgressBar } from 'react-bootstrap'; import Link from './Link'; import VisualizeModal from './VisualizeModal'; import SqlShrink from './SqlShrink'; import { STATE_BSSTYLE_MAP } from '../common'; import { fDuration } from '../../modules/dates'; import { getLink } from '../../../utils/common'; class QueryTable extends React.Component { constructor(props) { super(props); const uri = window.location.toString(); const cleanUri = uri.substring(0, uri.indexOf('#')); this.state = { cleanUri, showVisualizeModal: false, activeQuery: null, }; } getQueryLink(dbId, sql) { const params = ['dbid=' + dbId, 'sql=' + sql, 'title=Untitled Query']; return getLink(this.state.cleanUri, params); } hideVisualizeModal() { this.setState({ showVisualizeModal: false }); } showVisualizeModal(query) { this.setState({ showVisualizeModal: true }); this.setState({ activeQuery: query }); } restoreSql(query) { this.props.actions.queryEditorSetSql({ id: query.sqlEditorId }, query.sql); } notImplemented() { /* eslint no-alert: 0 */ alert('Not implemented yet!'); } render() { const data = this.props.queries.map((query) => { const q = Object.assign({}, query); if (q.endDttm) { q.duration = fDuration(q.startDttm, q.endDttm); } q.userId = ( <button className="btn btn-link btn-xs" onClick={this.props.onUserClicked.bind(this, q.userId)} > {q.userId} </button> ); q.dbId = ( <button className="btn btn-link btn-xs" onClick={this.props.onDbClicked.bind(this, q.dbId)} > {q.dbId} </button> ); q.started = moment(q.startDttm).format('HH:mm:ss'); const source = (q.ctas) ? q.executedSql : q.sql; q.sql = ( <SqlShrink sql={source} maxWidth={100} /> ); q.output = q.tempTable; q.progress = ( <ProgressBar style={{ width: '75px' }} striped now={q.progress} label={`${q.progress}%`} /> ); let errorTooltip; if (q.errorMessage) { errorTooltip = ( <Link tooltip={q.errorMessage}> <i className="fa fa-exclamation-circle text-danger" /> </Link> ); } q.state = ( <div> <span className={'m-r-3 label label-' + STATE_BSSTYLE_MAP[q.state]}> {q.state} </span> {errorTooltip} </div> ); q.actions = ( <div style={{ width: '75px' }}> <Link className="fa fa-line-chart m-r-3" tooltip="Visualize the data out of this query" onClick={this.showVisualizeModal.bind(this, query)} /> <Link className="fa fa-pencil m-r-3" onClick={this.restoreSql.bind(this, query)} tooltip="Overwrite text in editor with a query on this table" placement="top" /> <Link className="fa fa-plus-circle m-r-3" onClick={self.notImplemented} tooltip="Run query in a new tab" placement="top" /> <Link className="fa fa-trash m-r-3" tooltip="Remove query from log" onClick={this.props.actions.removeQuery.bind(this, query)} /> </div> ); q.querylink = ( <div style={{ width: '100px' }}> <a href={this.getQueryLink(q.dbId, source)} className="btn btn-primary btn-xs" > <i className="fa fa-external-link" />Open in SQL Editor </a> </div> ); return q; }).reverse(); return ( <div> <VisualizeModal show={this.state.showVisualizeModal} query={this.state.activeQuery} onHide={this.hideVisualizeModal.bind(this)} /> <Table columns={this.props.columns} className="table table-condensed" data={data} /> </div> ); } } QueryTable.propTypes = { columns: React.PropTypes.array, actions: React.PropTypes.object, queries: React.PropTypes.array, onUserClicked: React.PropTypes.func, onDbClicked: React.PropTypes.func, }; QueryTable.defaultProps = { columns: ['started', 'duration', 'rows'], queries: [], onUserClicked: () => {}, onDbClicked: () => {}, }; function mapStateToProps() { return {}; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(Actions, dispatch), }; } export default connect(mapStateToProps, mapDispatchToProps)(QueryTable);
caravel/assets/javascripts/SqlLab/components/QueryTable.jsx
1
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.00020814848539885134, 0.0001729453942971304, 0.0001626146404305473, 0.00017110166663769633, 0.000009384431905345991 ]
{ "id": 6, "code_window": [ " DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=True)\n", "\n", " database = relationship(\n", " 'Database', foreign_keys=[database_id], backref='queries')\n", "\n", " __table_args__ = (\n", " sqla.Index('ti_user_id_changed_on', user_id, changed_on),\n", " )\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " user = relationship('User', backref='queries', foreign_keys=[user_id])\n" ], "file_path": "caravel/models.py", "type": "add", "edit_start_line_idx": 1000 }
export const RESET_STATE = 'RESET_STATE'; export const ADD_QUERY_EDITOR = 'ADD_QUERY_EDITOR'; export const REMOVE_QUERY_EDITOR = 'REMOVE_QUERY_EDITOR'; export const ADD_TABLE = 'ADD_TABLE'; export const REMOVE_TABLE = 'REMOVE_TABLE'; export const START_QUERY = 'START_QUERY'; export const STOP_QUERY = 'STOP_QUERY'; export const END_QUERY = 'END_QUERY'; export const REMOVE_QUERY = 'REMOVE_QUERY'; export const EXPAND_TABLE = 'EXPAND_TABLE'; export const COLLAPSE_TABLE = 'COLLAPSE_TABLE'; export const QUERY_SUCCESS = 'QUERY_SUCCESS'; export const QUERY_FAILED = 'QUERY_FAILED'; export const QUERY_EDITOR_SETDB = 'QUERY_EDITOR_SETDB'; export const QUERY_EDITOR_SET_SCHEMA = 'QUERY_EDITOR_SET_SCHEMA'; export const QUERY_EDITOR_SET_TITLE = 'QUERY_EDITOR_SET_TITLE'; export const QUERY_EDITOR_SET_AUTORUN = 'QUERY_EDITOR_SET_AUTORUN'; export const QUERY_EDITOR_SET_SQL = 'QUERY_EDITOR_SET_SQL'; export const SET_DATABASES = 'SET_DATABASES'; export const ADD_WORKSPACE_QUERY = 'ADD_WORKSPACE_QUERY'; export const REMOVE_WORKSPACE_QUERY = 'REMOVE_WORKSPACE_QUERY'; export const SET_ACTIVE_QUERY_EDITOR = 'SET_ACTIVE_QUERY_EDITOR'; export const ADD_ALERT = 'ADD_ALERT'; export const REMOVE_ALERT = 'REMOVE_ALERT'; export const REFRESH_QUERIES = 'REFRESH_QUERIES'; export const SET_NETWORK_STATUS = 'SET_NETWORK_STATUS'; export function resetState() { return { type: RESET_STATE }; } export function setDatabases(databases) { return { type: SET_DATABASES, databases }; } export function addQueryEditor(queryEditor) { return { type: ADD_QUERY_EDITOR, queryEditor }; } export function setNetworkStatus(networkOn) { return { type: SET_NETWORK_STATUS, networkOn }; } export function addAlert(alert) { return { type: ADD_ALERT, alert }; } export function removeAlert(alert) { return { type: REMOVE_ALERT, alert }; } export function setActiveQueryEditor(queryEditor) { return { type: SET_ACTIVE_QUERY_EDITOR, queryEditor }; } export function removeQueryEditor(queryEditor) { return { type: REMOVE_QUERY_EDITOR, queryEditor }; } export function removeQuery(query) { return { type: REMOVE_QUERY, query }; } export function queryEditorSetDb(queryEditor, dbId) { return { type: QUERY_EDITOR_SETDB, queryEditor, dbId }; } export function queryEditorSetSchema(queryEditor, schema) { return { type: QUERY_EDITOR_SET_SCHEMA, queryEditor, schema }; } export function queryEditorSetAutorun(queryEditor, autorun) { return { type: QUERY_EDITOR_SET_AUTORUN, queryEditor, autorun }; } export function queryEditorSetTitle(queryEditor, title) { return { type: QUERY_EDITOR_SET_TITLE, queryEditor, title }; } export function queryEditorSetSql(queryEditor, sql) { return { type: QUERY_EDITOR_SET_SQL, queryEditor, sql }; } export function addTable(table) { return { type: ADD_TABLE, table }; } export function expandTable(table) { return { type: EXPAND_TABLE, table }; } export function collapseTable(table) { return { type: COLLAPSE_TABLE, table }; } export function removeTable(table) { return { type: REMOVE_TABLE, table }; } export function startQuery(query) { return { type: START_QUERY, query }; } export function stopQuery(query) { return { type: STOP_QUERY, query }; } export function querySuccess(query, results) { return { type: QUERY_SUCCESS, query, results }; } export function queryFailed(query, msg) { return { type: QUERY_FAILED, query, msg }; } export function addWorkspaceQuery(query) { return { type: ADD_WORKSPACE_QUERY, query }; } export function removeWorkspaceQuery(query) { return { type: REMOVE_WORKSPACE_QUERY, query }; } export function refreshQueries(alteredQueries) { return { type: REFRESH_QUERIES, alteredQueries }; }
caravel/assets/javascripts/SqlLab/actions.js
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.0003887368366122246, 0.0001998167426791042, 0.00016662577399984002, 0.00017123158613685519, 0.00006085098721086979 ]
{ "id": 6, "code_window": [ " DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=True)\n", "\n", " database = relationship(\n", " 'Database', foreign_keys=[database_id], backref='queries')\n", "\n", " __table_args__ = (\n", " sqla.Index('ti_user_id_changed_on', user_id, changed_on),\n", " )\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " user = relationship('User', backref='queries', foreign_keys=[user_id])\n" ], "file_path": "caravel/models.py", "type": "add", "edit_start_line_idx": 1000 }
[ignore: caravel/assets/node_modules/**] [python: caravel/**.py] [jinja2: caravel/**/templates/**.html] encoding = utf-8
babel/babel.cfg
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.000177893482032232, 0.000177893482032232, 0.000177893482032232, 0.000177893482032232, 0 ]
{ "id": 6, "code_window": [ " DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=True)\n", "\n", " database = relationship(\n", " 'Database', foreign_keys=[database_id], backref='queries')\n", "\n", " __table_args__ = (\n", " sqla.Index('ti_user_id_changed_on', user_id, changed_on),\n", " )\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " user = relationship('User', backref='queries', foreign_keys=[user_id])\n" ], "file_path": "caravel/models.py", "type": "add", "edit_start_line_idx": 1000 }
.directed_force path.link { fill: none; stroke: #000; stroke-width: 1.5px; } .directed_force circle { fill: #ccc; stroke: #000; stroke-width: 1.5px; stroke-opacity: 1; opacity: 0.75; } .directed_force text { fill: #000; font: 10px sans-serif; pointer-events: none; }
caravel/assets/visualizations/directed_force.css
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.0001801628095563501, 0.00017864967230707407, 0.00017713654960971326, 0.00017864967230707407, 0.0000015131299733184278 ]
{ "id": 7, "code_window": [ " 'changedOn': self.changed_on,\n", " 'changed_on': self.changed_on.isoformat(),\n", " 'dbId': self.database_id,\n", " 'endDttm': self.end_time,\n", " 'errorMessage': self.error_message,\n", " 'executedSql': self.executed_sql,\n", " 'id': self.client_id,\n", " 'limit': self.limit,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'db': self.database.database_name,\n" ], "file_path": "caravel/models.py", "type": "add", "edit_start_line_idx": 1014 }
import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as Actions from '../actions'; import moment from 'moment'; import { Table } from 'reactable'; import { ProgressBar } from 'react-bootstrap'; import Link from './Link'; import VisualizeModal from './VisualizeModal'; import SqlShrink from './SqlShrink'; import { STATE_BSSTYLE_MAP } from '../common'; import { fDuration } from '../../modules/dates'; import { getLink } from '../../../utils/common'; class QueryTable extends React.Component { constructor(props) { super(props); const uri = window.location.toString(); const cleanUri = uri.substring(0, uri.indexOf('#')); this.state = { cleanUri, showVisualizeModal: false, activeQuery: null, }; } getQueryLink(dbId, sql) { const params = ['dbid=' + dbId, 'sql=' + sql, 'title=Untitled Query']; return getLink(this.state.cleanUri, params); } hideVisualizeModal() { this.setState({ showVisualizeModal: false }); } showVisualizeModal(query) { this.setState({ showVisualizeModal: true }); this.setState({ activeQuery: query }); } restoreSql(query) { this.props.actions.queryEditorSetSql({ id: query.sqlEditorId }, query.sql); } notImplemented() { /* eslint no-alert: 0 */ alert('Not implemented yet!'); } render() { const data = this.props.queries.map((query) => { const q = Object.assign({}, query); if (q.endDttm) { q.duration = fDuration(q.startDttm, q.endDttm); } q.userId = ( <button className="btn btn-link btn-xs" onClick={this.props.onUserClicked.bind(this, q.userId)} > {q.userId} </button> ); q.dbId = ( <button className="btn btn-link btn-xs" onClick={this.props.onDbClicked.bind(this, q.dbId)} > {q.dbId} </button> ); q.started = moment(q.startDttm).format('HH:mm:ss'); const source = (q.ctas) ? q.executedSql : q.sql; q.sql = ( <SqlShrink sql={source} maxWidth={100} /> ); q.output = q.tempTable; q.progress = ( <ProgressBar style={{ width: '75px' }} striped now={q.progress} label={`${q.progress}%`} /> ); let errorTooltip; if (q.errorMessage) { errorTooltip = ( <Link tooltip={q.errorMessage}> <i className="fa fa-exclamation-circle text-danger" /> </Link> ); } q.state = ( <div> <span className={'m-r-3 label label-' + STATE_BSSTYLE_MAP[q.state]}> {q.state} </span> {errorTooltip} </div> ); q.actions = ( <div style={{ width: '75px' }}> <Link className="fa fa-line-chart m-r-3" tooltip="Visualize the data out of this query" onClick={this.showVisualizeModal.bind(this, query)} /> <Link className="fa fa-pencil m-r-3" onClick={this.restoreSql.bind(this, query)} tooltip="Overwrite text in editor with a query on this table" placement="top" /> <Link className="fa fa-plus-circle m-r-3" onClick={self.notImplemented} tooltip="Run query in a new tab" placement="top" /> <Link className="fa fa-trash m-r-3" tooltip="Remove query from log" onClick={this.props.actions.removeQuery.bind(this, query)} /> </div> ); q.querylink = ( <div style={{ width: '100px' }}> <a href={this.getQueryLink(q.dbId, source)} className="btn btn-primary btn-xs" > <i className="fa fa-external-link" />Open in SQL Editor </a> </div> ); return q; }).reverse(); return ( <div> <VisualizeModal show={this.state.showVisualizeModal} query={this.state.activeQuery} onHide={this.hideVisualizeModal.bind(this)} /> <Table columns={this.props.columns} className="table table-condensed" data={data} /> </div> ); } } QueryTable.propTypes = { columns: React.PropTypes.array, actions: React.PropTypes.object, queries: React.PropTypes.array, onUserClicked: React.PropTypes.func, onDbClicked: React.PropTypes.func, }; QueryTable.defaultProps = { columns: ['started', 'duration', 'rows'], queries: [], onUserClicked: () => {}, onDbClicked: () => {}, }; function mapStateToProps() { return {}; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(Actions, dispatch), }; } export default connect(mapStateToProps, mapDispatchToProps)(QueryTable);
caravel/assets/javascripts/SqlLab/components/QueryTable.jsx
1
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.00037165533285588026, 0.00018181478662882, 0.00016396235150750726, 0.00017078967357520014, 0.000046190398279577494 ]
{ "id": 7, "code_window": [ " 'changedOn': self.changed_on,\n", " 'changed_on': self.changed_on.isoformat(),\n", " 'dbId': self.database_id,\n", " 'endDttm': self.end_time,\n", " 'errorMessage': self.error_message,\n", " 'executedSql': self.executed_sql,\n", " 'id': self.client_id,\n", " 'limit': self.limit,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'db': self.database.database_name,\n" ], "file_path": "caravel/models.py", "type": "add", "edit_start_line_idx": 1014 }
// Index .less, any imports here will be included in the final css build @import "~bootstrap/less/bootstrap.less"; @import "./cosmo/variables.less"; @import "./cosmo/bootswatch.less";
caravel/assets/stylesheets/less/index.less
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.00017282614135183394, 0.00017282614135183394, 0.00017282614135183394, 0.00017282614135183394, 0 ]
{ "id": 7, "code_window": [ " 'changedOn': self.changed_on,\n", " 'changed_on': self.changed_on.isoformat(),\n", " 'dbId': self.database_id,\n", " 'endDttm': self.end_time,\n", " 'errorMessage': self.error_message,\n", " 'executedSql': self.executed_sql,\n", " 'id': self.client_id,\n", " 'limit': self.limit,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'db': self.database.database_name,\n" ], "file_path": "caravel/models.py", "type": "add", "edit_start_line_idx": 1014 }
import React from 'react'; // import { Tab, Row, Col, Nav, NavItem } from 'react-bootstrap'; import Select from 'react-select'; import { Button } from 'react-bootstrap'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as actions from '../actions/exploreActions'; import shortid from 'shortid'; const propTypes = { actions: React.PropTypes.object, filterColumnOpts: React.PropTypes.array, filters: React.PropTypes.array, }; const defaultProps = { filterColumnOpts: [], filters: [], }; class Filters extends React.Component { constructor(props) { super(props); this.state = { opOpts: ['in', 'not in'], }; } changeField(filter, fieldOpt) { const val = (fieldOpt) ? fieldOpt.value : null; this.props.actions.changeFilterField(filter, val); } changeOp(filter, opOpt) { const val = (opOpt) ? opOpt.value : null; this.props.actions.changeFilterOp(filter, val); } changeValue(filter, value) { this.props.actions.changeFilterValue(filter, value); } removeFilter(filter) { this.props.actions.removeFilter(filter); } addFilter() { this.props.actions.addFilter({ id: shortid.generate(), field: null, op: null, value: null, }); } render() { const filters = this.props.filters.map((filter) => ( <div> <Select className="row" multi={false} name="select-column" placeholder="Select column" options={this.props.filterColumnOpts} value={filter.field} autosize={false} onChange={this.changeField.bind(this, filter)} /> <div className="row"> <Select className="col-sm-3" multi={false} name="select-op" placeholder="Select operator" options={this.state.opOpts.map((o) => ({ value: o, label: o }))} value={filter.op} autosize={false} onChange={this.changeOp.bind(this, filter)} /> <div className="col-sm-6"> <input type="text" onChange={this.changeValue.bind(this, filter)} className="form-control input-sm" placeholder="Filter value" /> </div> <div className="col-sm-3"> <Button bsStyle="primary" onClick={this.removeFilter.bind(this, filter)} > <i className="fa fa-minus" /> </Button> </div> </div> </div> ) ); return ( <div className="panel space-1"> <div className="panel-header">Filters</div> <div className="panel-body"> {filters} <Button bsStyle="primary" onClick={this.addFilter.bind(this)} > <i className="fa fa-plus" />Add Filter </Button> </div> </div> ); } } Filters.propTypes = propTypes; Filters.defaultProps = defaultProps; function mapStateToProps(state) { return { filterColumnOpts: state.filterColumnOpts, filters: state.filters, }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(actions, dispatch), }; } export default connect(mapStateToProps, mapDispatchToProps)(Filters);
caravel/assets/javascripts/explorev2/components/Filters.jsx
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.0001763216423569247, 0.00017168039630632848, 0.00016695354133844376, 0.000172329499037005, 0.0000026128652734769275 ]
{ "id": 7, "code_window": [ " 'changedOn': self.changed_on,\n", " 'changed_on': self.changed_on.isoformat(),\n", " 'dbId': self.database_id,\n", " 'endDttm': self.end_time,\n", " 'errorMessage': self.error_message,\n", " 'executedSql': self.executed_sql,\n", " 'id': self.client_id,\n", " 'limit': self.limit,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " 'db': self.database.database_name,\n" ], "file_path": "caravel/models.py", "type": "add", "edit_start_line_idx": 1014 }
.sankey .node rect { cursor: move; fill-opacity: .9; shape-rendering: crispEdges; } .sankey .node text { pointer-events: none; text-shadow: 0 1px 0 #fff; } .sankey .link { fill: none; stroke: #000; stroke-opacity: .2; } .sankey .link:hover { stroke-opacity: .5; } .sankey-tooltip { position: absolute; width: auto; background: #ddd; padding: 10px; font-size: 12px; font-weight: 200; color: #333; border: 1px solid #fff; text-align: center; pointer-events: none; }
caravel/assets/visualizations/sankey.css
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.0001750101218931377, 0.00017286800721194595, 0.00017116712115239352, 0.0001726474001770839, 0.0000014745008911631885 ]
{ "id": 8, "code_window": [ " 'startDttm': self.start_time,\n", " 'state': self.status.lower(),\n", " 'tab': self.tab_name,\n", " 'tempTable': self.tmp_table_name,\n", " 'userId': self.user_id,\n", " 'limit_reached': self.limit_reached,\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " 'user': self.user.username,\n" ], "file_path": "caravel/models.py", "type": "add", "edit_start_line_idx": 1031 }
import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as Actions from '../actions'; import moment from 'moment'; import { Table } from 'reactable'; import { ProgressBar } from 'react-bootstrap'; import Link from './Link'; import VisualizeModal from './VisualizeModal'; import SqlShrink from './SqlShrink'; import { STATE_BSSTYLE_MAP } from '../common'; import { fDuration } from '../../modules/dates'; import { getLink } from '../../../utils/common'; class QueryTable extends React.Component { constructor(props) { super(props); const uri = window.location.toString(); const cleanUri = uri.substring(0, uri.indexOf('#')); this.state = { cleanUri, showVisualizeModal: false, activeQuery: null, }; } getQueryLink(dbId, sql) { const params = ['dbid=' + dbId, 'sql=' + sql, 'title=Untitled Query']; return getLink(this.state.cleanUri, params); } hideVisualizeModal() { this.setState({ showVisualizeModal: false }); } showVisualizeModal(query) { this.setState({ showVisualizeModal: true }); this.setState({ activeQuery: query }); } restoreSql(query) { this.props.actions.queryEditorSetSql({ id: query.sqlEditorId }, query.sql); } notImplemented() { /* eslint no-alert: 0 */ alert('Not implemented yet!'); } render() { const data = this.props.queries.map((query) => { const q = Object.assign({}, query); if (q.endDttm) { q.duration = fDuration(q.startDttm, q.endDttm); } q.userId = ( <button className="btn btn-link btn-xs" onClick={this.props.onUserClicked.bind(this, q.userId)} > {q.userId} </button> ); q.dbId = ( <button className="btn btn-link btn-xs" onClick={this.props.onDbClicked.bind(this, q.dbId)} > {q.dbId} </button> ); q.started = moment(q.startDttm).format('HH:mm:ss'); const source = (q.ctas) ? q.executedSql : q.sql; q.sql = ( <SqlShrink sql={source} maxWidth={100} /> ); q.output = q.tempTable; q.progress = ( <ProgressBar style={{ width: '75px' }} striped now={q.progress} label={`${q.progress}%`} /> ); let errorTooltip; if (q.errorMessage) { errorTooltip = ( <Link tooltip={q.errorMessage}> <i className="fa fa-exclamation-circle text-danger" /> </Link> ); } q.state = ( <div> <span className={'m-r-3 label label-' + STATE_BSSTYLE_MAP[q.state]}> {q.state} </span> {errorTooltip} </div> ); q.actions = ( <div style={{ width: '75px' }}> <Link className="fa fa-line-chart m-r-3" tooltip="Visualize the data out of this query" onClick={this.showVisualizeModal.bind(this, query)} /> <Link className="fa fa-pencil m-r-3" onClick={this.restoreSql.bind(this, query)} tooltip="Overwrite text in editor with a query on this table" placement="top" /> <Link className="fa fa-plus-circle m-r-3" onClick={self.notImplemented} tooltip="Run query in a new tab" placement="top" /> <Link className="fa fa-trash m-r-3" tooltip="Remove query from log" onClick={this.props.actions.removeQuery.bind(this, query)} /> </div> ); q.querylink = ( <div style={{ width: '100px' }}> <a href={this.getQueryLink(q.dbId, source)} className="btn btn-primary btn-xs" > <i className="fa fa-external-link" />Open in SQL Editor </a> </div> ); return q; }).reverse(); return ( <div> <VisualizeModal show={this.state.showVisualizeModal} query={this.state.activeQuery} onHide={this.hideVisualizeModal.bind(this)} /> <Table columns={this.props.columns} className="table table-condensed" data={data} /> </div> ); } } QueryTable.propTypes = { columns: React.PropTypes.array, actions: React.PropTypes.object, queries: React.PropTypes.array, onUserClicked: React.PropTypes.func, onDbClicked: React.PropTypes.func, }; QueryTable.defaultProps = { columns: ['started', 'duration', 'rows'], queries: [], onUserClicked: () => {}, onDbClicked: () => {}, }; function mapStateToProps() { return {}; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(Actions, dispatch), }; } export default connect(mapStateToProps, mapDispatchToProps)(QueryTable);
caravel/assets/javascripts/SqlLab/components/QueryTable.jsx
1
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.00030315600452013314, 0.00017776306776795536, 0.00016426797083113343, 0.00016983045497909188, 0.00003065046985284425 ]
{ "id": 8, "code_window": [ " 'startDttm': self.start_time,\n", " 'state': self.status.lower(),\n", " 'tab': self.tab_name,\n", " 'tempTable': self.tmp_table_name,\n", " 'userId': self.user_id,\n", " 'limit_reached': self.limit_reached,\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " 'user': self.user.username,\n" ], "file_path": "caravel/models.py", "type": "add", "edit_start_line_idx": 1031 }
{% extends "caravel/basic.html" %} {% block title %}{{ _("No Access!") }}{% endblock %} {% block body %} <div class="container"> {% include "caravel/flash_wrapper.html" %} <h4> {{ _("You do not have permissions to access the datasource(s): %(name)s.", name=datasource_names) }} </h4> <div> <button onclick="window.location += '&action=go';"> {{ _("Request Permissions") }} </button> <button onclick="window.location.href = '/slicemodelview/list/';"> {{ _("Cancel") }} </button> </div> </div> {% endblock %}
caravel/templates/caravel/request_access.html
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.00017237536667380482, 0.00017169305647257715, 0.00017069559544324875, 0.00017200823640450835, 7.210672947621788e-7 ]
{ "id": 8, "code_window": [ " 'startDttm': self.start_time,\n", " 'state': self.status.lower(),\n", " 'tab': self.tab_name,\n", " 'tempTable': self.tmp_table_name,\n", " 'userId': self.user_id,\n", " 'limit_reached': self.limit_reached,\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " 'user': self.user.username,\n" ], "file_path": "caravel/models.py", "type": "add", "edit_start_line_idx": 1031 }
"""is_featured Revision ID: 12d55656cbca Revises: 55179c7f25c7 Create Date: 2015-12-14 13:37:17.374852 """ # revision identifiers, used by Alembic. revision = '12d55656cbca' down_revision = '55179c7f25c7' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('tables', sa.Column('is_featured', sa.Boolean(), nullable=True)) def downgrade(): op.drop_column('tables', 'is_featured')
caravel/migrations/versions/12d55656cbca_is_featured.py
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.00017150709754787385, 0.00016854323621373624, 0.00016458294703625143, 0.00016953969316091388, 0.000002913262278525508 ]
{ "id": 8, "code_window": [ " 'startDttm': self.start_time,\n", " 'state': self.status.lower(),\n", " 'tab': self.tab_name,\n", " 'tempTable': self.tmp_table_name,\n", " 'userId': self.user_id,\n", " 'limit_reached': self.limit_reached,\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " 'user': self.user.username,\n" ], "file_path": "caravel/models.py", "type": "add", "edit_start_line_idx": 1031 }
<div id="alert-container"> {% include 'appbuilder/flash.html' %} </div>
caravel/templates/caravel/flash_wrapper.html
0
https://github.com/apache/superset/commit/5c5b393f2fd7be5a4496c0ea0a0808f720fdc904
[ 0.00017097462841775268, 0.00017097462841775268, 0.00017097462841775268, 0.00017097462841775268, 0 ]
{ "id": 0, "code_window": [ "\n", "_Note: Gaps between patch versions are faulty/broken releases._\n", "\n", "See [CHANGELOG - 6to5](CHANGELOG-6to5.md) for the pre-4.0.0 version changelog.\n", "\n", "## 5.5.0\n", "\n", " * **Bug Fix**\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "## 5.5.1\n", "\n", " * **Bug Fix**\n", " * Remove `ClassProperty` nodes always in the `Flow` transformer. This is fine now since.\n", "\n" ], "file_path": "CHANGELOG.md", "type": "add", "edit_start_line_idx": 15 }
# Changelog > **Tags:** > - [New Feature] > - [Bug Fix] > - [Spec Compliancy] > - [Breaking Change] > - [Documentation] > - [Internal] > - [Polish] _Note: Gaps between patch versions are faulty/broken releases._ See [CHANGELOG - 6to5](CHANGELOG-6to5.md) for the pre-4.0.0 version changelog. ## 5.5.0 * **Bug Fix** * Allow pushing declarations to `SwitchStatement`s. * Fix `minification.removeDebugger` to remove `DebuggerStatement`s rather than `ExpressionStatement`s with an identifier of `debugger`. * Check LHS in `ForInStatement` and `ForOfStatement` for constant violations. * Register function `id` as a reference when naming methods to avoid collisions. * Support key literals when checking for the existence of `displayName` property when attempting to add it for `React.createClass`. * Remove `ExportDefaultSpecifier` check from `t.isDefaultSpecifier`. * Don't consider `JSXIdentifier` HTML tag identifiers to be references. * **Polish** * Update `minification.deadCodeElimination` transformer to remove all statements after completion statements. * Update `minification.deadCodeElimination` transformer to not inline single used bindings that exist in different scopes. * When performing Istanbul interop in `babel/register`, add the auxiliary comment `"istanbul ignore text"` to get more accurate coverage. * Add `--nolazy` argument to `babel-node`. * Add support for `cluster` forking. * Perform scope tracking in a single pass instead of multiple. * Smarten up type inferrence and resolution to support the whole array of language constructs. * Optimise module metadata retrieval into a single pass. * Ignore trailing commas when inferring newlines. * Rename `minification.inlineExpressions` transformer to `minification.constantFolding`. * Check path relative to entry file when checking to see if we're inside `node_modules` when using `babel/register`. * Upgrade `regenerator`. ## 5.4.7 * **Bug Fix** * Don't consider `JSXAttribute` `names` to be valid `ReferencedIdentifier`s. ## 5.4.6 * **Bug Fix** * Fix `spec.functionName` transformer incorrectly attempting to rename a binding that doesn't exist as it's a global. * **Internal** * Deprecate custom module formatters. ## 5.4.5 * **Bug Fix** * Add `JSXIdentifier` as a valid `ReferencedIdentifier` visitor virtual type. * Ignore `CallExpression` `_prettyCall` when the `retainLines` option is enabled. * Inherit comments to new declaration node when exploding module declarations. * Fix `es6.tailCall` transformer failing on calls that exceed the max parameters of the function. ## 5.4.4 * **Bug Fix** * Fix bug where replacing variable declarations in the head of a `for` loop would turn them into `ExpressionStatement`s. * Fix renaming of assignment expressions that were non-identifiers ie. patterns. * Force space before `class` `id` to avoid breaking named classes when using `compact` mode. * Add assignment pattern explosion to avoid initial duplicate nodes. * Ignore this and arguments when performing TCO on shadowed functions. * **Polish** * Rename `sourceMapName` option to `sourceMapTarget`. Thanks [@getify](https://github.com/getify)! * Better detection of completion records, ignore those in `Function`s. * Clarified descriptions of the options that are enabled by default. * Resolve `\`babel-plugin-${name}\`` plugin names **before** just checking the `name`. Thanks [@jquense](https://github.com/jquense)! * Update AMD module formatter to add import default remapping. ## 5.4.3 * **Bug Fix** * Fix `module` being incorrectly rewritten when used as in an export declaration. * When performing single-reference inlining, ensure that the single reference isn't a child of the binding itself. * Fix a bug in `minification.deadCodeElimination` where a new binding instance was being created for local class bindings instead of just inheriting the parent one. * Fix bug with paren printing in `compact` and `retainLines` mode where a left paren was already printed before catching up. * **Internal** * Handle contexts for paths much better. This will ensure that the path node location info is in sync. ## 5.4.2 * **Polish** * `ignore` and `only` patterns are now **very** liberal. The pattern can now exist anywhere in the path. ## 5.4.1 * **Bug Fix** * Add missing `slash` dependency. Thanks [@browncolyn](https://github.com/browncolyn)! * **Polish** * Clean up `shouldIgnore` algorithm to work how you'd expect rather than being a hacky piece of shit. It now crawls the entire path, checking each section of it against the input ignore/only patterns. This means that the pattern `foo` will ignore the paths `foo/bar.js`, `bar/foo` etc. ## 5.4.0 * **New Feature** * Added [function bind syntax](https://github.com/zenparsing/es-function-bind) behind stage 0. Thanks [@RReverser](https://github.com/rreverser)! * Added `env` option. Especially handy when using the `.babelrc`. * **Bug Fix** * Fix files not properly being ignored when `babel.transform` ignores them when using `$ babel`. * Fix scope tracking registering loop head bindings to their `VariableDeclaration` instead of `VariableDeclarator`. * **Polish** * Normalise path separators for souce map paths when using `$ babel`. * Rework `PathHoister` to ignore global references and to not deopt on reassignments to referenced bindings, instead it tries to hoist to the highest scope. * Added missing exponential operator inlining. Thanks [@nkt](https://github.com/nkt)! * Optimise `regenerator` transformer. Thanks [@benjamn](https://github.com/benjamn)! ## 5.3.3 * **Bug Fix** * Fix `minification.deadCodeElimination` transformer incorrectly trying to inline import declarations. * Fix `minification.inlineExpression` transformer getting into an infinite loop. ## 5.3.2 * **Bug Fix** * Fix patterns not being considered when hoisting variables in the `es6.blockScoping` transformer. ## 5.3.1 * **Bug Fix** * Fix unique export specifiers not being cloned when exploding class and function exports, * **Polish** * Turn import remaps to sequence expressions to remove their context and improve performance. ## 5.3.0 **Speeeeeeed** ![gifs lol](https://31.media.tumblr.com/568205a0e37ae15eca510fa639589a59/tumblr_n8kw8kpcSb1sg6cg8o1_500.gif) * **Spec Compliancy** * Allow trailing param commas for methods when using the `es7.trailingCommas` transformer. * **Bug Fix** * Fix `es6.blockScoping` transformer not properly ignoring `break` in `SwitchCase`. * Fix lookahead context saving to avoid weird tokenizer state. * Explode duplicate identifiers in export/import specifiers and property shorthand to create unique objects. * Skip loose mode for class methods when they have decorators. * When removing nodes, share their comments with their siblings. * Properly hoist temp param declarations when doing TCO. * **Internal** * Add `--harmony_generators` flag to `$ babel-node`. * Internal AST traversals have been minimised **drastically**. Transformers have been grouped together which means entire tree traversals are much fewer. Visiting nodes is now also skipped if the traversal context can detect that the handler is a noop. This sames precious cycles as it avoids constructing traversal paths and creating a new traversal context. See issues [#1472](https://github.com/babel/babel/issues/1472) and [#1486](https://github.com/babel/babel/issues/1486) for related discussion. * **Polish** * Move many `utility` transformers to `minification`. ## 5.2.17 * **Bug Fix** * Fix auxiliary comments not properly being attached to function declaration helpers. * Add `Super` node type to `ast-types` patch. * Ignore parameter bindings when attempting to inline them in the `minification.deadCodeElimination` transformer. * Correct `extensions` arguments when using the Babel CLI. ## 5.2.16 * **Bug Fix** * Fix plugins being disabled when using the whitelist. * Fix correct function scope being passed to `nameMethod.property` when inferring the function name for class methods. * Fix incorrect extensions reference causing weird issues when using the Babel CLI. * Fix destructuring param reference replacements not inheriting from their original param. * **Spec Compliancy** * Fix order that method decorators are ran in. ## 5.2.15 * **Bug Fix** * Fix initializer descriptor add attempt if it doesn't exist. ## 5.2.14 * **Bug Fix** * Fix bug with initializer decorators where the descriptors weren't being defined if there was no `initializer` property. * **Internal** * Expose `retainLines` option to CLI. * Fix `retainLines` option not being taken into consideration when doing multiple variable declaration declarators generation. * Expose minified and unminified copies of dist scripts. ## 5.2.13 * **Bug Fix** * Fix `ExportDeclaration`s being incorrectly removed when using the `utility.deadCodeElimination` transformer. * Fix position of `utility` transformers. * **New Feature** * Add built-in `esquery` support. * **Internal** * Consolidate notion of "virtual types". ## 5.2.12 * **Polish** * Make UID generation based on module declarations **much** nicer. * **Internal** * Remove internal check for traversal path replacement of self. This is a pattern that **could** come up in the wild and it could lead to pretty nasty code and may lead to internal regressions as the test coverage isn't 100% :( Instead, just put it in the fast path. ## 5.2.11 * **Internal** * Rename `getModuleName` option to `getModuleId`, doh. ## 5.2.10 * **Bug Fix** * Fix numerous issues in `replaceWithSourceString`. Thanks [@pangratz](https://github.com/pangratz)! * **New Feature** * Add `getModuleName` option. Thanks [@jayphelps](https://github.com/jayphelps)! ## 5.2.9 * **Bug Fix** * Fix `_blockHoist` transformer incorrectly sorting nodes on shitty environments that aren't spec compliant in their key order. * Fix broken `parse` API method reference to an undeclared import. ## 5.2.7 * **Bug Fix** * Move `utility.deadCodeElimination` transformer up to avoid race conditions. * Fix shorthand property scope binding renaming. * **Polish** * Turn helper variable declarations into function declarations if possible. * **Internal** * Removed native inheritance support from classes. * Added `replaceWithSourceString` path API. * Split up `es3.propertyLiterals` and `es3.memberExpressionLiterals` transformers to `minfication.propertyLiterals` and `es3.memberExpressionLiterals`. ## 5.2.6 * **Internal** * Fix transformer aliases being accidently set as deprecated ones. * Expose `Pipeline` as `TransformerPipeline` instead. ## 5.2.5 * **Bug Fix** * Fix `parse` API not adding all the correct pipeline transformers. ## 5.2.4 * **Bug Fix** * Fix race condition with the Node API being loaded awkwardly and not being able to initialise itself when used in the browser. * **Internal** * Expose `transform.pipeline`. ## 5.2.3 * **Bug Fix** * Fix plugin containers being called with an undefined import. Thanks [@timbur](https://github.com/timbur)! * Allow Flow object separators to be commas. Thanks [@monsanto](https://github.com/monsanto)! * Add missing `Statement` and `Declaration` node aliases to flow types. ## 5.2.2 * **Internal** * Allow `util.arrayify` to take arbitrary types and coerce it into an array. ## 5.2.1 * **Bug Fix** * Fix regression in `node/register` that caused `node_modules` to not be ignored. ## 5.2.0 * **Bug Fix** * Fix plugin strings splitting arbitrarily on `:` which caused full paths on Windows to fail as they include `:` after the drive letter. * Call class property `initializer`s with their target instead of their descriptor. * Fix `ignore` and `only` not properly working on Windows path separators. Thanks [@stagas](https://github.com/stagas)! * Fix `resolveRc` running on files twice causing issues. Thanks [@lukescott](https://github.com/lukescott)! * Fix shorthand properties not correctly being target for `isReferenced` checks. Thanks [@monsanto](https://github.com/monsanto)! * **Polish** * Allow passing an array of globs to `babel/register` `only` and `ignore` options. Thanks [@Mark-Simulacrum](https://github.com/Mark-Simulacrum)! * When inferring function names that collide with upper bindings, instead of doing the wrapper, instead rename them. * Consider constant-like variable declaration functions to always refer to themselves so TOC can be performed. * Process globs manually when using `$ babel` as some shells such as Windows don't explode them. Thanks [@jden](https://github.com/jden)! * Add alternative way to execute plugins via a closure that's called with the current Babel instance. * **Internal** * Remove multiple internal transformers in favor of directly doing things when we need to. Previously, declarations such as `_ref` that we needed to create in specific scopes were done at the very end via the `_declarations` transformer. Now, they're done and added to the scope **right** when they're needed. This gets rid of the crappy `_declarations` property on scope nodes and fixes the crappy regenerator bug where it was creating a new `BlockStatement` so the declarations were being lost. * Rework transformer traversal optimisation. Turns out that calling a `check` function for **every single node** in the AST is ridiculously expensive. 300,000 nodes timesed by ~30 transformers meant that it took tens of seconds to perform while it's quicker to just do the unnecessary traversal. Seems obvious in hindsight. * **New Feature** * Add `jscript` transformer that turns named function expressions into function declarations to get around [JScript's horribly broken function expression semantics](https://kangax.github.io/nfe/#jscript-bugs). Thanks [@kondi](https://github.com/kondi)! * Add `@@hasInstance` support to objects when using the `es6.spec.symbols` transformer. * Add `retainLines` option that retains the line (but not the columns!) of the input code. ## 5.1.13 * **Polish** * Remove symbol check from `defineProperty` helper. ## 5.1.12 * **Bug Fix** * Fix `resolveModuleSource` not being ran on `ExportAllDeclaration`s. * Fix `.babelrc` being resolved multiple times when using the require hook. * Fix parse error on spread properties in assignment position. * Fix `externalHelpers` option being incorrectly listed as type `string`. * **Internal** * Upgrade `core-js` to `0.9.0`. * **Spec Compliancy** * Fix object decorators not using the `initializer` pattern. * Remove property initializer descriptor reflection. ## 5.1.11 * **Bug Fix** * Memoise and bind member expression decorators. * Move JSX children cleaning to opening element visitor. Fixes elements not being cleaned in certain scenarios. * Consider `SwitchStatement`s to be `Scopable`. * Fix `bluebirdCoroutines` calling `interopRequireWildcard` before it's defined. * Add space to `do...while` code generation. * Validate `super` use before `this` on `super` exit rather than entrance. * **Polish** * Add Babel name to logger. ## 5.1.10 * **Bug Fix** * Remove `makePredicate` from acorn in favor of an `indexOf`. * Remove statements to expression explosion when inserting a block statement. * **Internal** * Remove runtime compatibility check. ## 5.1.9 * **Bug Fix** * Fix class property initializers with `undefined` values not being correctly writable. * Fix self inferring generators incorrectly causing a stack error. * Fix default export specifiers not triggering AMD `module` argument inclusion. * Fix assignments not having their module references properly remapped. * **Internal** * Upgrade to latest `acorn`. * **Polish** * Make invalid LHS pattern error messages nicer. ## 5.1.8 * **Bug Fix** * Only make parenthesized object pattern LHS illegal. ## 5.1.7 * **Internal** * Add `parse` node API. ## 5.1.6 * **Bug Fix** * Fix `runtime` built-in catchall not properly checking for local variables. ## 5.1.5 * **Internal** * Bump `core-js` version. ## 5.1.4 * **Polish** * Add missing `Reflect` methods to runtime transformer. ## 5.1.3 * **Internal** * Switch entirely to vanilla regenerator. * Clean up and make the parsing of decorators stateless. * **Bug Fix** * Don't do TCO on generators and async functions. * Add missing `core-js` runtime definitions. ## 5.1.2 * **Bug Fix** * Add `getIterator` and `isIterable` to `babel-runtime` build script. ## 5.1.1 * **Bug Fix** * Add missing runtime symbol definitions. ## 5.1.0 * **Bug Fix** * Fix super reference when using decorators. * Don't do array unpack optimisation when member expressions are present. * Add missing descriptors for undecorated class properties. * Don't consider `arguments` and `eval` valid function names when doing function name inferrence. * Fix scope tracking of constants in loop heads. * Parse `AwaitExpression` as a unary instead of an assignment. * Fix regex evaluation when attempting static evaluation. * Don't emit tokens when doing a lookahead. * Add missing `test` declaration to `utility.deadCodeElimination` transformer. * **Internal** * Upgrade `regenerator` to the latest and use my branch with the hope of eventually switching to vanilla regenerator. * Add support for the replacement of for loop `init`s with statements. * Upgrade dependencies. * **Polish** * When adding the scope IIFE when using default parameters, don't shadow the function expression, just `apply` `this` and `arguments` if necessary. * Use path basename as non-default import fallback. * **New Feature** * Add [trailing function comma proposal](https://github.com/jeffmo/es-trailing-function-commas). Thanks [@AluisioASG](https://github.com/AluisioASG)! * Add support for object literal decorators. * Make core-js modular when using the `runtime` transformer. ## 5.0.12 * **Bug Fix** * Fix incorrect remapping of module references inside of a function id redirection container. ## 5.0.11 * **Bug Fix** * Fix new `for...of` loops not properly inheriting their original loop. * **Internal** * Disable scope instance cache. * **Polish** * Allow comments in `.babelrc` JSON. ## 5.0.9 * **Polish** * Use `moduleId` for UMD global name if available. * **Bug Fix** * Fix UMD global `module` variable shadowing the `amd`/`common` `module` variable. * Fix Flow param type annotation regression. * Fix function name collision `toString` wrapper. Thanks [@alawatthe](https://github.com/alawatthe)! ## 5.0.8 * **Bug Fix** * Fix falsy static class properties not being writable. * Fix block scoping collisions not properly detecting modules and function clashes. * Skip `this` before `super` for derived constructors on functions. ## 5.0.7 * **New Feature** * Add `--ignore` and `--only` support to the CLI. * **Bug Fix** * Remove `HOMEPATH` environment variable from home resolution in `babel/register` cache. * **Internal** * Disable WIP path resolution introducing infinite recursion in some code examples. * **Polish** * Add live binding to CommonJS default imports. ## 5.0.6 * **Bug Fix** * Fix mangling of import references that collide with properties on `Object.prototype`. * Fix duplicate declarations incorrectly being reported for `var`. ## 5.0.5 * **Internal** * Upgrade `core-js`. * **Bug Fix** * Fix arrays not being supported in `util.list`. ## 5.0.4 * **Polish** * Check for top level `breakConfig` in `resolveRc`. ## 5.0.3 * **Bug Fix** * Make relative location absolute before calling `resolveRc`. * **Internal** * Switch to global UID registry. * Add `breakConfig` option to prevent Babel from erroring when hitting that option. ## 5.0.1 * **Bug Fix** * Fix duplicate declaration regression. * Fix not being able to call non-writable methods. ## 5.0.0 * **New Feature** * Decorators based on [@wycat's](https://github.com/wycats) [stage 1 proposal](https://github.com/wycats/javascript-decorators). * Class property initializers based on [@jeffmo's](https://github.com/jeffmo) [stage 0 proposal](https://gist.github.com/jeffmo/054df782c05639da2adb). * Export extensions based on [@leebyron's](https://github.com/leebyron) [stage 1 proposal](https://github.com/leebyron/ecmascript-more-export-from). * UMD module formatter now supports globals. * Add `es3.runtime`, `optimisation.react.inlineElements` and `optimisation.react.constantElements` transformers. * Add stage option that replaces the experimental one. * Allow ES7 transformer to be enabled via `optional` instead of only via `stage`. * Infer string quotes to use in the code generator. * Consider `export { foo as default };` to be the same as `export default foo;`. * Add `nonStandard` option that can be set to `false` to remove parser support for JSX and Flow. * Add `jsxPragma` option. * Automatically generate CLI options based on internal API options. * Add support for `.babelrc` on absolute paths. * Plugin API! * **Internal** * Export `options` in browser API. * Rewritten parser. * Don't block hoist when runtime transformer is enabled in system module formatter. * Rewritten the internal traversal and node replacement API to use "paths" that abstracts out node relationships. * **Polish** * JSX output is now more inline with the official JSX transformer. * Hoist block scoping IIFE - this improves memory usage and performance. * Better IIFE detection - references are now checked to see if they're referencing the binding we're searching for. * Check for import reassignments in constants transformer. * Make method definitions with expression bodies illegal. * Save register cache on tick instead of `SIGINT`. * Enable strict mode on babel-node eval flag. * **Bug Fixes** * Add support for live bindings. This change also increases the reliablity of export specifier renaming. * Add support for super update and non equals assignment expressions. * Rename shadow constructor binding in classes. * Seed next iteration bindings with previous fresh bindings when reassinging loop block scoped variables. * Fix new expression spread referencing the wrong constructor. * Call `resolveModuleSource` on dynamic imports. * Added `param` to list of duplicate declaration kinds. * **Breaking Changes** * The Babel playground has been removed. * ES7 Abstract References have been removed. * Experimental option has been removed in favor of a stage option. * Rename `returnUsedHelpers` to `metadataUsedHelpers`. ## 4.7.16 * **Bug Fix** * Fix constructor spreading of typed arrays. * Fix break/continue/return aliasing of non-loops in block scoping transformer. ## 4.7.15 * **Bug Fix** * Fix constructor spreading of collections. ## 4.7.14 * **Bug Fix** * Fix constructor spreading of `Promise`. * **Internal** * Deprecate remaining playground transformers and abstract references. ## 4.7.13 * **Bug Fix** * Handle comments on use strict directives. * Fix assignment patterns with a left side pattern. * **Polish** * Special case `this` when doing expression memoisation. ## 4.7.12 * **Bug Fix** * Deprecate `playground.methodBinding`. ## 4.7.11 * **Bug Fix** * Fix unicode regexes stripping their unicode flag before being passed on two `regexpu`. ## 4.7.10 * **Internal** * Deprecate `playground.methodBinding` and `playground.objectGetterMemoization`. * **Bug Fix** * Fix `inputSourceMap` option. Thanks [@Rich-Harris](https://github.com/Rich-Harris)! ## 4.7.9 * **Polish** * Allow `inputSourceMap` to be set to `false` to skip the source map inference. * Infer computed literal property names. * **Bug Fix** * Fix nested labeled for-ofs. * Fix block scoping `break` colliding with the parent switch case. * **Internal** * Upgrade `acorn-babel`. ## 4.7.8 * **Bug Fix** * Fix computed classes not properly setting symbols. ## 4.7.7 * **Bug Fix** * Fix `types` API exposure. ## 4.7.6 * **Bug Fix** * Fix non-Identifier/Literal computed class methods. * **Polish** * Add a fallback if `stack` on an error is unconfigurable. * Hoist `esModule` module declarations to the top of the file to handle circular dependencies better. ## 4.7.5 * **Bug Fix** * Don't remap` break`s to call the iterator return. * **Polish** * Use a different helper for computed classes for much nicer output. Also fixes a bug in symbols being non-enumerable so they wouldn't be set on the class. ## 4.7.4 * **Bug Fix** * Rewrite named function expressions in optional async function transformers. * Hoist directives. * Remove `Number` from the list of valid `runtime` constructors. * **Internal** * `spec.typeofSymbol` transformer has been renamed to `es6.symbols`. ## 4.7.2 * **New Feature** * `"both"` option for `sourceMap`. * Add output types to external helpers. Thanks [@neVERberleRfellerER](https://github.com/neVERberleRfellerER)! * **Bug Fix** * Fix node duplication sometimes resulting in a recursion error. * Ignore `break`s within cases inside `for...of`. * **Polish** * Split up variable declarations and export declarations to allow easier transformation. ## 4.7.0 * **Bug Fix** * Add `alternate` to list of `STATEMENT_OR_BLOCK` keys. * Add support for module specifiers to `t.isReferenced`. * **New Feature** * Add `inputSourceMap` option. * **Polish** * Throw an error on different `babel` and `babel-runtime` versions. * Replicate module environment for `babel-node` eval. * Clean up classes output. * **Spec Compliancy** * Make it illegal to use a rest parameter on a setter. ## 4.6.6 * **Bug Fix** * Fix incorrect method call in `utility.deadCodeElimination` transformer. * Fix `es6.blockScopingTDZ` transformer duplicating binding nodes. ## 4.6.5 * **Internal** * `useStrict` transformer has been renamed to `strict`. ## 4.6.4 * **Bug Fix** * Fix `ForOfStatement` not proplery inheriting labels. * When in closure mode in block scoping transformer, properly check for variable shadowing. * **New Feature** * New `utility.inlineEnvironmentVariables` and `utility.inlineExpression` transformers. ## 4.6.3 * **Bug Fix** * Fix `arguments` being incorrectly aliased in arrow function rest parameter optimisation. * Make deoptimisation trigger safer. * **New Feature** * Flow types are now retained when blacklisting the `flow` transformer. ## 4.6.1 * **Bug Fix** * Fix generators in template directory being transformed. * Fix exposure of `util` for plugins. ## 4.6.0 * **New Feature** * Desugar sticky regexes to a new constructor expression so it can be handled by a polyfill. * **Spec Compliancy** * `for...of` now outputs in a lengthy `try...catch` this is to ensure spec compliancy in regards to iterator returns and abrupt completions. See [google/traceur-compiler#1773](https://github.com/google/traceur-compiler/issues/1773) and [babel/babel/#838](https://github.com/babel/babel/issues/838) for more information. * **Polish** * Rest parameters that are only refered to via number properties on member expressions are desugared into a direct `arguments` reference. Thanks [@neVERberleRfellerER](https://github.com/neVERberleRfellerER)! * `$ babel` no longer exits on syntax errors. * **Internal** * Upgrade `browserify`. * Upgrade `source-map`. * Publicly expose more internals. ## 4.5.5 * **Polish** * Delete old extensions when overriding them in `babel/register`. ## 4.5.3 * **Bug Fix** * Fix whitelisting logic for helper build script. ## 4.5.2 * **New Feature** * `returnUsedHelpers` option and add whitelist to `buildHelpers`. * **Bug Fix** * Fix function arity on self referencing inferred named functions. * **Internal** * Bump `acorn-babel`. * Start converting source to ES6... ## 4.5.1 **Babel now compiles itself!** ![holy shit](http://gifsec.com/wp-content/uploads/GIF/2014/03/OMG-GIF_2.gif) ## 4.5.0 * **New Feature** * Add `.babelrc` support. * **Bug Fix** * Move use strict directives to the module formatter bodies. * **Internal** * Make default `bin/babel` behaviour to ignore non-compilable files and add a `--copy-files` flag to revert to the old behaviour. ## 4.4.6 * **Bug Fix** * Fix extending a class expression with no methods/only constructor. Thanks [@neVERberleRfellerER](https://github.com/neVERberleRfellerER)! * Allow `MemberExpression` as a valid `left` of `ForOfStatement`. * **Polish** * Throw an error when people try and transpile code with the `@jsx React.DOM` pragma as it conflicts with the custom jsx constructo method detection. * Crawl all comments for `@jsx` pragma. * **Internal** * Upgrade `chalk`. * Upgrade `core-js`. ## 4.4.5 * **Internal** * Remove function self reference optimisation. ## 4.4.4 * **Bug Fix** * Handle inferred function ids to be reassigned and deopt to a slower but working equivalent. * Don't unpack array patterns that have more elements than their right hand array expression. * **Polish** * Improve syntax highlighting in the code frame. Thanks [@lydell](https://github.com/lydell)! * **Internal** * Upgrade `acorn-babel`. ## 4.4.3 * **Bug Fix** * Fix `for...of` iterator break returns being duplicated. * Only call `return` on the iterator if it exists. * **Internal** * Rename `selfContained` transformer to `runtime`. ## 4.4.2 * **New Feature** * Add `moduleId` option for specifying a custom module id. ## 4.4.0 * **New Feature** * `/*** @jsx NAMESPACE **/` comments are now honored by the `react` transformer. * `getModuleName` option. * Infer function expression names. Thanks [@RReverser](https://github.com/RReverser)! * **Bug Fix** * Add proper control flow for tail recursion optimisation. * **Internal** * Remove useless `format` options and move the `format.compact` option to `format`. * **Polish** * Newline handling of the code generator has been heavily improved. * Code generator now deopts whitespace if the input size is >100KB. ## 4.3.0 * **Breaking Change** * Remove `commonStandard` module formatter and make it the default behaviour of all the strict module formatters. ## 4.2.1 * **Polish** * Add auxiliary comment to let scoping closure flow control. ## 4.2.0 * **Polish** * Use an assignment instead of a define for `__esModule` in loose mode. * **Internal** * Add error for `eval();` usage and enable strict mode for parsing. ## 4.1.0 * **New Feature** * Add `BABEL_CACHE_PATH` and `BABEL_DISABLE_CACHE` environment variables. * **Internal** * Replace many internal util functions with modules. Thanks [@sindresorhus](https://github.com/sindresorhus)! ## 4.0.2 * **Bug Fix** * Fix generators not properly propagating their internal declarations. * **Polish** * Update setter param length error message. * Use ranges on dependencies. ## 4.0.0 * 6to5 is now known as Babel. * Global helpers/runtime has now been given the more descriptive name of "external helpers".
CHANGELOG.md
1
https://github.com/babel/babel/commit/25581981b5bafb66341dafd67fc46b90eb925f98
[ 0.011137678287923336, 0.000311877578496933, 0.00016470997070427984, 0.00017492052575107664, 0.0012103948974981904 ]
{ "id": 0, "code_window": [ "\n", "_Note: Gaps between patch versions are faulty/broken releases._\n", "\n", "See [CHANGELOG - 6to5](CHANGELOG-6to5.md) for the pre-4.0.0 version changelog.\n", "\n", "## 5.5.0\n", "\n", " * **Bug Fix**\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "## 5.5.1\n", "\n", " * **Bug Fix**\n", " * Remove `ClassProperty` nodes always in the `Flow` transformer. This is fine now since.\n", "\n" ], "file_path": "CHANGELOG.md", "type": "add", "edit_start_line_idx": 15 }
"use strict"; var obj = babelHelpers.defineProperty({ first: "first" }, "second", "second");
test/core/fixtures/transformation/es6.properties.computed/two/expected.js
0
https://github.com/babel/babel/commit/25581981b5bafb66341dafd67fc46b90eb925f98
[ 0.00016899965703487396, 0.00016899965703487396, 0.00016899965703487396, 0.00016899965703487396, 0 ]
{ "id": 0, "code_window": [ "\n", "_Note: Gaps between patch versions are faulty/broken releases._\n", "\n", "See [CHANGELOG - 6to5](CHANGELOG-6to5.md) for the pre-4.0.0 version changelog.\n", "\n", "## 5.5.0\n", "\n", " * **Bug Fix**\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "## 5.5.1\n", "\n", " * **Bug Fix**\n", " * Remove `ClassProperty` nodes always in the `Flow` transformer. This is fine now since.\n", "\n" ], "file_path": "CHANGELOG.md", "type": "add", "edit_start_line_idx": 15 }
"use strict"; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = arr[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var i = _step.value; } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"]) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = numbers[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var i = _step2.value; } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2["return"]) { _iterator2["return"](); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } }
test/core/fixtures/transformation/es6.for-of/multiple/expected.js
0
https://github.com/babel/babel/commit/25581981b5bafb66341dafd67fc46b90eb925f98
[ 0.00017123681027442217, 0.00017019693041220307, 0.00016797259740997106, 0.00017079980170819908, 0.000001229996996698901 ]
{ "id": 0, "code_window": [ "\n", "_Note: Gaps between patch versions are faulty/broken releases._\n", "\n", "See [CHANGELOG - 6to5](CHANGELOG-6to5.md) for the pre-4.0.0 version changelog.\n", "\n", "## 5.5.0\n", "\n", " * **Bug Fix**\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "## 5.5.1\n", "\n", " * **Bug Fix**\n", " * Remove `ClassProperty` nodes always in the `Flow` transformer. This is fine now since.\n", "\n" ], "file_path": "CHANGELOG.md", "type": "add", "edit_start_line_idx": 15 }
(function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } });
src/babel/transformation/templates/helper-class-call-check.js
0
https://github.com/babel/babel/commit/25581981b5bafb66341dafd67fc46b90eb925f98
[ 0.00016688891628291458, 0.00016688891628291458, 0.00016688891628291458, 0.00016688891628291458, 0 ]
{ "id": 1, "code_window": [ "}\n", "\n", "export function ClassProperty(node) {\n", " node.typeAnnotation = null;\n", "}\n", "\n", "export function Class(node) {\n", " node.implements = null;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " // todo: uncomment when/if class properties are supported by default.\n", " // node.typeAnnotation = null;\n", " this.dangerouslyRemove();\n" ], "file_path": "src/babel/transformation/transformers/other/flow.js", "type": "replace", "edit_start_line_idx": 9 }
export var metadata = { group: "builtin-trailing" }; export function Flow(node) { this.dangerouslyRemove(); } export function ClassProperty(node) { node.typeAnnotation = null; } export function Class(node) { node.implements = null; } export function Func/*tion*/(node) { for (var i = 0; i < node.params.length; i++) { var param = node.params[i]; param.optional = false; } } export function TypeCastExpression(node) { return node.expression; } export function ImportDeclaration(node) { if (node.isType) this.dangerouslyRemove(); } export function ExportDeclaration(node) { if (this.get("declaration").isTypeAlias()) this.dangerouslyRemove(); }
src/babel/transformation/transformers/other/flow.js
1
https://github.com/babel/babel/commit/25581981b5bafb66341dafd67fc46b90eb925f98
[ 0.6478368639945984, 0.17050285637378693, 0.0015602429630234838, 0.016307132318615913, 0.27581003308296204 ]
{ "id": 1, "code_window": [ "}\n", "\n", "export function ClassProperty(node) {\n", " node.typeAnnotation = null;\n", "}\n", "\n", "export function Class(node) {\n", " node.implements = null;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " // todo: uncomment when/if class properties are supported by default.\n", " // node.typeAnnotation = null;\n", " this.dangerouslyRemove();\n" ], "file_path": "src/babel/transformation/transformers/other/flow.js", "type": "replace", "edit_start_line_idx": 9 }
exports.__esModule = true;
src/babel/transformation/templates/exports-module-declaration-loose.js
0
https://github.com/babel/babel/commit/25581981b5bafb66341dafd67fc46b90eb925f98
[ 0.0001748461800161749, 0.0001748461800161749, 0.0001748461800161749, 0.0001748461800161749, 0 ]
{ "id": 1, "code_window": [ "}\n", "\n", "export function ClassProperty(node) {\n", " node.typeAnnotation = null;\n", "}\n", "\n", "export function Class(node) {\n", " node.implements = null;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " // todo: uncomment when/if class properties are supported by default.\n", " // node.typeAnnotation = null;\n", " this.dangerouslyRemove();\n" ], "file_path": "src/babel/transformation/transformers/other/flow.js", "type": "replace", "edit_start_line_idx": 9 }
(function (global, factory) { if (typeof define === "function" && define.amd) { define("my custom module name", ["exports"], factory); } else if (typeof exports !== "undefined") { factory(exports); } else { var mod = { exports: {} }; factory(mod.exports); global.myCustomModuleName = mod.exports; } })(this, function (exports) { "use strict"; });
test/core/fixtures/transformation/es6.modules-umd/get-module-name-option/expected.js
0
https://github.com/babel/babel/commit/25581981b5bafb66341dafd67fc46b90eb925f98
[ 0.00017305022629443556, 0.00016989656432997435, 0.00016674290236551315, 0.00016989656432997435, 0.0000031536619644612074 ]
{ "id": 1, "code_window": [ "}\n", "\n", "export function ClassProperty(node) {\n", " node.typeAnnotation = null;\n", "}\n", "\n", "export function Class(node) {\n", " node.implements = null;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " // todo: uncomment when/if class properties are supported by default.\n", " // node.typeAnnotation = null;\n", " this.dangerouslyRemove();\n" ], "file_path": "src/babel/transformation/transformers/other/flow.js", "type": "replace", "edit_start_line_idx": 9 }
import codeFrame from "../../helpers/code-frame"; import NodePath from "./index"; import traverse from "../index"; import * as t from "../../types"; import parse from "../../helpers/parse"; var hoistVariablesVisitor = { Function() { this.skip(); }, VariableDeclaration(node, parent, scope) { if (node.kind !== "var") return; var bindings = this.getBindingIdentifiers(); for (var key in bindings) { scope.push({ id: bindings[key] }); } var exprs = []; for (var declar of (node.declarations: Array)) { if (declar.init) { exprs.push(t.expressionStatement( t.assignmentExpression("=", declar.id, declar.init) )); } } return exprs; } }; /** * Description */ export function replaceWithMultiple(nodes: Array<Object>) { this.resync(); nodes = this._verifyNodeList(nodes); t.inheritsComments(nodes[0], this.node); this.node = this.container[this.key] = null; this.insertAfter(nodes); if (!this.node) this.dangerouslyRemove(); } /** * Description */ export function replaceWithSourceString(replacement) { this.resync(); try { replacement = `(${replacement})`; replacement = parse(replacement); } catch (err) { var loc = err.loc; if (loc) { err.message += " - make sure this is an expression."; err.message += "\n" + codeFrame(replacement, loc.line, loc.column + 1); } throw err; } replacement = replacement.program.body[0].expression; traverse.removeProperties(replacement); return this.replaceWith(replacement); } /** * Description */ export function replaceWith(replacement, whateverAllowed) { this.resync(); if (this.removed) { throw new Error("You can't replace this node, we've already removed it"); } if (replacement instanceof NodePath) { replacement = replacement.node; } if (!replacement) { throw new Error("You passed `path.replaceWith()` a falsy node, use `path.dangerouslyRemove()` instead"); } if (this.node === replacement) { return; } // normalise inserting an entire AST if (t.isProgram(replacement)) { replacement = replacement.body; whateverAllowed = true; } if (Array.isArray(replacement)) { if (whateverAllowed) { return this.replaceWithMultiple(replacement); } else { throw new Error("Don't use `path.replaceWith()` with an array of nodes, use `path.replaceWithMultiple()`"); } } if (typeof replacement === "string") { if (whateverAllowed) { return this.replaceWithSourceString(replacement); } else { throw new Error("Don't use `path.replaceWith()` with a string, use `path.replaceWithSourceString()`"); } } // replacing a statement with an expression so wrap it in an expression statement if (this.isNodeType("Statement") && t.isExpression(replacement) && !this.canHaveVariableDeclarationOrExpression()) { replacement = t.expressionStatement(replacement); } // replacing an expression with a statement so let's explode it if (this.isNodeType("Expression") && t.isStatement(replacement)) { return this.replaceExpressionWithStatements([replacement]); } var oldNode = this.node; if (oldNode) t.inheritsComments(replacement, oldNode); // replace the node this.node = this.container[this.key] = replacement; this.type = replacement.type; // potentially create new scope this.setScope(); } /** * Description */ export function replaceExpressionWithStatements(nodes: Array) { this.resync(); var toSequenceExpression = t.toSequenceExpression(nodes, this.scope); if (toSequenceExpression) { return this.replaceWith(toSequenceExpression); } else { var container = t.functionExpression(null, [], t.blockStatement(nodes)); container.shadow = true; this.replaceWith(t.callExpression(container, [])); this.traverse(hoistVariablesVisitor); // add implicit returns to all ending expression statements var last = this.get("callee").getCompletionRecords(); for (var i = 0; i < last.length; i++) { var lastNode = last[i]; if (lastNode.isExpressionStatement()) { var loop = lastNode.findParent((node, path) => path.isLoop()); if (loop) { var uid = this.get("callee").scope.generateDeclaredUidIdentifier("ret"); this.get("callee.body").pushContainer("body", t.returnStatement(uid)); lastNode.get("expression").replaceWith( t.assignmentExpression("=", uid, lastNode.node.expression) ); } else { lastNode.replaceWith(t.returnStatement(lastNode.node.expression)); } } } return this.node; } } /** * Description */ export function replaceInline(nodes) { this.resync(); if (Array.isArray(nodes)) { if (Array.isArray(this.container)) { nodes = this._verifyNodeList(nodes); this._containerInsertAfter(nodes); return this.dangerouslyRemove(); } else { return this.replaceWithMultiple(nodes); } } else { return this.replaceWith(nodes); } }
src/babel/traversal/path/replacement.js
0
https://github.com/babel/babel/commit/25581981b5bafb66341dafd67fc46b90eb925f98
[ 0.0006266715354286134, 0.00024931266671046615, 0.00016669582691974938, 0.00017468183068558574, 0.00012225830869283527 ]
{ "id": 2, "code_window": [ " \"bar\"() {}\n", "}\n", "function foo(requiredParam, optParam) {}\n", "class Foo9 {\n", " prop1;\n", " prop2;\n", "}\n", "class Foo10 {\n", " static prop1;\n", " prop2;\n", "}\n", "var x = 4;\n", "class Array {\n", " concat(items) {}\n", "}\n", "var x = fn;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "class Foo9 {}\n", "class Foo10 {}\n" ], "file_path": "test/core/fixtures/transformation/flow/strip-type-annotations/expected.js", "type": "replace", "edit_start_line_idx": 66 }
# Changelog > **Tags:** > - [New Feature] > - [Bug Fix] > - [Spec Compliancy] > - [Breaking Change] > - [Documentation] > - [Internal] > - [Polish] _Note: Gaps between patch versions are faulty/broken releases._ See [CHANGELOG - 6to5](CHANGELOG-6to5.md) for the pre-4.0.0 version changelog. ## 5.5.0 * **Bug Fix** * Allow pushing declarations to `SwitchStatement`s. * Fix `minification.removeDebugger` to remove `DebuggerStatement`s rather than `ExpressionStatement`s with an identifier of `debugger`. * Check LHS in `ForInStatement` and `ForOfStatement` for constant violations. * Register function `id` as a reference when naming methods to avoid collisions. * Support key literals when checking for the existence of `displayName` property when attempting to add it for `React.createClass`. * Remove `ExportDefaultSpecifier` check from `t.isDefaultSpecifier`. * Don't consider `JSXIdentifier` HTML tag identifiers to be references. * **Polish** * Update `minification.deadCodeElimination` transformer to remove all statements after completion statements. * Update `minification.deadCodeElimination` transformer to not inline single used bindings that exist in different scopes. * When performing Istanbul interop in `babel/register`, add the auxiliary comment `"istanbul ignore text"` to get more accurate coverage. * Add `--nolazy` argument to `babel-node`. * Add support for `cluster` forking. * Perform scope tracking in a single pass instead of multiple. * Smarten up type inferrence and resolution to support the whole array of language constructs. * Optimise module metadata retrieval into a single pass. * Ignore trailing commas when inferring newlines. * Rename `minification.inlineExpressions` transformer to `minification.constantFolding`. * Check path relative to entry file when checking to see if we're inside `node_modules` when using `babel/register`. * Upgrade `regenerator`. ## 5.4.7 * **Bug Fix** * Don't consider `JSXAttribute` `names` to be valid `ReferencedIdentifier`s. ## 5.4.6 * **Bug Fix** * Fix `spec.functionName` transformer incorrectly attempting to rename a binding that doesn't exist as it's a global. * **Internal** * Deprecate custom module formatters. ## 5.4.5 * **Bug Fix** * Add `JSXIdentifier` as a valid `ReferencedIdentifier` visitor virtual type. * Ignore `CallExpression` `_prettyCall` when the `retainLines` option is enabled. * Inherit comments to new declaration node when exploding module declarations. * Fix `es6.tailCall` transformer failing on calls that exceed the max parameters of the function. ## 5.4.4 * **Bug Fix** * Fix bug where replacing variable declarations in the head of a `for` loop would turn them into `ExpressionStatement`s. * Fix renaming of assignment expressions that were non-identifiers ie. patterns. * Force space before `class` `id` to avoid breaking named classes when using `compact` mode. * Add assignment pattern explosion to avoid initial duplicate nodes. * Ignore this and arguments when performing TCO on shadowed functions. * **Polish** * Rename `sourceMapName` option to `sourceMapTarget`. Thanks [@getify](https://github.com/getify)! * Better detection of completion records, ignore those in `Function`s. * Clarified descriptions of the options that are enabled by default. * Resolve `\`babel-plugin-${name}\`` plugin names **before** just checking the `name`. Thanks [@jquense](https://github.com/jquense)! * Update AMD module formatter to add import default remapping. ## 5.4.3 * **Bug Fix** * Fix `module` being incorrectly rewritten when used as in an export declaration. * When performing single-reference inlining, ensure that the single reference isn't a child of the binding itself. * Fix a bug in `minification.deadCodeElimination` where a new binding instance was being created for local class bindings instead of just inheriting the parent one. * Fix bug with paren printing in `compact` and `retainLines` mode where a left paren was already printed before catching up. * **Internal** * Handle contexts for paths much better. This will ensure that the path node location info is in sync. ## 5.4.2 * **Polish** * `ignore` and `only` patterns are now **very** liberal. The pattern can now exist anywhere in the path. ## 5.4.1 * **Bug Fix** * Add missing `slash` dependency. Thanks [@browncolyn](https://github.com/browncolyn)! * **Polish** * Clean up `shouldIgnore` algorithm to work how you'd expect rather than being a hacky piece of shit. It now crawls the entire path, checking each section of it against the input ignore/only patterns. This means that the pattern `foo` will ignore the paths `foo/bar.js`, `bar/foo` etc. ## 5.4.0 * **New Feature** * Added [function bind syntax](https://github.com/zenparsing/es-function-bind) behind stage 0. Thanks [@RReverser](https://github.com/rreverser)! * Added `env` option. Especially handy when using the `.babelrc`. * **Bug Fix** * Fix files not properly being ignored when `babel.transform` ignores them when using `$ babel`. * Fix scope tracking registering loop head bindings to their `VariableDeclaration` instead of `VariableDeclarator`. * **Polish** * Normalise path separators for souce map paths when using `$ babel`. * Rework `PathHoister` to ignore global references and to not deopt on reassignments to referenced bindings, instead it tries to hoist to the highest scope. * Added missing exponential operator inlining. Thanks [@nkt](https://github.com/nkt)! * Optimise `regenerator` transformer. Thanks [@benjamn](https://github.com/benjamn)! ## 5.3.3 * **Bug Fix** * Fix `minification.deadCodeElimination` transformer incorrectly trying to inline import declarations. * Fix `minification.inlineExpression` transformer getting into an infinite loop. ## 5.3.2 * **Bug Fix** * Fix patterns not being considered when hoisting variables in the `es6.blockScoping` transformer. ## 5.3.1 * **Bug Fix** * Fix unique export specifiers not being cloned when exploding class and function exports, * **Polish** * Turn import remaps to sequence expressions to remove their context and improve performance. ## 5.3.0 **Speeeeeeed** ![gifs lol](https://31.media.tumblr.com/568205a0e37ae15eca510fa639589a59/tumblr_n8kw8kpcSb1sg6cg8o1_500.gif) * **Spec Compliancy** * Allow trailing param commas for methods when using the `es7.trailingCommas` transformer. * **Bug Fix** * Fix `es6.blockScoping` transformer not properly ignoring `break` in `SwitchCase`. * Fix lookahead context saving to avoid weird tokenizer state. * Explode duplicate identifiers in export/import specifiers and property shorthand to create unique objects. * Skip loose mode for class methods when they have decorators. * When removing nodes, share their comments with their siblings. * Properly hoist temp param declarations when doing TCO. * **Internal** * Add `--harmony_generators` flag to `$ babel-node`. * Internal AST traversals have been minimised **drastically**. Transformers have been grouped together which means entire tree traversals are much fewer. Visiting nodes is now also skipped if the traversal context can detect that the handler is a noop. This sames precious cycles as it avoids constructing traversal paths and creating a new traversal context. See issues [#1472](https://github.com/babel/babel/issues/1472) and [#1486](https://github.com/babel/babel/issues/1486) for related discussion. * **Polish** * Move many `utility` transformers to `minification`. ## 5.2.17 * **Bug Fix** * Fix auxiliary comments not properly being attached to function declaration helpers. * Add `Super` node type to `ast-types` patch. * Ignore parameter bindings when attempting to inline them in the `minification.deadCodeElimination` transformer. * Correct `extensions` arguments when using the Babel CLI. ## 5.2.16 * **Bug Fix** * Fix plugins being disabled when using the whitelist. * Fix correct function scope being passed to `nameMethod.property` when inferring the function name for class methods. * Fix incorrect extensions reference causing weird issues when using the Babel CLI. * Fix destructuring param reference replacements not inheriting from their original param. * **Spec Compliancy** * Fix order that method decorators are ran in. ## 5.2.15 * **Bug Fix** * Fix initializer descriptor add attempt if it doesn't exist. ## 5.2.14 * **Bug Fix** * Fix bug with initializer decorators where the descriptors weren't being defined if there was no `initializer` property. * **Internal** * Expose `retainLines` option to CLI. * Fix `retainLines` option not being taken into consideration when doing multiple variable declaration declarators generation. * Expose minified and unminified copies of dist scripts. ## 5.2.13 * **Bug Fix** * Fix `ExportDeclaration`s being incorrectly removed when using the `utility.deadCodeElimination` transformer. * Fix position of `utility` transformers. * **New Feature** * Add built-in `esquery` support. * **Internal** * Consolidate notion of "virtual types". ## 5.2.12 * **Polish** * Make UID generation based on module declarations **much** nicer. * **Internal** * Remove internal check for traversal path replacement of self. This is a pattern that **could** come up in the wild and it could lead to pretty nasty code and may lead to internal regressions as the test coverage isn't 100% :( Instead, just put it in the fast path. ## 5.2.11 * **Internal** * Rename `getModuleName` option to `getModuleId`, doh. ## 5.2.10 * **Bug Fix** * Fix numerous issues in `replaceWithSourceString`. Thanks [@pangratz](https://github.com/pangratz)! * **New Feature** * Add `getModuleName` option. Thanks [@jayphelps](https://github.com/jayphelps)! ## 5.2.9 * **Bug Fix** * Fix `_blockHoist` transformer incorrectly sorting nodes on shitty environments that aren't spec compliant in their key order. * Fix broken `parse` API method reference to an undeclared import. ## 5.2.7 * **Bug Fix** * Move `utility.deadCodeElimination` transformer up to avoid race conditions. * Fix shorthand property scope binding renaming. * **Polish** * Turn helper variable declarations into function declarations if possible. * **Internal** * Removed native inheritance support from classes. * Added `replaceWithSourceString` path API. * Split up `es3.propertyLiterals` and `es3.memberExpressionLiterals` transformers to `minfication.propertyLiterals` and `es3.memberExpressionLiterals`. ## 5.2.6 * **Internal** * Fix transformer aliases being accidently set as deprecated ones. * Expose `Pipeline` as `TransformerPipeline` instead. ## 5.2.5 * **Bug Fix** * Fix `parse` API not adding all the correct pipeline transformers. ## 5.2.4 * **Bug Fix** * Fix race condition with the Node API being loaded awkwardly and not being able to initialise itself when used in the browser. * **Internal** * Expose `transform.pipeline`. ## 5.2.3 * **Bug Fix** * Fix plugin containers being called with an undefined import. Thanks [@timbur](https://github.com/timbur)! * Allow Flow object separators to be commas. Thanks [@monsanto](https://github.com/monsanto)! * Add missing `Statement` and `Declaration` node aliases to flow types. ## 5.2.2 * **Internal** * Allow `util.arrayify` to take arbitrary types and coerce it into an array. ## 5.2.1 * **Bug Fix** * Fix regression in `node/register` that caused `node_modules` to not be ignored. ## 5.2.0 * **Bug Fix** * Fix plugin strings splitting arbitrarily on `:` which caused full paths on Windows to fail as they include `:` after the drive letter. * Call class property `initializer`s with their target instead of their descriptor. * Fix `ignore` and `only` not properly working on Windows path separators. Thanks [@stagas](https://github.com/stagas)! * Fix `resolveRc` running on files twice causing issues. Thanks [@lukescott](https://github.com/lukescott)! * Fix shorthand properties not correctly being target for `isReferenced` checks. Thanks [@monsanto](https://github.com/monsanto)! * **Polish** * Allow passing an array of globs to `babel/register` `only` and `ignore` options. Thanks [@Mark-Simulacrum](https://github.com/Mark-Simulacrum)! * When inferring function names that collide with upper bindings, instead of doing the wrapper, instead rename them. * Consider constant-like variable declaration functions to always refer to themselves so TOC can be performed. * Process globs manually when using `$ babel` as some shells such as Windows don't explode them. Thanks [@jden](https://github.com/jden)! * Add alternative way to execute plugins via a closure that's called with the current Babel instance. * **Internal** * Remove multiple internal transformers in favor of directly doing things when we need to. Previously, declarations such as `_ref` that we needed to create in specific scopes were done at the very end via the `_declarations` transformer. Now, they're done and added to the scope **right** when they're needed. This gets rid of the crappy `_declarations` property on scope nodes and fixes the crappy regenerator bug where it was creating a new `BlockStatement` so the declarations were being lost. * Rework transformer traversal optimisation. Turns out that calling a `check` function for **every single node** in the AST is ridiculously expensive. 300,000 nodes timesed by ~30 transformers meant that it took tens of seconds to perform while it's quicker to just do the unnecessary traversal. Seems obvious in hindsight. * **New Feature** * Add `jscript` transformer that turns named function expressions into function declarations to get around [JScript's horribly broken function expression semantics](https://kangax.github.io/nfe/#jscript-bugs). Thanks [@kondi](https://github.com/kondi)! * Add `@@hasInstance` support to objects when using the `es6.spec.symbols` transformer. * Add `retainLines` option that retains the line (but not the columns!) of the input code. ## 5.1.13 * **Polish** * Remove symbol check from `defineProperty` helper. ## 5.1.12 * **Bug Fix** * Fix `resolveModuleSource` not being ran on `ExportAllDeclaration`s. * Fix `.babelrc` being resolved multiple times when using the require hook. * Fix parse error on spread properties in assignment position. * Fix `externalHelpers` option being incorrectly listed as type `string`. * **Internal** * Upgrade `core-js` to `0.9.0`. * **Spec Compliancy** * Fix object decorators not using the `initializer` pattern. * Remove property initializer descriptor reflection. ## 5.1.11 * **Bug Fix** * Memoise and bind member expression decorators. * Move JSX children cleaning to opening element visitor. Fixes elements not being cleaned in certain scenarios. * Consider `SwitchStatement`s to be `Scopable`. * Fix `bluebirdCoroutines` calling `interopRequireWildcard` before it's defined. * Add space to `do...while` code generation. * Validate `super` use before `this` on `super` exit rather than entrance. * **Polish** * Add Babel name to logger. ## 5.1.10 * **Bug Fix** * Remove `makePredicate` from acorn in favor of an `indexOf`. * Remove statements to expression explosion when inserting a block statement. * **Internal** * Remove runtime compatibility check. ## 5.1.9 * **Bug Fix** * Fix class property initializers with `undefined` values not being correctly writable. * Fix self inferring generators incorrectly causing a stack error. * Fix default export specifiers not triggering AMD `module` argument inclusion. * Fix assignments not having their module references properly remapped. * **Internal** * Upgrade to latest `acorn`. * **Polish** * Make invalid LHS pattern error messages nicer. ## 5.1.8 * **Bug Fix** * Only make parenthesized object pattern LHS illegal. ## 5.1.7 * **Internal** * Add `parse` node API. ## 5.1.6 * **Bug Fix** * Fix `runtime` built-in catchall not properly checking for local variables. ## 5.1.5 * **Internal** * Bump `core-js` version. ## 5.1.4 * **Polish** * Add missing `Reflect` methods to runtime transformer. ## 5.1.3 * **Internal** * Switch entirely to vanilla regenerator. * Clean up and make the parsing of decorators stateless. * **Bug Fix** * Don't do TCO on generators and async functions. * Add missing `core-js` runtime definitions. ## 5.1.2 * **Bug Fix** * Add `getIterator` and `isIterable` to `babel-runtime` build script. ## 5.1.1 * **Bug Fix** * Add missing runtime symbol definitions. ## 5.1.0 * **Bug Fix** * Fix super reference when using decorators. * Don't do array unpack optimisation when member expressions are present. * Add missing descriptors for undecorated class properties. * Don't consider `arguments` and `eval` valid function names when doing function name inferrence. * Fix scope tracking of constants in loop heads. * Parse `AwaitExpression` as a unary instead of an assignment. * Fix regex evaluation when attempting static evaluation. * Don't emit tokens when doing a lookahead. * Add missing `test` declaration to `utility.deadCodeElimination` transformer. * **Internal** * Upgrade `regenerator` to the latest and use my branch with the hope of eventually switching to vanilla regenerator. * Add support for the replacement of for loop `init`s with statements. * Upgrade dependencies. * **Polish** * When adding the scope IIFE when using default parameters, don't shadow the function expression, just `apply` `this` and `arguments` if necessary. * Use path basename as non-default import fallback. * **New Feature** * Add [trailing function comma proposal](https://github.com/jeffmo/es-trailing-function-commas). Thanks [@AluisioASG](https://github.com/AluisioASG)! * Add support for object literal decorators. * Make core-js modular when using the `runtime` transformer. ## 5.0.12 * **Bug Fix** * Fix incorrect remapping of module references inside of a function id redirection container. ## 5.0.11 * **Bug Fix** * Fix new `for...of` loops not properly inheriting their original loop. * **Internal** * Disable scope instance cache. * **Polish** * Allow comments in `.babelrc` JSON. ## 5.0.9 * **Polish** * Use `moduleId` for UMD global name if available. * **Bug Fix** * Fix UMD global `module` variable shadowing the `amd`/`common` `module` variable. * Fix Flow param type annotation regression. * Fix function name collision `toString` wrapper. Thanks [@alawatthe](https://github.com/alawatthe)! ## 5.0.8 * **Bug Fix** * Fix falsy static class properties not being writable. * Fix block scoping collisions not properly detecting modules and function clashes. * Skip `this` before `super` for derived constructors on functions. ## 5.0.7 * **New Feature** * Add `--ignore` and `--only` support to the CLI. * **Bug Fix** * Remove `HOMEPATH` environment variable from home resolution in `babel/register` cache. * **Internal** * Disable WIP path resolution introducing infinite recursion in some code examples. * **Polish** * Add live binding to CommonJS default imports. ## 5.0.6 * **Bug Fix** * Fix mangling of import references that collide with properties on `Object.prototype`. * Fix duplicate declarations incorrectly being reported for `var`. ## 5.0.5 * **Internal** * Upgrade `core-js`. * **Bug Fix** * Fix arrays not being supported in `util.list`. ## 5.0.4 * **Polish** * Check for top level `breakConfig` in `resolveRc`. ## 5.0.3 * **Bug Fix** * Make relative location absolute before calling `resolveRc`. * **Internal** * Switch to global UID registry. * Add `breakConfig` option to prevent Babel from erroring when hitting that option. ## 5.0.1 * **Bug Fix** * Fix duplicate declaration regression. * Fix not being able to call non-writable methods. ## 5.0.0 * **New Feature** * Decorators based on [@wycat's](https://github.com/wycats) [stage 1 proposal](https://github.com/wycats/javascript-decorators). * Class property initializers based on [@jeffmo's](https://github.com/jeffmo) [stage 0 proposal](https://gist.github.com/jeffmo/054df782c05639da2adb). * Export extensions based on [@leebyron's](https://github.com/leebyron) [stage 1 proposal](https://github.com/leebyron/ecmascript-more-export-from). * UMD module formatter now supports globals. * Add `es3.runtime`, `optimisation.react.inlineElements` and `optimisation.react.constantElements` transformers. * Add stage option that replaces the experimental one. * Allow ES7 transformer to be enabled via `optional` instead of only via `stage`. * Infer string quotes to use in the code generator. * Consider `export { foo as default };` to be the same as `export default foo;`. * Add `nonStandard` option that can be set to `false` to remove parser support for JSX and Flow. * Add `jsxPragma` option. * Automatically generate CLI options based on internal API options. * Add support for `.babelrc` on absolute paths. * Plugin API! * **Internal** * Export `options` in browser API. * Rewritten parser. * Don't block hoist when runtime transformer is enabled in system module formatter. * Rewritten the internal traversal and node replacement API to use "paths" that abstracts out node relationships. * **Polish** * JSX output is now more inline with the official JSX transformer. * Hoist block scoping IIFE - this improves memory usage and performance. * Better IIFE detection - references are now checked to see if they're referencing the binding we're searching for. * Check for import reassignments in constants transformer. * Make method definitions with expression bodies illegal. * Save register cache on tick instead of `SIGINT`. * Enable strict mode on babel-node eval flag. * **Bug Fixes** * Add support for live bindings. This change also increases the reliablity of export specifier renaming. * Add support for super update and non equals assignment expressions. * Rename shadow constructor binding in classes. * Seed next iteration bindings with previous fresh bindings when reassinging loop block scoped variables. * Fix new expression spread referencing the wrong constructor. * Call `resolveModuleSource` on dynamic imports. * Added `param` to list of duplicate declaration kinds. * **Breaking Changes** * The Babel playground has been removed. * ES7 Abstract References have been removed. * Experimental option has been removed in favor of a stage option. * Rename `returnUsedHelpers` to `metadataUsedHelpers`. ## 4.7.16 * **Bug Fix** * Fix constructor spreading of typed arrays. * Fix break/continue/return aliasing of non-loops in block scoping transformer. ## 4.7.15 * **Bug Fix** * Fix constructor spreading of collections. ## 4.7.14 * **Bug Fix** * Fix constructor spreading of `Promise`. * **Internal** * Deprecate remaining playground transformers and abstract references. ## 4.7.13 * **Bug Fix** * Handle comments on use strict directives. * Fix assignment patterns with a left side pattern. * **Polish** * Special case `this` when doing expression memoisation. ## 4.7.12 * **Bug Fix** * Deprecate `playground.methodBinding`. ## 4.7.11 * **Bug Fix** * Fix unicode regexes stripping their unicode flag before being passed on two `regexpu`. ## 4.7.10 * **Internal** * Deprecate `playground.methodBinding` and `playground.objectGetterMemoization`. * **Bug Fix** * Fix `inputSourceMap` option. Thanks [@Rich-Harris](https://github.com/Rich-Harris)! ## 4.7.9 * **Polish** * Allow `inputSourceMap` to be set to `false` to skip the source map inference. * Infer computed literal property names. * **Bug Fix** * Fix nested labeled for-ofs. * Fix block scoping `break` colliding with the parent switch case. * **Internal** * Upgrade `acorn-babel`. ## 4.7.8 * **Bug Fix** * Fix computed classes not properly setting symbols. ## 4.7.7 * **Bug Fix** * Fix `types` API exposure. ## 4.7.6 * **Bug Fix** * Fix non-Identifier/Literal computed class methods. * **Polish** * Add a fallback if `stack` on an error is unconfigurable. * Hoist `esModule` module declarations to the top of the file to handle circular dependencies better. ## 4.7.5 * **Bug Fix** * Don't remap` break`s to call the iterator return. * **Polish** * Use a different helper for computed classes for much nicer output. Also fixes a bug in symbols being non-enumerable so they wouldn't be set on the class. ## 4.7.4 * **Bug Fix** * Rewrite named function expressions in optional async function transformers. * Hoist directives. * Remove `Number` from the list of valid `runtime` constructors. * **Internal** * `spec.typeofSymbol` transformer has been renamed to `es6.symbols`. ## 4.7.2 * **New Feature** * `"both"` option for `sourceMap`. * Add output types to external helpers. Thanks [@neVERberleRfellerER](https://github.com/neVERberleRfellerER)! * **Bug Fix** * Fix node duplication sometimes resulting in a recursion error. * Ignore `break`s within cases inside `for...of`. * **Polish** * Split up variable declarations and export declarations to allow easier transformation. ## 4.7.0 * **Bug Fix** * Add `alternate` to list of `STATEMENT_OR_BLOCK` keys. * Add support for module specifiers to `t.isReferenced`. * **New Feature** * Add `inputSourceMap` option. * **Polish** * Throw an error on different `babel` and `babel-runtime` versions. * Replicate module environment for `babel-node` eval. * Clean up classes output. * **Spec Compliancy** * Make it illegal to use a rest parameter on a setter. ## 4.6.6 * **Bug Fix** * Fix incorrect method call in `utility.deadCodeElimination` transformer. * Fix `es6.blockScopingTDZ` transformer duplicating binding nodes. ## 4.6.5 * **Internal** * `useStrict` transformer has been renamed to `strict`. ## 4.6.4 * **Bug Fix** * Fix `ForOfStatement` not proplery inheriting labels. * When in closure mode in block scoping transformer, properly check for variable shadowing. * **New Feature** * New `utility.inlineEnvironmentVariables` and `utility.inlineExpression` transformers. ## 4.6.3 * **Bug Fix** * Fix `arguments` being incorrectly aliased in arrow function rest parameter optimisation. * Make deoptimisation trigger safer. * **New Feature** * Flow types are now retained when blacklisting the `flow` transformer. ## 4.6.1 * **Bug Fix** * Fix generators in template directory being transformed. * Fix exposure of `util` for plugins. ## 4.6.0 * **New Feature** * Desugar sticky regexes to a new constructor expression so it can be handled by a polyfill. * **Spec Compliancy** * `for...of` now outputs in a lengthy `try...catch` this is to ensure spec compliancy in regards to iterator returns and abrupt completions. See [google/traceur-compiler#1773](https://github.com/google/traceur-compiler/issues/1773) and [babel/babel/#838](https://github.com/babel/babel/issues/838) for more information. * **Polish** * Rest parameters that are only refered to via number properties on member expressions are desugared into a direct `arguments` reference. Thanks [@neVERberleRfellerER](https://github.com/neVERberleRfellerER)! * `$ babel` no longer exits on syntax errors. * **Internal** * Upgrade `browserify`. * Upgrade `source-map`. * Publicly expose more internals. ## 4.5.5 * **Polish** * Delete old extensions when overriding them in `babel/register`. ## 4.5.3 * **Bug Fix** * Fix whitelisting logic for helper build script. ## 4.5.2 * **New Feature** * `returnUsedHelpers` option and add whitelist to `buildHelpers`. * **Bug Fix** * Fix function arity on self referencing inferred named functions. * **Internal** * Bump `acorn-babel`. * Start converting source to ES6... ## 4.5.1 **Babel now compiles itself!** ![holy shit](http://gifsec.com/wp-content/uploads/GIF/2014/03/OMG-GIF_2.gif) ## 4.5.0 * **New Feature** * Add `.babelrc` support. * **Bug Fix** * Move use strict directives to the module formatter bodies. * **Internal** * Make default `bin/babel` behaviour to ignore non-compilable files and add a `--copy-files` flag to revert to the old behaviour. ## 4.4.6 * **Bug Fix** * Fix extending a class expression with no methods/only constructor. Thanks [@neVERberleRfellerER](https://github.com/neVERberleRfellerER)! * Allow `MemberExpression` as a valid `left` of `ForOfStatement`. * **Polish** * Throw an error when people try and transpile code with the `@jsx React.DOM` pragma as it conflicts with the custom jsx constructo method detection. * Crawl all comments for `@jsx` pragma. * **Internal** * Upgrade `chalk`. * Upgrade `core-js`. ## 4.4.5 * **Internal** * Remove function self reference optimisation. ## 4.4.4 * **Bug Fix** * Handle inferred function ids to be reassigned and deopt to a slower but working equivalent. * Don't unpack array patterns that have more elements than their right hand array expression. * **Polish** * Improve syntax highlighting in the code frame. Thanks [@lydell](https://github.com/lydell)! * **Internal** * Upgrade `acorn-babel`. ## 4.4.3 * **Bug Fix** * Fix `for...of` iterator break returns being duplicated. * Only call `return` on the iterator if it exists. * **Internal** * Rename `selfContained` transformer to `runtime`. ## 4.4.2 * **New Feature** * Add `moduleId` option for specifying a custom module id. ## 4.4.0 * **New Feature** * `/*** @jsx NAMESPACE **/` comments are now honored by the `react` transformer. * `getModuleName` option. * Infer function expression names. Thanks [@RReverser](https://github.com/RReverser)! * **Bug Fix** * Add proper control flow for tail recursion optimisation. * **Internal** * Remove useless `format` options and move the `format.compact` option to `format`. * **Polish** * Newline handling of the code generator has been heavily improved. * Code generator now deopts whitespace if the input size is >100KB. ## 4.3.0 * **Breaking Change** * Remove `commonStandard` module formatter and make it the default behaviour of all the strict module formatters. ## 4.2.1 * **Polish** * Add auxiliary comment to let scoping closure flow control. ## 4.2.0 * **Polish** * Use an assignment instead of a define for `__esModule` in loose mode. * **Internal** * Add error for `eval();` usage and enable strict mode for parsing. ## 4.1.0 * **New Feature** * Add `BABEL_CACHE_PATH` and `BABEL_DISABLE_CACHE` environment variables. * **Internal** * Replace many internal util functions with modules. Thanks [@sindresorhus](https://github.com/sindresorhus)! ## 4.0.2 * **Bug Fix** * Fix generators not properly propagating their internal declarations. * **Polish** * Update setter param length error message. * Use ranges on dependencies. ## 4.0.0 * 6to5 is now known as Babel. * Global helpers/runtime has now been given the more descriptive name of "external helpers".
CHANGELOG.md
1
https://github.com/babel/babel/commit/25581981b5bafb66341dafd67fc46b90eb925f98
[ 0.00025299107073806226, 0.00016888263053260744, 0.00016121065709739923, 0.00016815096023492515, 0.000009881742698780727 ]
{ "id": 2, "code_window": [ " \"bar\"() {}\n", "}\n", "function foo(requiredParam, optParam) {}\n", "class Foo9 {\n", " prop1;\n", " prop2;\n", "}\n", "class Foo10 {\n", " static prop1;\n", " prop2;\n", "}\n", "var x = 4;\n", "class Array {\n", " concat(items) {}\n", "}\n", "var x = fn;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "class Foo9 {}\n", "class Foo10 {}\n" ], "file_path": "test/core/fixtures/transformation/flow/strip-type-annotations/expected.js", "type": "replace", "edit_start_line_idx": 66 }
<div>&nbsp; </div>;
test/core/fixtures/transformation/react/.should-not-strip-nbsp-even-coupled-with-other-whitespace/actual.js
0
https://github.com/babel/babel/commit/25581981b5bafb66341dafd67fc46b90eb925f98
[ 0.00017144071171060205, 0.00017144071171060205, 0.00017144071171060205, 0.00017144071171060205, 0 ]
{ "id": 2, "code_window": [ " \"bar\"() {}\n", "}\n", "function foo(requiredParam, optParam) {}\n", "class Foo9 {\n", " prop1;\n", " prop2;\n", "}\n", "class Foo10 {\n", " static prop1;\n", " prop2;\n", "}\n", "var x = 4;\n", "class Array {\n", " concat(items) {}\n", "}\n", "var x = fn;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "class Foo9 {}\n", "class Foo10 {}\n" ], "file_path": "test/core/fixtures/transformation/flow/strip-type-annotations/expected.js", "type": "replace", "edit_start_line_idx": 66 }
!function () {} // , 42; !{ get 42() {} // , foo: 42 }; (function () {} // );
test/core/fixtures/generation/comments/function-block-line-comment/expected.js
0
https://github.com/babel/babel/commit/25581981b5bafb66341dafd67fc46b90eb925f98
[ 0.00016587831487413496, 0.00016587831487413496, 0.00016587831487413496, 0.00016587831487413496, 0 ]
{ "id": 2, "code_window": [ " \"bar\"() {}\n", "}\n", "function foo(requiredParam, optParam) {}\n", "class Foo9 {\n", " prop1;\n", " prop2;\n", "}\n", "class Foo10 {\n", " static prop1;\n", " prop2;\n", "}\n", "var x = 4;\n", "class Array {\n", " concat(items) {}\n", "}\n", "var x = fn;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "class Foo9 {}\n", "class Foo10 {}\n" ], "file_path": "test/core/fixtures/transformation/flow/strip-type-annotations/expected.js", "type": "replace", "edit_start_line_idx": 66 }
class Foo { foo() {} "foo"() {} [bar]() {} [bar + "foo"]() {} }
test/core/fixtures/transformation/es6.classes/computed-methods/actual.js
0
https://github.com/babel/babel/commit/25581981b5bafb66341dafd67fc46b90eb925f98
[ 0.2529173493385315, 0.2529173493385315, 0.2529173493385315, 0.2529173493385315, 0 ]
{ "id": 0, "code_window": [ "const props = defineProps<{\n", " value?: string | null\n", " readonly?: boolean\n", " syncValueChange?: boolean\n", " showMenu?: boolean\n", "}>()\n", "\n", "const emits = defineEmits(['update:value'])\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " fullMode?: boolean\n" ], "file_path": "packages/nc-gui/components/cell/RichText.vue", "type": "add", "edit_start_line_idx": 16 }
<script lang="ts" setup> import StarterKit from '@tiptap/starter-kit' import TaskItem from '@tiptap/extension-task-item' import TaskList from '@tiptap/extension-task-list' import { EditorContent, useEditor } from '@tiptap/vue-3' import TurndownService from 'turndown' import { parse } from 'marked' import { generateJSON } from '@tiptap/html' import Underline from '@tiptap/extension-underline' import { Link } from '@/helpers/dbTiptapExtensions/links' const props = defineProps<{ value?: string | null readonly?: boolean syncValueChange?: boolean showMenu?: boolean }>() const emits = defineEmits(['update:value']) const turndownService = new TurndownService() const editorDom = ref<HTMLElement | null>(null) const vModel = useVModel(props, 'value', emits, { defaultValue: '' }) const tiptapExtensions = [ StarterKit, TaskList, TaskItem.configure({ nested: true, }), Underline, Link, ] const editor = useEditor({ extensions: tiptapExtensions, onUpdate: ({ editor }) => { const markdown = turndownService.turndown(editor.getHTML()) vModel.value = markdown }, editable: !props.readonly, }) const setEditorContent = (contentMd: any) => { if (!editor.value) return ;(editor.value.state as any).history$.prevRanges = null ;(editor.value.state as any).history$.done.eventCount = 0 const selection = editor.value.view.state.selection const contentHtml = contentMd ? parse(contentMd) : '<p></p>' const content = generateJSON(contentHtml, tiptapExtensions) editor.value.chain().setContent(content).setTextSelection(selection.to).run() } if (props.syncValueChange) { watch(vModel, () => { setEditorContent(vModel.value) }) } watch(editorDom, () => { if (!editorDom.value) return setEditorContent(vModel.value) // Focus editor after editor is mounted setTimeout(() => { editor.value?.chain().focus().run() }, 50) }) </script> <template> <div class="h-full"> <div v-if="props.showMenu" class="absolute top-1 z-1000 right-3"> <CellRichTextSelectedBubbleMenu v-if="editor" :editor="editor" embed-mode /> </div> <CellRichTextSelectedBubbleMenuPopup v-if="editor" :editor="editor" /> <CellRichTextLinkOptions v-if="editor" :editor="editor" /> <EditorContent ref="editorDom" :editor="editor" class="nc-textarea-rich w-full h-full nc-text-rich-scroll nc-scrollbar-md" /> </div> </template> <style lang="scss"> .nc-text-rich-scroll { &::-webkit-scrollbar-thumb { @apply bg-transparent; } } .nc-text-rich-scroll:hover { &::-webkit-scrollbar-thumb { @apply bg-gray-200; } } .nc-textarea-rich { .ProseMirror-focused { // remove all border outline: none; } p { @apply !mb-1; } ul { @apply ml-4; li { list-style-type: disc; } } ol { @apply -ml-6; li { list-style-type: decimal; } } ul[data-type='taskList'] { @apply ml-0; li { @apply flex flex-row items-baseline gap-x-2; list-style-type: none; } } // Pre tag is the parent wrapper for Code block pre { border-color: #d0d5dd; border: 1px; color: black; font-family: 'JetBrainsMono', monospace; padding: 1rem; border-radius: 0.5rem; @apply overflow-auto mt-3 bg-gray-100; code { @apply !px-0; } } code { @apply rounded-md px-2 py-1 bg-gray-100; color: inherit; font-size: 0.8rem; } h1 { font-weight: 700; font-size: 1.85rem; margin-bottom: 0.1rem; } h2 { font-weight: 600; font-size: 1.55rem; margin-bottom: 0.1em; } h3 { font-weight: 600; font-size: 1.15rem; margin-bottom: 0.1em; } } </style>
packages/nc-gui/components/cell/RichText.vue
1
https://github.com/nocodb/nocodb/commit/f69391c0943d577049a8b484d88d0d94df137245
[ 0.9989301562309265, 0.2196030467748642, 0.000169955994351767, 0.00017603812739253044, 0.41051948070526123 ]
{ "id": 0, "code_window": [ "const props = defineProps<{\n", " value?: string | null\n", " readonly?: boolean\n", " syncValueChange?: boolean\n", " showMenu?: boolean\n", "}>()\n", "\n", "const emits = defineEmits(['update:value'])\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " fullMode?: boolean\n" ], "file_path": "packages/nc-gui/components/cell/RichText.vue", "type": "add", "edit_start_line_idx": 16 }
import type { BoolType, HookReqType, HookType } from 'nocodb-sdk'; import Model from '~/models/Model'; import Filter from '~/models/Filter'; import HookFilter from '~/models/HookFilter'; import { CacheDelDirection, CacheGetType, CacheScope, MetaTable, } from '~/utils/globals'; import Noco from '~/Noco'; import NocoCache from '~/cache/NocoCache'; import { extractProps } from '~/helpers/extractProps'; import { NcError } from '~/helpers/catchError'; export default class Hook implements HookType { id?: string; fk_model_id?: string; title?: string; description?: string; env?: string; type?: string; event?: HookType['event']; operation?: HookType['operation']; async?: BoolType; payload?: string; url?: string; headers?: string; condition?: BoolType; notification?: string | Record<string, any>; retries?: number; retry_interval?: number; timeout?: number; active?: BoolType; base_id?: string; source_id?: string; version?: 'v1' | 'v2'; constructor(hook: Partial<Hook | HookReqType>) { Object.assign(this, hook); } public static async get(hookId: string, ncMeta = Noco.ncMeta) { let hook = hookId && (await NocoCache.get( `${CacheScope.HOOK}:${hookId}`, CacheGetType.TYPE_OBJECT, )); if (!hook) { hook = await ncMeta.metaGet2(null, null, MetaTable.HOOKS, hookId); await NocoCache.set(`${CacheScope.HOOK}:${hookId}`, hook); } return hook && new Hook(hook); } public async getFilters(ncMeta = Noco.ncMeta) { return await Filter.rootFilterListByHook({ hookId: this.id }, ncMeta); } // public static async insert(hook: Partial<Hook>) { // const { id } = await ncMeta.metaInsert2(null, null, MetaTable.HOOKS, { // // user: hook.user, // // ip: hook.ip, // // source_id: hook.source_id, // // base_id: hook.base_id, // // row_id: hook.row_id, // // fk_model_id: hook.fk_model_id, // // op_type: hook.op_type, // // op_sub_type: hook.op_sub_type, // // status: hook.status, // // description: hook.description, // // details: hook.details // }); // // return this.get(id); // } static async list( param: { fk_model_id: string; event?: HookType['event']; operation?: HookType['operation']; }, ncMeta = Noco.ncMeta, ) { const cachedList = await NocoCache.getList(CacheScope.HOOK, [ param.fk_model_id, ]); let { list: hooks } = cachedList; const { isNoneList } = cachedList; if (!isNoneList && !hooks.length) { hooks = await ncMeta.metaList(null, null, MetaTable.HOOKS, { condition: { fk_model_id: param.fk_model_id, // ...(param.event ? { event: param.event?.toLowerCase?.() } : {}), // ...(param.operation // ? { operation: param.operation?.toLowerCase?.() } // : {}) }, orderBy: { created_at: 'asc', }, }); await NocoCache.setList(CacheScope.HOOK, [param.fk_model_id], hooks); } // filter event & operation if (param.event) { hooks = hooks.filter( (h) => h.event?.toLowerCase() === param.event?.toLowerCase(), ); } if (param.operation) { hooks = hooks.filter( (h) => h.operation?.toLowerCase() === param.operation?.toLowerCase(), ); } return hooks?.map((h) => new Hook(h)); } public static async insert(hook: Partial<Hook>, ncMeta = Noco.ncMeta) { const insertObj = extractProps(hook, [ 'fk_model_id', 'title', 'description', 'env', 'type', 'event', 'operation', 'async', 'url', 'headers', 'condition', 'notification', 'retries', 'retry_interval', 'timeout', 'active', 'base_id', 'source_id', ]); if (insertObj.notification && typeof insertObj.notification === 'object') { insertObj.notification = JSON.stringify(insertObj.notification); } if (!(hook.base_id && hook.source_id)) { const model = await Model.getByIdOrName({ id: hook.fk_model_id }, ncMeta); insertObj.base_id = model.base_id; insertObj.source_id = model.source_id; } // new hook will set as version 2 insertObj.version = 'v2'; const { id } = await ncMeta.metaInsert2( null, null, MetaTable.HOOKS, insertObj, ); await NocoCache.appendToList( CacheScope.HOOK, [hook.fk_model_id], `${CacheScope.HOOK}:${id}`, ); return this.get(id, ncMeta); } public static async update( hookId: string, hook: Partial<Hook>, ncMeta = Noco.ncMeta, ) { const updateObj = extractProps(hook, [ 'title', 'description', 'env', 'type', 'event', 'operation', 'async', 'payload', 'url', 'headers', 'condition', 'notification', 'retries', 'retry_interval', 'timeout', 'active', 'version', ]); if ( updateObj.version && updateObj.operation && updateObj.version === 'v1' && ['bulkInsert', 'bulkUpdate', 'bulkDelete'].includes(updateObj.operation) ) { NcError.badRequest(`${updateObj.operation} not supported in v1 hook`); } if (updateObj.notification && typeof updateObj.notification === 'object') { updateObj.notification = JSON.stringify(updateObj.notification); } // get existing cache const key = `${CacheScope.HOOK}:${hookId}`; let o = await NocoCache.get(key, CacheGetType.TYPE_OBJECT); if (o) { // update data o = { ...o, ...updateObj }; // replace notification o.notification = updateObj.notification; // set cache await NocoCache.set(key, o); } // set meta await ncMeta.metaUpdate(null, null, MetaTable.HOOKS, updateObj, hookId); return this.get(hookId, ncMeta); } static async delete(hookId: any, ncMeta = Noco.ncMeta) { // Delete Hook Filters const filterList = await ncMeta.metaList2( null, null, MetaTable.FILTER_EXP, { condition: { fk_hook_id: hookId }, }, ); for (const filter of filterList) { await NocoCache.deepDel( CacheScope.FILTER_EXP, `${CacheScope.FILTER_EXP}:${filter.id}`, CacheDelDirection.CHILD_TO_PARENT, ); await HookFilter.delete(filter.id); } // Delete Hook await NocoCache.deepDel( CacheScope.HOOK, `${CacheScope.HOOK}:${hookId}`, CacheDelDirection.CHILD_TO_PARENT, ); return await ncMeta.metaDelete(null, null, MetaTable.HOOKS, hookId); } }
packages/nocodb/src/models/Hook.ts
0
https://github.com/nocodb/nocodb/commit/f69391c0943d577049a8b484d88d0d94df137245
[ 0.0012093327241018414, 0.00021270800789352506, 0.00016704814333934337, 0.0001732046075630933, 0.00019933984731324017 ]
{ "id": 0, "code_window": [ "const props = defineProps<{\n", " value?: string | null\n", " readonly?: boolean\n", " syncValueChange?: boolean\n", " showMenu?: boolean\n", "}>()\n", "\n", "const emits = defineEmits(['update:value'])\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " fullMode?: boolean\n" ], "file_path": "packages/nc-gui/components/cell/RichText.vue", "type": "add", "edit_start_line_idx": 16 }
<% const { apiConfig, generateResponses, config } = it; %> export type QueryParamsType = Record<string | number, any>; export type ResponseFormat = keyof Omit<Body, "body" | "bodyUsed">; export interface FullRequestParams extends Omit<RequestInit, "body"> { /** set parameter to `true` for call `securityWorker` for this request */ secure?: boolean; /** request path */ path: string; /** content type of request body */ type?: ContentType; /** query params */ query?: QueryParamsType; /** format of response (i.e. response.json() -> format: "json") */ format?: ResponseFormat; /** request body */ body?: unknown; /** base url */ baseUrl?: string; /** request cancellation token */ cancelToken?: CancelToken; } export type RequestParams = Omit<FullRequestParams, "body" | "method" | "path"> export interface ApiConfig<SecurityDataType = unknown> { baseUrl?: string; baseApiParams?: Omit<RequestParams, "baseUrl" | "cancelToken" | "signal">; securityWorker?: (securityData: SecurityDataType | null) => Promise<RequestParams | void> | RequestParams | void; customFetch?: typeof fetch; } export interface HttpResponse<D extends unknown, E extends unknown = unknown> extends Response { data: D; error: E; } type CancelToken = Symbol | string | number; export enum ContentType { Json = "application/json", FormData = "multipart/form-data", UrlEncoded = "application/x-www-form-urlencoded", } export class HttpClient<SecurityDataType = unknown> { public baseUrl: string = "<%~ apiConfig.baseUrl %>"; private securityData: SecurityDataType | null = null; private securityWorker?: ApiConfig<SecurityDataType>["securityWorker"]; private abortControllers = new Map<CancelToken, AbortController>(); private customFetch = (...fetchParams: Parameters<typeof fetch>) => fetch(...fetchParams); private baseApiParams: RequestParams = { credentials: 'same-origin', headers: {}, redirect: 'follow', referrerPolicy: 'no-referrer', } constructor(apiConfig: ApiConfig<SecurityDataType> = {}) { Object.assign(this, apiConfig); } public setSecurityData = (data: SecurityDataType | null) => { this.securityData = data; } private encodeQueryParam(key: string, value: any) { const encodedKey = encodeURIComponent(key); return `${encodedKey}=${encodeURIComponent(typeof value === "number" ? value : `${value}`)}`; } private addQueryParam(query: QueryParamsType, key: string) { return this.encodeQueryParam(key, query[key]); } private addArrayQueryParam(query: QueryParamsType, key: string) { const value = query[key]; return value.map((v: any) => this.encodeQueryParam(key, v)).join("&"); } protected toQueryString(rawQuery?: QueryParamsType): string { const query = rawQuery || {}; const keys = Object.keys(query).filter((key) => "undefined" !== typeof query[key]); return keys .map((key) => Array.isArray(query[key]) ? this.addArrayQueryParam(query, key) : this.addQueryParam(query, key), ) .join("&"); } protected addQueryParams(rawQuery?: QueryParamsType): string { const queryString = this.toQueryString(rawQuery); return queryString ? `?${queryString}` : ""; } private contentFormatters: Record<ContentType, (input: any) => any> = { [ContentType.Json]: (input:any) => input !== null && (typeof input === "object" || typeof input === "string") ? JSON.stringify(input) : input, [ContentType.FormData]: (input: any) => Object.keys(input || {}).reduce((formData, key) => { const property = input[key]; formData.append( key, property instanceof Blob ? property : typeof property === "object" && property !== null ? JSON.stringify(property) : `${property}` ); return formData; }, new FormData()), [ContentType.UrlEncoded]: (input: any) => this.toQueryString(input), } private mergeRequestParams(params1: RequestParams, params2?: RequestParams): RequestParams { return { ...this.baseApiParams, ...params1, ...(params2 || {}), headers: { ...(this.baseApiParams.headers || {}), ...(params1.headers || {}), ...((params2 && params2.headers) || {}), }, }; } private createAbortSignal = (cancelToken: CancelToken): AbortSignal | undefined => { if (this.abortControllers.has(cancelToken)) { const abortController = this.abortControllers.get(cancelToken); if (abortController) { return abortController.signal; } return void 0; } const abortController = new AbortController(); this.abortControllers.set(cancelToken, abortController); return abortController.signal; } public abortRequest = (cancelToken: CancelToken) => { const abortController = this.abortControllers.get(cancelToken) if (abortController) { abortController.abort(); this.abortControllers.delete(cancelToken); } } public request = async <T = any, E = any>({ body, secure, path, type, query, format, baseUrl, cancelToken, ...params <% if (config.unwrapResponseData) { %> }: FullRequestParams): Promise<T> => { <% } else { %> }: FullRequestParams): Promise<HttpResponse<T, E>> => { <% } %> const secureParams = ((typeof secure === 'boolean' ? secure : this.baseApiParams.secure) && this.securityWorker && await this.securityWorker(this.securityData)) || {}; const requestParams = this.mergeRequestParams(params, secureParams); const queryString = query && this.toQueryString(query); const payloadFormatter = this.contentFormatters[type || ContentType.Json]; const responseFormat = format || requestParams.format; return this.customFetch( `${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`, { ...requestParams, headers: { ...(type && type !== ContentType.FormData ? { "Content-Type": type } : {}), ...(requestParams.headers || {}), }, signal: cancelToken ? this.createAbortSignal(cancelToken) : void 0, body: typeof body === "undefined" || body === null ? null : payloadFormatter(body), } ).then(async (response) => { const r = response as HttpResponse<T, E>; r.data = (null as unknown) as T; r.error = (null as unknown) as E; const data = !responseFormat ? r : await response[responseFormat]() .then((data) => { if (r.ok) { r.data = data; } else { r.error = data; } return r; }) .catch((e) => { r.error = e; return r; }); if (cancelToken) { this.abortControllers.delete(cancelToken); } if (!response.ok) throw data; <% if (config.unwrapResponseData) { %> return data.data; <% } else { %> return data; <% } %> }); }; }
scripts/sdk/templates/http-clients/fetch-http-client.eta
0
https://github.com/nocodb/nocodb/commit/f69391c0943d577049a8b484d88d0d94df137245
[ 0.00017623137682676315, 0.000170879575307481, 0.00016358600987587124, 0.00017124399892054498, 0.0000031188842513074633 ]
{ "id": 0, "code_window": [ "const props = defineProps<{\n", " value?: string | null\n", " readonly?: boolean\n", " syncValueChange?: boolean\n", " showMenu?: boolean\n", "}>()\n", "\n", "const emits = defineEmits(['update:value'])\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " fullMode?: boolean\n" ], "file_path": "packages/nc-gui/components/cell/RichText.vue", "type": "add", "edit_start_line_idx": 16 }
import { Page, selectors } from '@playwright/test'; import axios, { AxiosResponse } from 'axios'; import { Api, BaseType, ProjectListType, ProjectTypes, UserType, WorkspaceType } from 'nocodb-sdk'; import { getDefaultPwd } from '../tests/utils/general'; import { Knex, knex } from 'knex'; import { promises as fs } from 'fs'; import { isEE } from './db'; import { resetSakilaPg } from './knexHelper'; import path from 'path'; // MySQL Configuration const mysqlConfig = { client: 'mysql2', connection: { host: 'localhost', port: 3306, user: 'root', password: 'password', database: 'sakila', multipleStatements: true, dateStrings: true, }, }; const extMysqlProject = (title, parallelId) => ({ title, sources: [ { type: 'mysql2', config: { client: 'mysql2', connection: { host: 'localhost', port: '3306', user: 'root', password: 'password', database: `test_sakila_${parallelId}`, }, }, inflection_column: 'camelize', inflection_table: 'camelize', }, ], external: true, }); // PG Configuration // const pgConfig = { client: 'pg', connection: { host: 'localhost', port: 5432, user: 'postgres', password: 'password', database: 'postgres', multipleStatements: true, }, searchPath: ['public', 'information_schema'], pool: { min: 0, max: 1 }, }; // Sakila Knex Configuration // const sakilaKnexConfig = (parallelId: string) => ({ ...pgConfig, connection: { ...pgConfig.connection, database: `sakila${parallelId}`, }, pool: { min: 0, max: 1 }, }); // External PG Base create payload // const extPgProject = (workspaceId, title, parallelId, baseType) => ({ fk_workspace_id: workspaceId, title, type: baseType, sources: [ { type: 'pg', config: { client: 'pg', connection: { host: 'localhost', port: '5432', user: 'postgres', password: 'password', database: `sakila${parallelId}`, }, searchPath: ['public'], }, inflection_column: 'camelize', inflection_table: 'camelize', }, ], external: true, }); const extPgProjectCE = (title, parallelId) => ({ title, sources: [ { type: 'pg', config: { client: 'pg', connection: { host: 'localhost', port: '5432', user: 'postgres', password: 'password', database: `sakila${parallelId}`, }, searchPath: ['public'], }, inflection_column: 'camelize', inflection_table: 'camelize', }, ], external: true, }); const extSQLiteProjectCE = (title: string, workerId: string) => ({ title, sources: [ { type: 'sqlite3', config: { client: 'sqlite3', connection: { client: 'sqlite3', connection: { filename: sqliteFilePath(workerId), database: 'test_sakila', multipleStatements: true, }, }, }, inflection_column: 'camelize', inflection_table: 'camelize', }, ], external: true, }); const workerCount = [0, 0, 0, 0, 0, 0, 0, 0]; export interface NcContext { base: BaseType; token: string; dbType?: string; workerId?: string; rootUser: UserType & { password: string }; workspace: WorkspaceType; defaultProjectTitle: string; defaultTableTitle: string; } selectors.setTestIdAttribute('data-testid'); const sqliteFilePath = (workerId: string) => { const rootDir = process.cwd(); return `${rootDir}/../../packages/nocodb/test_sakila_${workerId}.db`; }; async function localInit({ workerId, isEmptyProject = false, baseType = ProjectTypes.DATABASE, isSuperUser = false, dbType, }: { workerId: string; isEmptyProject?: boolean; baseType?: ProjectTypes; isSuperUser?: boolean; dbType?: string; }) { const parallelId = process.env.TEST_PARALLEL_INDEX; try { let response: AxiosResponse<any, any>; // Login as root user if (isSuperUser && !isEE()) { // required for configuring license key settings response = await axios.post('http://localhost:8080/api/v1/auth/user/signin', { email: `[email protected]`, password: getDefaultPwd(), }); } else { response = await axios.post('http://localhost:8080/api/v1/auth/user/signin', { email: `user-${parallelId}@nocodb.com`, password: getDefaultPwd(), }); } const token = response.data.token; // Init SDK using token const api = new Api({ baseURL: `http://localhost:8080/`, headers: { 'xc-auth': token, }, }); // const workspaceTitle_old = `ws_pgExtREST${+workerId - 1}`; const workspaceTitle = `ws_pgExtREST${workerId}`; const baseTitle = `pgExtREST${workerId}`; // console.log(process.env.TEST_WORKER_INDEX, process.env.TEST_PARALLEL_INDEX); if (isEE() && api['workspace']) { // Delete associated workspace // Note that: on worker error, entire thread is reset & worker ID numbering is reset too // Hence, workspace delete is based on workerId prefix instead of just workerId const ws = await api['workspace'].list(); for (const w of ws.list) { // check if w.title starts with workspaceTitle if (w.title.startsWith(`ws_pgExtREST${process.env.TEST_PARALLEL_INDEX}`)) { try { const bases = await api.workspaceBase.list(w.id); for (const base of bases.list) { try { await api.base.delete(base.id); } catch (e) { console.log(`Error deleting base: ws delete`, base); } } await api['workspace'].delete(w.id); } catch (e) { console.log(`Error deleting workspace: ${w.id}`, `user-${parallelId}@nocodb.com`, isSuperUser); } } } } else { let bases: ProjectListType; try { bases = await api.base.list(); } catch (e) { console.log('Error fetching bases', e); } if (bases) { for (const p of bases.list) { // check if p.title starts with baseTitle if ( p.title.startsWith(`pgExtREST${process.env.TEST_PARALLEL_INDEX}`) || p.title.startsWith(`xcdb_p${process.env.TEST_PARALLEL_INDEX}`) ) { try { await api.base.delete(p.id); } catch (e) { console.log(`Error deleting base: ${p.id}`, `user-${parallelId}@nocodb.com`, isSuperUser); } } } } } // DB reset if (dbType === 'pg' && !isEmptyProject) { await resetSakilaPg(`sakila${workerId}`); } else if (dbType === 'sqlite') { if (await fs.stat(sqliteFilePath(parallelId)).catch(() => null)) { await fs.unlink(sqliteFilePath(parallelId)); } if (!isEmptyProject) { const testsDir = path.join(process.cwd(), '../../packages/nocodb/tests'); await fs.copyFile(`${testsDir}/sqlite-sakila-db/sakila.db`, sqliteFilePath(parallelId)); } } else if (dbType === 'mysql') { const nc_knex = knex(mysqlConfig); try { await nc_knex.raw(`USE test_sakila_${parallelId}`); } catch (e) { await nc_knex.raw(`CREATE DATABASE test_sakila_${parallelId}`); await nc_knex.raw(`USE test_sakila_${parallelId}`); } if (!isEmptyProject) { await resetSakilaMysql(nc_knex, parallelId, isEmptyProject); } } let workspace; if (isEE() && api['workspace']) { // create a new workspace workspace = await api['workspace'].create({ title: workspaceTitle, }); } let base; if (isEE()) { if (isEmptyProject) { // create a new base under the workspace we just created base = await api.base.create({ title: baseTitle, fk_workspace_id: workspace.id, type: baseType, }); } else { if ('id' in workspace) { // @ts-ignore base = await api.base.create(extPgProject(workspace.id, baseTitle, workerId, baseType)); } } } else { if (isEmptyProject) { // create a new base base = await api.base.create({ title: baseTitle, }); } else { try { base = await api.base.create( dbType === 'pg' ? extPgProjectCE(baseTitle, workerId) : dbType === 'sqlite' ? extSQLiteProjectCE(baseTitle, parallelId) : extMysqlProject(baseTitle, parallelId) ); } catch (e) { console.log(`Error creating base: ${baseTitle}`); } } } // get current user information const user = await api.auth.me(); return { data: { base, user, workspace, token }, status: 200 }; } catch (e) { console.error(`Error resetting base: ${process.env.TEST_PARALLEL_INDEX}`, e); return { data: {}, status: 500 }; } } const setup = async ({ baseType = ProjectTypes.DATABASE, page, isEmptyProject = false, isSuperUser = false, url, }: { baseType?: ProjectTypes; page: Page; isEmptyProject?: boolean; isSuperUser?: boolean; url?: string; }): Promise<NcContext> => { console.time('Setup'); let dbType = process.env.CI ? process.env.E2E_DB_TYPE : process.env.E2E_DEV_DB_TYPE; dbType = dbType || (isEE() ? 'pg' : 'sqlite'); let response; const workerIndex = process.env.TEST_WORKER_INDEX; const parallelIndex = process.env.TEST_PARALLEL_INDEX; const workerId = parallelIndex; // console.log(process.env.TEST_PARALLEL_INDEX, '#Setup', workerId); try { // Localised reset logic response = await localInit({ workerId: parallelIndex, isEmptyProject, baseType, isSuperUser, dbType, }); } catch (e) { console.error(`Error resetting base: ${process.env.TEST_PARALLEL_INDEX}`, e); } if (response.status !== 200 || !response.data?.token || !response.data?.base) { console.error('Failed to reset test data', response.data, response.status, dbType); throw new Error('Failed to reset test data'); } const token = response.data.token; try { const admin = await axios.post('http://localhost:8080/api/v1/auth/user/signin', { email: `[email protected]`, password: getDefaultPwd(), }); if (!isEE()) await axios.post( `http://localhost:8080/api/v1/license`, { key: '' }, { headers: { 'xc-auth': admin.data.token } } ); } catch (e) { // ignore error: some roles will not have permission for license reset // console.error(`Error resetting base: ${process.env.TEST_PARALLEL_INDEX}`, e); } await page.addInitScript( async ({ token }) => { try { let initialLocalStorage = {}; try { initialLocalStorage = JSON.parse(localStorage.getItem('nocodb-gui-v2') || '{}'); } catch (e) { console.error('Failed to parse local storage', e); } window.localStorage.setItem( 'nocodb-gui-v2', JSON.stringify({ ...initialLocalStorage, token: token, }) ); } catch (e) { window.console.log('initialLocalStorage error'); } }, { token: token } ); const base = response.data.base; const rootUser = { ...response.data.user, password: getDefaultPwd() }; const workspace = response.data.workspace; // default landing page for tests let baseUrl; if (isEE()) { switch (base.type) { case ProjectTypes.DOCUMENTATION: baseUrl = url ? url : `/#/${base.fk_workspace_id}/${base.id}/doc`; break; case ProjectTypes.DATABASE: baseUrl = url ? url : `/#/${base.fk_workspace_id}/${base.id}`; break; default: throw new Error(`Unknown base type: ${base.type}`); } } else { // sample: http://localhost:3000/#/ws/default/base/pdknlfoc5e7bx4w baseUrl = url ? url : `/#/nc/${base.id}`; } await page.goto(baseUrl, { waitUntil: 'networkidle' }); console.timeEnd('Setup'); return { base, token, dbType, workerId, rootUser, workspace, defaultProjectTitle: 'Getting Started', defaultTableTitle: 'Features', } as NcContext; }; export const unsetup = async (context: NcContext): Promise<void> => {}; // Reference // packages/nocodb/src/lib/services/test/TestResetService/resetPgSakilaProject.ts const resetSakilaMysql = async (knex: Knex, parallelId: string, isEmptyProject: boolean) => { const testsDir = path.join(process.cwd(), '/../../packages/nocodb/tests'); try { await knex.raw(`DROP DATABASE test_sakila_${parallelId}`); } catch (e) { console.log('Error dropping db', e); } await knex.raw(`CREATE DATABASE test_sakila_${parallelId}`); if (isEmptyProject) return; const trx = await knex.transaction(); try { const schemaFile = await fs.readFile(`${testsDir}/mysql-sakila-db/03-test-sakila-schema.sql`); const dataFile = await fs.readFile(`${testsDir}/mysql-sakila-db/04-test-sakila-data.sql`); await trx.raw(schemaFile.toString().replace(/test_sakila/g, `test_sakila_${parallelId}`)); await trx.raw(dataFile.toString().replace(/test_sakila/g, `test_sakila_${parallelId}`)); await trx.commit(); } catch (e) { console.log('Error resetting mysql db', e); await trx.rollback(e); } }; // General purpose API based routines // export default setup;
tests/playwright/setup/index.ts
0
https://github.com/nocodb/nocodb/commit/f69391c0943d577049a8b484d88d0d94df137245
[ 0.0001779591548256576, 0.00017246586503461003, 0.00016739156853873283, 0.00017224137263838202, 0.000002484981223460636 ]
{ "id": 1, "code_window": [ " setTimeout(() => {\n", " editor.value?.chain().focus().run()\n", " }, 50)\n", "})\n", "</script>\n", "\n", "<template>\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", "const focusEditorEnd = () => {\n", " setTimeout(() => {\n", " if (!editor.value) return\n", " const docSize = editor.value.state.doc.content.size\n", "\n", " editor.value\n", " ?.chain()\n", " .setTextSelection(docSize - 2)\n", " .focus()\n", " .run()\n", " }, 50)\n", "}\n" ], "file_path": "packages/nc-gui/components/cell/RichText.vue", "type": "add", "edit_start_line_idx": 76 }
<script lang="ts" setup> import StarterKit from '@tiptap/starter-kit' import TaskItem from '@tiptap/extension-task-item' import TaskList from '@tiptap/extension-task-list' import { EditorContent, useEditor } from '@tiptap/vue-3' import TurndownService from 'turndown' import { parse } from 'marked' import { generateJSON } from '@tiptap/html' import Underline from '@tiptap/extension-underline' import { Link } from '@/helpers/dbTiptapExtensions/links' const props = defineProps<{ value?: string | null readonly?: boolean syncValueChange?: boolean showMenu?: boolean }>() const emits = defineEmits(['update:value']) const turndownService = new TurndownService() const editorDom = ref<HTMLElement | null>(null) const vModel = useVModel(props, 'value', emits, { defaultValue: '' }) const tiptapExtensions = [ StarterKit, TaskList, TaskItem.configure({ nested: true, }), Underline, Link, ] const editor = useEditor({ extensions: tiptapExtensions, onUpdate: ({ editor }) => { const markdown = turndownService.turndown(editor.getHTML()) vModel.value = markdown }, editable: !props.readonly, }) const setEditorContent = (contentMd: any) => { if (!editor.value) return ;(editor.value.state as any).history$.prevRanges = null ;(editor.value.state as any).history$.done.eventCount = 0 const selection = editor.value.view.state.selection const contentHtml = contentMd ? parse(contentMd) : '<p></p>' const content = generateJSON(contentHtml, tiptapExtensions) editor.value.chain().setContent(content).setTextSelection(selection.to).run() } if (props.syncValueChange) { watch(vModel, () => { setEditorContent(vModel.value) }) } watch(editorDom, () => { if (!editorDom.value) return setEditorContent(vModel.value) // Focus editor after editor is mounted setTimeout(() => { editor.value?.chain().focus().run() }, 50) }) </script> <template> <div class="h-full"> <div v-if="props.showMenu" class="absolute top-1 z-1000 right-3"> <CellRichTextSelectedBubbleMenu v-if="editor" :editor="editor" embed-mode /> </div> <CellRichTextSelectedBubbleMenuPopup v-if="editor" :editor="editor" /> <CellRichTextLinkOptions v-if="editor" :editor="editor" /> <EditorContent ref="editorDom" :editor="editor" class="nc-textarea-rich w-full h-full nc-text-rich-scroll nc-scrollbar-md" /> </div> </template> <style lang="scss"> .nc-text-rich-scroll { &::-webkit-scrollbar-thumb { @apply bg-transparent; } } .nc-text-rich-scroll:hover { &::-webkit-scrollbar-thumb { @apply bg-gray-200; } } .nc-textarea-rich { .ProseMirror-focused { // remove all border outline: none; } p { @apply !mb-1; } ul { @apply ml-4; li { list-style-type: disc; } } ol { @apply -ml-6; li { list-style-type: decimal; } } ul[data-type='taskList'] { @apply ml-0; li { @apply flex flex-row items-baseline gap-x-2; list-style-type: none; } } // Pre tag is the parent wrapper for Code block pre { border-color: #d0d5dd; border: 1px; color: black; font-family: 'JetBrainsMono', monospace; padding: 1rem; border-radius: 0.5rem; @apply overflow-auto mt-3 bg-gray-100; code { @apply !px-0; } } code { @apply rounded-md px-2 py-1 bg-gray-100; color: inherit; font-size: 0.8rem; } h1 { font-weight: 700; font-size: 1.85rem; margin-bottom: 0.1rem; } h2 { font-weight: 600; font-size: 1.55rem; margin-bottom: 0.1em; } h3 { font-weight: 600; font-size: 1.15rem; margin-bottom: 0.1em; } } </style>
packages/nc-gui/components/cell/RichText.vue
1
https://github.com/nocodb/nocodb/commit/f69391c0943d577049a8b484d88d0d94df137245
[ 0.9846749305725098, 0.05514649301767349, 0.00016621904796920717, 0.00017276519793085754, 0.2254447638988495 ]
{ "id": 1, "code_window": [ " setTimeout(() => {\n", " editor.value?.chain().focus().run()\n", " }, 50)\n", "})\n", "</script>\n", "\n", "<template>\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", "const focusEditorEnd = () => {\n", " setTimeout(() => {\n", " if (!editor.value) return\n", " const docSize = editor.value.state.doc.content.size\n", "\n", " editor.value\n", " ?.chain()\n", " .setTextSelection(docSize - 2)\n", " .focus()\n", " .run()\n", " }, 50)\n", "}\n" ], "file_path": "packages/nc-gui/components/cell/RichText.vue", "type": "add", "edit_start_line_idx": 76 }
<script lang="ts" setup> import { useTitle } from '@vueuse/core' import { useI18n, useRoute, useSidebar } from '#imports' const route = useRoute() const { te, t } = useI18n() const { hasSidebar } = useSidebar('nc-left-sidebar') const refreshSidebar = ref(false) const sidebarReady = ref(false) useTitle(route.meta?.title && te(route.meta.title) ? `${t(route.meta.title)}` : 'NocoDB') watch(hasSidebar, (val) => { if (!val) { refreshSidebar.value = true nextTick(() => { refreshSidebar.value = false }) } }) onMounted(() => { until(() => document.querySelector('#nc-sidebar-left')) .toBeTruthy() .then(() => { sidebarReady.value = true }) }) </script> <script lang="ts"> export default { name: 'DefaultLayout', } </script> <template> <div class="w-full h-full"> <Teleport v-if="sidebarReady" :to="hasSidebar ? '#nc-sidebar-left' : null" :disabled="!hasSidebar"> <slot v-if="!refreshSidebar" name="sidebar" /> </Teleport> <a-layout-content> <slot /> </a-layout-content> </div> </template>
packages/nc-gui/layouts/default.vue
0
https://github.com/nocodb/nocodb/commit/f69391c0943d577049a8b484d88d0d94df137245
[ 0.001705703791230917, 0.00043159082997590303, 0.0001660656853346154, 0.00017485549324192107, 0.0005698890308849514 ]
{ "id": 1, "code_window": [ " setTimeout(() => {\n", " editor.value?.chain().focus().run()\n", " }, 50)\n", "})\n", "</script>\n", "\n", "<template>\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", "const focusEditorEnd = () => {\n", " setTimeout(() => {\n", " if (!editor.value) return\n", " const docSize = editor.value.state.doc.content.size\n", "\n", " editor.value\n", " ?.chain()\n", " .setTextSelection(docSize - 2)\n", " .focus()\n", " .run()\n", " }, 50)\n", "}\n" ], "file_path": "packages/nc-gui/components/cell/RichText.vue", "type": "add", "edit_start_line_idx": 76 }
<script setup lang="ts"> // TODO: </script> <template>Stars</template>
packages/nc-gui/components/profile/stars.vue
0
https://github.com/nocodb/nocodb/commit/f69391c0943d577049a8b484d88d0d94df137245
[ 0.00025660195387899876, 0.00025660195387899876, 0.00025660195387899876, 0.00025660195387899876, 0 ]
{ "id": 1, "code_window": [ " setTimeout(() => {\n", " editor.value?.chain().focus().run()\n", " }, 50)\n", "})\n", "</script>\n", "\n", "<template>\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", "const focusEditorEnd = () => {\n", " setTimeout(() => {\n", " if (!editor.value) return\n", " const docSize = editor.value.state.doc.content.size\n", "\n", " editor.value\n", " ?.chain()\n", " .setTextSelection(docSize - 2)\n", " .focus()\n", " .run()\n", " }, 50)\n", "}\n" ], "file_path": "packages/nc-gui/components/cell/RichText.vue", "type": "add", "edit_start_line_idx": 76 }
<script setup lang="ts"> const workspaceStore = useWorkspace() const { isLeftSidebarOpen } = storeToRefs(useSidebarStore()) const { activeWorkspace, isWorkspaceLoading } = storeToRefs(workspaceStore) const { activeViewTitleOrId } = storeToRefs(useViewsStore()) const { activeTableId } = storeToRefs(useTablesStore()) const { isMobileMode } = useGlobal() const showSidebarBtn = computed(() => !(isMobileMode.value && !activeViewTitleOrId.value && !activeTableId.value)) </script> <template> <div class="flex items-center nc-sidebar-header w-full border-b-1 border-gray-200 group md:(px-2 py-1.2) xs:(px-1 py-1)" :data-workspace-title="activeWorkspace?.title" style="height: var(--topbar-height)" > <div v-if="!isWorkspaceLoading" class="flex flex-row items-center w-full"> <WorkspaceMenu /> <div class="flex flex-grow min-w-1"></div> <NcTooltip class="flex" :class="{ '!opacity-100': !isLeftSidebarOpen, }" placement="bottom" hide-on-click > <template #title> {{ isLeftSidebarOpen ? `${$t('title.hideSidebar')}` : `${$t('title.showSidebar')}` }} </template> <NcButton v-if="showSidebarBtn" v-e="['c:leftSidebar:hideToggle']" :type="isMobileMode ? 'secondary' : 'text'" :size="isMobileMode ? 'medium' : 'small'" class="nc-sidebar-left-toggle-icon !text-gray-700 !hover:text-gray-800 !xs:(h-10.5 max-h-10.5 max-w-10.5) !md:(hover:bg-gray-200)" @click="isLeftSidebarOpen = !isLeftSidebarOpen" > <div class="flex items-center text-inherit"> <GeneralIcon v-if="isMobileMode" icon="close" /> <GeneralIcon v-else icon="doubleLeftArrow" class="duration-150 transition-all !text-lg -mt-0.5" :class="{ 'transform rotate-180': !isLeftSidebarOpen, }" /> </div> </NcButton> </NcTooltip> </div> <div v-else class="flex flex-row items-center w-full mt-0.25 ml-2.5 gap-x-3"> <a-skeleton-input :active="true" class="!w-6 !h-6 !rounded overflow-hidden" /> <a-skeleton-input :active="true" class="!w-40 !h-6 !rounded overflow-hidden" /> </div> </div> </template>
packages/nc-gui/components/dashboard/Sidebar/Header.vue
0
https://github.com/nocodb/nocodb/commit/f69391c0943d577049a8b484d88d0d94df137245
[ 0.0005802706000395119, 0.00026515545323491096, 0.00016759040590841323, 0.00017057699733413756, 0.000144107747473754 ]
{ "id": 2, "code_window": [ "</script>\n", "\n", "<template>\n", " <div class=\"h-full\">\n", " <div v-if=\"props.showMenu\" class=\"absolute top-1 z-1000 right-3\">\n", " <CellRichTextSelectedBubbleMenu v-if=\"editor\" :editor=\"editor\" embed-mode />\n", " </div>\n", " <CellRichTextSelectedBubbleMenuPopup v-if=\"editor\" :editor=\"editor\" />\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <div\n", " class=\"h-full\"\n", " :class=\"{\n", " 'flex flex-col flex-grow': props.fullMode,\n", " }\"\n", " >\n" ], "file_path": "packages/nc-gui/components/cell/RichText.vue", "type": "replace", "edit_start_line_idx": 79 }
<script lang="ts" setup> import StarterKit from '@tiptap/starter-kit' import TaskItem from '@tiptap/extension-task-item' import TaskList from '@tiptap/extension-task-list' import { EditorContent, useEditor } from '@tiptap/vue-3' import TurndownService from 'turndown' import { parse } from 'marked' import { generateJSON } from '@tiptap/html' import Underline from '@tiptap/extension-underline' import { Link } from '@/helpers/dbTiptapExtensions/links' const props = defineProps<{ value?: string | null readonly?: boolean syncValueChange?: boolean showMenu?: boolean }>() const emits = defineEmits(['update:value']) const turndownService = new TurndownService() const editorDom = ref<HTMLElement | null>(null) const vModel = useVModel(props, 'value', emits, { defaultValue: '' }) const tiptapExtensions = [ StarterKit, TaskList, TaskItem.configure({ nested: true, }), Underline, Link, ] const editor = useEditor({ extensions: tiptapExtensions, onUpdate: ({ editor }) => { const markdown = turndownService.turndown(editor.getHTML()) vModel.value = markdown }, editable: !props.readonly, }) const setEditorContent = (contentMd: any) => { if (!editor.value) return ;(editor.value.state as any).history$.prevRanges = null ;(editor.value.state as any).history$.done.eventCount = 0 const selection = editor.value.view.state.selection const contentHtml = contentMd ? parse(contentMd) : '<p></p>' const content = generateJSON(contentHtml, tiptapExtensions) editor.value.chain().setContent(content).setTextSelection(selection.to).run() } if (props.syncValueChange) { watch(vModel, () => { setEditorContent(vModel.value) }) } watch(editorDom, () => { if (!editorDom.value) return setEditorContent(vModel.value) // Focus editor after editor is mounted setTimeout(() => { editor.value?.chain().focus().run() }, 50) }) </script> <template> <div class="h-full"> <div v-if="props.showMenu" class="absolute top-1 z-1000 right-3"> <CellRichTextSelectedBubbleMenu v-if="editor" :editor="editor" embed-mode /> </div> <CellRichTextSelectedBubbleMenuPopup v-if="editor" :editor="editor" /> <CellRichTextLinkOptions v-if="editor" :editor="editor" /> <EditorContent ref="editorDom" :editor="editor" class="nc-textarea-rich w-full h-full nc-text-rich-scroll nc-scrollbar-md" /> </div> </template> <style lang="scss"> .nc-text-rich-scroll { &::-webkit-scrollbar-thumb { @apply bg-transparent; } } .nc-text-rich-scroll:hover { &::-webkit-scrollbar-thumb { @apply bg-gray-200; } } .nc-textarea-rich { .ProseMirror-focused { // remove all border outline: none; } p { @apply !mb-1; } ul { @apply ml-4; li { list-style-type: disc; } } ol { @apply -ml-6; li { list-style-type: decimal; } } ul[data-type='taskList'] { @apply ml-0; li { @apply flex flex-row items-baseline gap-x-2; list-style-type: none; } } // Pre tag is the parent wrapper for Code block pre { border-color: #d0d5dd; border: 1px; color: black; font-family: 'JetBrainsMono', monospace; padding: 1rem; border-radius: 0.5rem; @apply overflow-auto mt-3 bg-gray-100; code { @apply !px-0; } } code { @apply rounded-md px-2 py-1 bg-gray-100; color: inherit; font-size: 0.8rem; } h1 { font-weight: 700; font-size: 1.85rem; margin-bottom: 0.1rem; } h2 { font-weight: 600; font-size: 1.55rem; margin-bottom: 0.1em; } h3 { font-weight: 600; font-size: 1.15rem; margin-bottom: 0.1em; } } </style>
packages/nc-gui/components/cell/RichText.vue
1
https://github.com/nocodb/nocodb/commit/f69391c0943d577049a8b484d88d0d94df137245
[ 0.21118023991584778, 0.01319024246186018, 0.0001644957228563726, 0.00017156757530756295, 0.04830307886004448 ]
{ "id": 2, "code_window": [ "</script>\n", "\n", "<template>\n", " <div class=\"h-full\">\n", " <div v-if=\"props.showMenu\" class=\"absolute top-1 z-1000 right-3\">\n", " <CellRichTextSelectedBubbleMenu v-if=\"editor\" :editor=\"editor\" embed-mode />\n", " </div>\n", " <CellRichTextSelectedBubbleMenuPopup v-if=\"editor\" :editor=\"editor\" />\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <div\n", " class=\"h-full\"\n", " :class=\"{\n", " 'flex flex-col flex-grow': props.fullMode,\n", " }\"\n", " >\n" ], "file_path": "packages/nc-gui/components/cell/RichText.vue", "type": "replace", "edit_start_line_idx": 79 }
# Reverse proxy domain and cloudflare token DOMAINNAME=example.com CF_DNS_API_TOKEN=SOME_CLOUDFLARE_TOKEN # Database DATABASE_NAME=xcdb DATABASE_USER=nocodb DATABASE_PW=SECURE_PW
docker-compose/traefik/.env
0
https://github.com/nocodb/nocodb/commit/f69391c0943d577049a8b484d88d0d94df137245
[ 0.00016480281192343682, 0.00016480281192343682, 0.00016480281192343682, 0.00016480281192343682, 0 ]
{ "id": 2, "code_window": [ "</script>\n", "\n", "<template>\n", " <div class=\"h-full\">\n", " <div v-if=\"props.showMenu\" class=\"absolute top-1 z-1000 right-3\">\n", " <CellRichTextSelectedBubbleMenu v-if=\"editor\" :editor=\"editor\" embed-mode />\n", " </div>\n", " <CellRichTextSelectedBubbleMenuPopup v-if=\"editor\" :editor=\"editor\" />\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <div\n", " class=\"h-full\"\n", " :class=\"{\n", " 'flex flex-col flex-grow': props.fullMode,\n", " }\"\n", " >\n" ], "file_path": "packages/nc-gui/components/cell/RichText.vue", "type": "replace", "edit_start_line_idx": 79 }
<script lang="ts" setup> const workspaceStore = useWorkspace() const { isWorkspaceLoading } = storeToRefs(workspaceStore) const { isSharedBase } = storeToRefs(useBase()) const { isMobileMode } = useGlobal() const treeViewDom = ref<HTMLElement>() const isTreeViewOnScrollTop = ref(false) const checkScrollTopMoreThanZero = () => { if (isMobileMode.value) return if (treeViewDom.value) { if (treeViewDom.value.scrollTop > 0) { isTreeViewOnScrollTop.value = true } else { isTreeViewOnScrollTop.value = false } } return false } onMounted(() => { treeViewDom.value?.addEventListener('scroll', checkScrollTopMoreThanZero) }) onUnmounted(() => { treeViewDom.value?.removeEventListener('scroll', checkScrollTopMoreThanZero) }) </script> <template> <div class="nc-sidebar flex flex-col bg-gray-50 outline-r-1 outline-gray-100 select-none w-full h-full" :style="{ outlineWidth: '1px', }" > <div class="flex flex-col"> <DashboardSidebarHeader /> <DashboardSidebarTopSection v-if="!isSharedBase" /> </div> <div ref="treeViewDom" class="flex flex-col nc-scrollbar-dark-md flex-grow xs:(border-transparent pt-2 pr-2)" :class="{ 'border-t-1': !isSharedBase, 'border-transparent': !isTreeViewOnScrollTop, 'pt-0.25': isSharedBase, }" > <DashboardTreeView v-if="!isWorkspaceLoading" /> </div> <div v-if="!isSharedBase"> <DashboardSidebarUserInfo /> </div> </div> </template> <style lang="scss" scoped> .nc-sidebar-top-button { @apply flex flex-row mx-1 px-3.5 rounded-md items-center py-0.75 my-0.5 gap-x-2 hover:bg-gray-200 cursor-pointer; } </style>
packages/nc-gui/components/dashboard/Sidebar.vue
0
https://github.com/nocodb/nocodb/commit/f69391c0943d577049a8b484d88d0d94df137245
[ 0.0013770721852779388, 0.00035686258343048394, 0.00016708747716620564, 0.00017985780141316354, 0.0004170733445789665 ]
{ "id": 2, "code_window": [ "</script>\n", "\n", "<template>\n", " <div class=\"h-full\">\n", " <div v-if=\"props.showMenu\" class=\"absolute top-1 z-1000 right-3\">\n", " <CellRichTextSelectedBubbleMenu v-if=\"editor\" :editor=\"editor\" embed-mode />\n", " </div>\n", " <CellRichTextSelectedBubbleMenuPopup v-if=\"editor\" :editor=\"editor\" />\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <div\n", " class=\"h-full\"\n", " :class=\"{\n", " 'flex flex-col flex-grow': props.fullMode,\n", " }\"\n", " >\n" ], "file_path": "packages/nc-gui/components/cell/RichText.vue", "type": "replace", "edit_start_line_idx": 79 }
<script lang="ts" setup> import { useTitle } from '@vueuse/core' import { useI18n, useRoute, useSidebar } from '#imports' const route = useRoute() const { te, t } = useI18n() const { hasSidebar } = useSidebar('nc-left-sidebar') const refreshSidebar = ref(false) const sidebarReady = ref(false) useTitle(route.meta?.title && te(route.meta.title) ? `${t(route.meta.title)}` : 'NocoDB') watch(hasSidebar, (val) => { if (!val) { refreshSidebar.value = true nextTick(() => { refreshSidebar.value = false }) } }) onMounted(() => { until(() => document.querySelector('#nc-sidebar-left')) .toBeTruthy() .then(() => { sidebarReady.value = true }) }) </script> <script lang="ts"> export default { name: 'DefaultLayout', } </script> <template> <div class="w-full h-full"> <Teleport v-if="sidebarReady" :to="hasSidebar ? '#nc-sidebar-left' : null" :disabled="!hasSidebar"> <slot v-if="!refreshSidebar" name="sidebar" /> </Teleport> <a-layout-content> <slot /> </a-layout-content> </div> </template>
packages/nc-gui/layouts/default.vue
0
https://github.com/nocodb/nocodb/commit/f69391c0943d577049a8b484d88d0d94df137245
[ 0.001098121516406536, 0.0003439811116550118, 0.0001684529852354899, 0.0001688643533270806, 0.0003402113215997815 ]
{ "id": 3, "code_window": [ " <CellRichTextSelectedBubbleMenuPopup v-if=\"editor\" :editor=\"editor\" />\n", " <CellRichTextLinkOptions v-if=\"editor\" :editor=\"editor\" />\n", " <EditorContent ref=\"editorDom\" :editor=\"editor\" class=\"nc-textarea-rich w-full h-full nc-text-rich-scroll nc-scrollbar-md\" />\n", " </div>\n", "</template>\n", "\n", "<style lang=\"scss\">\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " <div v-if=\"props.fullMode\" class=\"flex flex-grow\" @click=\"focusEditorEnd\"></div>\n" ], "file_path": "packages/nc-gui/components/cell/RichText.vue", "type": "add", "edit_start_line_idx": 86 }
<script setup lang="ts"> import type { VNodeRef } from '@vue/runtime-core' import { ActiveCellInj, EditColumnInj, EditModeInj, IsExpandedFormOpenInj, ReadonlyInj, RowHeightInj, iconMap, inject, useVModel, } from '#imports' const props = defineProps<{ modelValue?: string | number isFocus?: boolean virtual?: boolean }>() const emits = defineEmits(['update:modelValue']) const column = inject(ColumnInj) const editEnabled = inject(EditModeInj, ref(false)) const isEditColumn = inject(EditColumnInj, ref(false)) const rowHeight = inject(RowHeightInj, ref(1 as const)) const isForm = inject(IsFormInj, ref(false)) const { showNull } = useGlobal() const vModel = useVModel(props, 'modelValue', emits, { defaultValue: '' }) const isExpandedFormOpen = inject(IsExpandedFormOpenInj, ref(false))! const focus: VNodeRef = (el) => !isExpandedFormOpen.value && !isEditColumn.value && (el as HTMLTextAreaElement)?.focus() const height = computed(() => { if (!rowHeight.value || rowHeight.value === 1) return 36 return rowHeight.value * 36 }) const isVisible = ref(false) const inputWrapperRef = ref<HTMLElement | null>(null) const inputRef = ref<HTMLTextAreaElement | null>(null) const active = inject(ActiveCellInj, ref(false)) const readOnly = inject(ReadonlyInj) watch(isVisible, () => { if (isVisible.value) { setTimeout(() => { inputRef.value?.focus() }, 100) } }) onClickOutside(inputWrapperRef, (e) => { if ((e.target as HTMLElement)?.className.includes('nc-long-text-toggle-expand')) return isVisible.value = false }) const onTextClick = () => { if (!props.virtual) return isVisible.value = true editEnabled.value = true } const isRichMode = computed(() => { let meta: any = {} if (typeof column?.value?.meta === 'string') { meta = JSON.parse(column?.value?.meta) } else { meta = column?.value?.meta ?? {} } return meta?.richMode }) watch(editEnabled, () => { if (editEnabled.value && isRichMode.value) { isVisible.value = true } }) </script> <template> <NcDropdown v-model:visible="isVisible" class="overflow-visible" :trigger="[]" placement="bottomLeft"> <div class="flex flex-row pt-0.5 w-full" :class="{ 'min-h-10': rowHeight !== 1, 'min-h-6.5': rowHeight === 1, 'h-full': isForm, }" > <div v-if="isRichMode" class="w-full" :style="{ maxHeight: `${height}px !important`, minHeight: `${height}px !important`, }" > <CellRichText v-model:value="vModel" sync-value-change readonly class="!pointer-events-none" /> </div> <textarea v-else-if="editEnabled && !isVisible" :ref="focus" v-model="vModel" rows="4" class="h-full w-full outline-none border-none" :class="{ 'p-2': editEnabled, 'py-1 h-full': isForm, 'px-1': isExpandedFormOpen, }" :style="{ minHeight: `${height}px`, }" :placeholder="isEditColumn ? $t('labels.optional') : ''" @blur="editEnabled = false" @keydown.alt.enter.stop @keydown.shift.enter.stop @keydown.down.stop @keydown.left.stop @keydown.right.stop @keydown.up.stop @keydown.delete.stop @selectstart.capture.stop @mousedown.stop /> <span v-else-if="vModel === null && showNull" class="nc-null uppercase">{{ $t('general.null') }}</span> <LazyCellClampedText v-else-if="rowHeight" :value="vModel" :lines="rowHeight" class="mr-7 nc-text-area-clamped-text" :style="{ 'word-break': 'break-word', 'white-space': 'pre-line', }" @click="onTextClick" /> <span v-else>{{ vModel }}</span> <div v-if="active && !isExpandedFormOpen" class="!absolute right-0 bottom-0 h-6 w-5 group cursor-pointer flex justify-end gap-1 items-center active:(ring ring-accent ring-opacity-100) rounded border-none p-1 hover:(bg-primary bg-opacity-10) dark:(!bg-slate-500)" :class="{ 'right-2 bottom-2': editEnabled }" data-testid="attachment-cell-file-picker-button" @click.stop="isVisible = !isVisible" > <NcTooltip placement="bottom"> <template #title>{{ $t('title.expand') }}</template> <component :is="iconMap.expand" class="transform dark:(!text-white) group-hover:(!text-grey-800 scale-120) text-gray-500 text-xs" /> </NcTooltip> </div> </div> <template #overlay> <div ref="inputWrapperRef" class="flex flex-col min-w-200 min-h-70 py-3 pl-3 pr-1 expanded-cell-input relative"> <div v-if="column" class="flex flex-row gap-x-1 items-center font-medium pb-2.5 mb-1 py-1 mr-3 ml-1 border-b-1 border-gray-100" > <SmartsheetHeaderCellIcon class="flex" /> <div class="flex max-w-38"> <span class="truncate"> {{ column.title }} </span> </div> </div> <a-textarea v-if="!isRichMode" ref="inputRef" v-model:value="vModel" class="p-1 !pt-1 !pr-3 !border-0 !border-r-0 !focus:outline-transparent nc-scrollbar-md !text-black !cursor-text" :placeholder="$t('activity.enterText')" :bordered="false" :auto-size="{ minRows: 20, maxRows: 20 }" :disabled="readOnly" @keydown.stop @keydown.escape="isVisible = false" /> <CellRichText v-else :key="String(isVisible)" v-model:value="vModel" class="ml-2 mt-2 nc-scrollbar-md" :style="{ 'max-height': 'calc(min(60vh, 100rem))', }" show-menu /> </div> </template> </NcDropdown> </template> <style lang="scss"> textarea:focus { box-shadow: none; } </style>
packages/nc-gui/components/cell/TextArea.vue
1
https://github.com/nocodb/nocodb/commit/f69391c0943d577049a8b484d88d0d94df137245
[ 0.000817160471342504, 0.00026777066523209214, 0.0001650357007747516, 0.00017170528008136898, 0.00018356750661041588 ]
{ "id": 3, "code_window": [ " <CellRichTextSelectedBubbleMenuPopup v-if=\"editor\" :editor=\"editor\" />\n", " <CellRichTextLinkOptions v-if=\"editor\" :editor=\"editor\" />\n", " <EditorContent ref=\"editorDom\" :editor=\"editor\" class=\"nc-textarea-rich w-full h-full nc-text-rich-scroll nc-scrollbar-md\" />\n", " </div>\n", "</template>\n", "\n", "<style lang=\"scss\">\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " <div v-if=\"props.fullMode\" class=\"flex flex-grow\" @click=\"focusEditorEnd\"></div>\n" ], "file_path": "packages/nc-gui/components/cell/RichText.vue", "type": "add", "edit_start_line_idx": 86 }
{ "extends": "../../tsconfig.json", "compilerOptions": { "skipLibCheck": true, "composite": true, "target": "es2017", "outDir": "build/main", "rootDir": "src", "moduleResolution": "node", "module": "commonjs", "declaration": true, "inlineSourceMap": true, "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, "allowJs": false, // "strict": true /* Enable all strict type-checking options. */, /* Strict Type-Checking Options */ // "noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */, // "strictNullChecks": true /* Enable strict null checks. */, // "strictFunctionTypes": true /* Enable strict checking of function types. */, // "strictPropertyInitialization": true /* Enable strict checking of property initialization in classes. */, // "noImplicitThis": true /* Raise error on 'this' expressions with an implied 'any' type. */, // "alwaysStrict": true /* Parse in strict mode and emit "use strict" for each source file. */, "resolveJsonModule": true, /* Additional Checks */ "noUnusedLocals": false /* Report errors on unused locals. */, "noUnusedParameters": false /* Report errors on unused parameters. */, "noImplicitReturns": false /* Report error when not all code paths in function return a value. */, "noFallthroughCasesInSwitch": false /* Report errors for fallthrough cases in switch statement. */, /* Debugging Options */ "traceResolution": false /* Report module resolution log messages. */, "listEmittedFiles": false /* Print names of generated files part of the compilation. */, "listFiles": false /* Print names of files part of the compilation. */, "pretty": true /* Stylize errors and messages using color and context. */, /* Experimental Options */ // "experimentalDecorators": true /* Enables experimental support for ES7 decorators. */, // "emitDecoratorMetadata": true /* Enables experimental support for emitting type metadata for decorators. */, "lib": [ "es2017", "dom" ], "types": [ "mocha", "node" ], "typeRoots": [ "../../src/types", "../../node_modules/@types" ] }, "include": [ "./tests/**/**/**.ts", "./tests/**/**.ts" // "**/*.ts", // "**/*.json" ], "exclude": [ ], "compileOnSave": false }
packages/nocodb/tests/unit/tsconfig.json
0
https://github.com/nocodb/nocodb/commit/f69391c0943d577049a8b484d88d0d94df137245
[ 0.00017287081573158503, 0.00017059274250641465, 0.0001651747152209282, 0.00017146285972557962, 0.000002505434622435132 ]
{ "id": 3, "code_window": [ " <CellRichTextSelectedBubbleMenuPopup v-if=\"editor\" :editor=\"editor\" />\n", " <CellRichTextLinkOptions v-if=\"editor\" :editor=\"editor\" />\n", " <EditorContent ref=\"editorDom\" :editor=\"editor\" class=\"nc-textarea-rich w-full h-full nc-text-rich-scroll nc-scrollbar-md\" />\n", " </div>\n", "</template>\n", "\n", "<style lang=\"scss\">\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " <div v-if=\"props.fullMode\" class=\"flex flex-grow\" @click=\"focusEditorEnd\"></div>\n" ], "file_path": "packages/nc-gui/components/cell/RichText.vue", "type": "add", "edit_start_line_idx": 86 }
import { Page, test } from '@playwright/test'; import { BaseType, ProjectTypes } from 'nocodb-sdk'; import { DashboardPage } from '../../pages/Dashboard'; import setup, { NcContext } from '../../setup'; test.describe('Tiptap:Keyboard shortcuts and drag and drop', () => { let dashboard: DashboardPage; let context: NcContext; let base: BaseType; test.beforeEach(async ({ page }) => { context = await setup({ page, baseType: ProjectTypes.DOCUMENTATION }); base = context.base; dashboard = new DashboardPage(page, context.base); }); test('Tiptap:Drag and drop', async ({ page }) => { const openedPage = await dashboard.docs.openedPage; await dashboard.sidebar.docsSidebar.createPage({ baseTitle: base.title as any, title: 'page', }); await openedPage.tiptap.addNewNode({ type: 'Heading 1', index: 0, }); await openedPage.tiptap.fillContent({ content: 'Heading 1 content', index: 0, type: 'Heading 1', }); await openedPage.tiptap.addNewNode({ type: 'Heading 2', index: 1, }); await openedPage.tiptap.fillContent({ content: 'Heading 2 content', index: 1, type: 'Heading 2', }); await openedPage.tiptap.dragToNode({ fromIndex: 0, toIndex: 1, }); await openedPage.tiptap.verifyNode({ index: 0, type: 'Heading 2', content: 'Heading 2 content', }); await openedPage.tiptap.verifyNode({ index: 1, type: 'Heading 1', content: 'Heading 1 content', }); await openedPage.tiptap.addNewNode({ index: 2, type: 'Image', filePath: `${process.cwd()}/fixtures/sampleFiles/sampleImage.jpeg`, }); await openedPage.tiptap.verifyNode({ index: 2, type: 'Image', isUploading: false, }); await openedPage.tiptap.clickNode({ index: 2, start: false, }); await openedPage.tiptap.dragToNode({ fromIndex: 2, toIndex: 0, withoutHandle: true, }); await openedPage.tiptap.verifyNode({ index: 0, type: 'Heading 2', content: 'Heading 2 content', }); await openedPage.tiptap.verifyNode({ index: 1, type: 'Image', isUploading: false, }); await openedPage.tiptap.verifyNode({ index: 2, type: 'Heading 1', content: 'Heading 1 content', }); }); test('Tiptap:Keyboard shortcuts', async ({ page }) => { const openedPage = await dashboard.docs.openedPage; await dashboard.sidebar.docsSidebar.createPage({ baseTitle: base.title as any, title: 'page', }); await openedPage.tiptap.clickNode({ index: 0, start: true, }); await page.keyboard.press('Control+Shift+1'); await openedPage.tiptap.verifyNode({ index: 0, type: 'Heading 1', }); await page.waitForTimeout(300); await openedPage.tiptap.clickNode({ index: 0, start: true, }); await page.keyboard.press('Control+Shift+2'); await openedPage.tiptap.verifyNode({ index: 0, type: 'Heading 2', }); await page.waitForTimeout(300); await openedPage.tiptap.clickNode({ index: 0, start: true, }); await page.keyboard.press('Control+Shift+3'); await openedPage.tiptap.verifyNode({ index: 0, type: 'Heading 3', }); await page.waitForTimeout(300); await openedPage.tiptap.clearContent(); await openedPage.tiptap.fillContent({ content: 'Link content', index: 0, }); await page.waitForTimeout(300); await openedPage.tiptap.selectNodes({ start: 0, end: 0, }); await page.waitForTimeout(300); await page.keyboard.press('Control+K'); await openedPage.tiptap.verifyLinkOptionVisible({ visible: true, }); await openedPage.tiptap.verifyLinkNode({ index: 0, placeholder: 'Link content', }); await page.waitForTimeout(300); await page.keyboard.press('Enter'); await openedPage.tiptap.clearContent(); await page.waitForTimeout(300); await openedPage.tiptap.fillContent({ content: 'Quote content', index: 0, }); await page.waitForTimeout(300); await page.keyboard.press('Meta+]'); await openedPage.tiptap.verifyNode({ index: 0, type: 'Quote', content: 'Quote content', }); await openedPage.tiptap.clearContent(); await page.waitForTimeout(300); await openedPage.tiptap.fillContent({ content: 'Code content', index: 0, }); await page.waitForTimeout(300); await page.keyboard.press('Alt+Meta+C'); await openedPage.tiptap.verifyTextFormatting({ index: 0, formatType: 'code', text: 'Code content', }); await openedPage.tiptap.clearContent(); await openedPage.tiptap.fillContent({ index: 0, content: 'Bullet content', }); await page.waitForTimeout(300); await page.keyboard.press('Control+Alt+2'); await openedPage.tiptap.verifyNode({ index: 0, type: 'Bullet List', content: 'Bullet content', }); await openedPage.tiptap.clearContent(); await page.waitForTimeout(300); await openedPage.tiptap.fillContent({ index: 0, content: 'Numbered content', }); await page.waitForTimeout(300); await page.keyboard.press('Control+Alt+3'); await openedPage.tiptap.verifyNode({ index: 0, type: 'Numbered List', content: 'Numbered content', }); await openedPage.tiptap.clearContent(); await page.waitForTimeout(300); await openedPage.tiptap.fillContent({ index: 0, content: 'Todo content', }); await page.waitForTimeout(300); await page.keyboard.press('Control+Alt+1'); await openedPage.tiptap.verifyNode({ index: 0, type: 'Task List', content: 'Todo content', }); await openedPage.tiptap.clearContent(); await page.waitForTimeout(300); await page.keyboard.press('Control+Shift+H'); await openedPage.tiptap.verifyNode({ index: 0, type: 'Divider', }); }); test('Tiptap:Keyboard shortcuts selection', async ({ page }) => { const openedPage = await dashboard.docs.openedPage; await dashboard.sidebar.docsSidebar.createPage({ baseTitle: base.title as any, title: 'page', }); // Cmd + Left await openedPage.tiptap.fillContent({ content: 'Content 1', }); await openedPage.tiptap.verifyNode({ content: 'Content 1', index: 0, }); await page.keyboard.press('Meta+ArrowLeft'); // Cmd + Shift + Right await page.waitForTimeout(300); await page.keyboard.press('Shift+Meta+ArrowRight'); await page.waitForTimeout(300); await page.keyboard.press('Delete'); await page.waitForTimeout(300); await openedPage.tiptap.fillContent({ index: 0, content: 'New Content 1', }); await openedPage.tiptap.verifyNode({ content: 'New Content 1', index: 0, }); await page.keyboard.press('Meta+ArrowLeft'); await page.waitForTimeout(300); // Cmd + Right await page.keyboard.press('Meta+ArrowRight'); await page.waitForTimeout(300); // Cmd + Shift + Left await page.keyboard.press('Shift+Meta+ArrowLeft'); await page.waitForTimeout(300); await page.keyboard.press('Delete'); await page.waitForTimeout(300); await openedPage.tiptap.fillContent({ index: 0, content: 'New New Content 1', }); await openedPage.tiptap.verifyNode({ content: 'New New Content 1', index: 0, }); // Cmd + Backspace await page.keyboard.press('Meta+Backspace'); await page.waitForTimeout(300); await openedPage.tiptap.fillContent({ index: 0, content: 'New New New Content 1', }); await openedPage.tiptap.verifyNode({ content: 'New New New Content 1', index: 0, }); }); });
tests/playwright/disabledTests/docs/keybaordShortcutsAndDragDrop.spec.ts
0
https://github.com/nocodb/nocodb/commit/f69391c0943d577049a8b484d88d0d94df137245
[ 0.00017569832562003285, 0.00017165849567390978, 0.000167596954270266, 0.00017159723211079836, 0.0000016340766251232708 ]
{ "id": 3, "code_window": [ " <CellRichTextSelectedBubbleMenuPopup v-if=\"editor\" :editor=\"editor\" />\n", " <CellRichTextLinkOptions v-if=\"editor\" :editor=\"editor\" />\n", " <EditorContent ref=\"editorDom\" :editor=\"editor\" class=\"nc-textarea-rich w-full h-full nc-text-rich-scroll nc-scrollbar-md\" />\n", " </div>\n", "</template>\n", "\n", "<style lang=\"scss\">\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " <div v-if=\"props.fullMode\" class=\"flex flex-grow\" @click=\"focusEditorEnd\"></div>\n" ], "file_path": "packages/nc-gui/components/cell/RichText.vue", "type": "add", "edit_start_line_idx": 86 }
<script lang="ts" setup> import { Modal, message } from 'ant-design-vue' import type { BaseType } from 'nocodb-sdk' import { useI18n } from 'vue-i18n' import { extractSdkResponseErrorMsg, iconMap, navigateTo, useNuxtApp, useRoute } from '#imports' import MaterialSymbolsFormatListBulletedRounded from '~icons/material-symbols/format-list-bulleted-rounded' import MaterialSymbolsGridView from '~icons/material-symbols/grid-view' import MdiFolderOutline from '~icons/mdi/folder-outline' const { t } = useI18n() const navDrawerOptions = [ { title: 'My NocoDB', icon: MdiFolderOutline, }, /* todo: implement the api and bring back the options below { title: "Shared With Me", icon: MdiAccountGroup }, { title: "Recent", icon: MdiClockOutline }, { title: "Starred", icon: MdiStar } */ ] const route = useRoute() const { $api } = useNuxtApp() const response = await $api.base.list({}) const bases = ref(response.list) const activePage = ref(navDrawerOptions[0].title) const deleteProject = (base: BaseType) => { Modal.confirm({ title: t('msg.info.deleteProject'), // icon: createVNode(ExclamationCircleOutlined), content: 'Some descriptions', okText: 'Yes', okType: 'danger', cancelText: 'No', async onOk() { try { await $api.base.delete(base.id as string) bases.value.splice(bases.value.indexOf(base), 1) } catch (e: any) { message.error(await extractSdkResponseErrorMsg(e)) } }, }) } </script> <template> <NuxtLayout> <template #sidebar> <div class="flex flex-col h-full"> <div class="flex p-4"> <v-menu class="select-none"> <template #activator="{ props }"> <div class="color-transition hover:(bg-gray-100) mr-auto select-none flex items-center gap-2 leading-8 cursor-pointer rounded-full border-1 border-gray-300 px-5 py-2 shadow prose-lg font-semibold" @click="props.onClick" > <component :is="iconMap.plus" class="text-primary text-2xl" /> {{ $t('title.newProj') }} </div> </template> <v-list class="!py-0 flex flex-col bg-white rounded-lg shadow-md border-1 border-gray-300 mt-2 ml-2"> <div class="grid grid-cols-12 cursor-pointer hover:bg-gray-200 flex items-center p-2" @click="navigateTo('/base/create')" > <component :is="iconMap.plus" class="col-span-2 mr-1 mt-[1px] text-primary text-lg" /> <div class="col-span-10 text-sm xl:text-md">{{ $t('activity.createProject') }}</div> </div> <div class="grid grid-cols-12 cursor-pointer hover:bg-gray-200 flex items-center p-2" @click="navigateTo('/base/create-external')" > <component :is="iconMap.database" class="col-span-2 mr-1 mt-[1px] text-green-500 text-lg" /> <div class="col-span-10 text-sm xl:text-md" v-html="$t('activity.createProjectExtended.extDB')" /> </div> </v-list> </v-menu> </div> <a-menu class="pr-4 flex-1 border-0"> <a-menu-item v-for="(option, index) in navDrawerOptions" :key="index" class="!rounded-r-lg" @click="activePage = option.title" > <div class="flex items-center gap-4"> <component :is="option.icon" /> <span class="font-semibold"> {{ option.title }} </span> </div> </a-menu-item> </a-menu> <general-social /> <general-sponsors :nav="true" /> </div> </template> <div class="flex-1 mb-12"> <div class="flex"> <div class="flex-1 text-2xl md:text-4xl font-bold text-gray-500 p-4"> {{ activePage }} </div> <div class="self-end flex text-4xl mb-1"> <MaterialSymbolsGridView :class="route.name === 'index-index' ? '!text-primary' : ''" class="cursor-pointer p-2 hover:bg-gray-300/50 rounded-full" @click="navigateTo('/')" /> <MaterialSymbolsFormatListBulletedRounded :class="route.name === 'index-index-list' ? '!text-primary' : ''" class="cursor-pointer p-2 hover:bg-gray-300/50 rounded-full" @click="navigateTo('/list')" /> </div> </div> <a-divider class="!mb-4 lg:(!mb-8)" /> <NuxtPage :bases="bases" @delete-base="deleteProject" /> </div> <a-modal></a-modal> </NuxtLayout> </template>
packages/nc-gui/pages/projects/index.vue
0
https://github.com/nocodb/nocodb/commit/f69391c0943d577049a8b484d88d0d94df137245
[ 0.00028018452576361597, 0.0001885967649286613, 0.00016478945326525718, 0.00017363220104016364, 0.000034823624446289614 ]
{ "id": 4, "code_window": [ " class=\"ml-2 mt-2 nc-scrollbar-md\"\n", " :style=\"{\n", " 'max-height': 'calc(min(60vh, 100rem))',\n", " }\"\n", " show-menu\n", " />\n", " </div>\n", " </template>\n", " </NcDropdown>\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " full-mode\n" ], "file_path": "packages/nc-gui/components/cell/TextArea.vue", "type": "add", "edit_start_line_idx": 208 }
<script setup lang="ts"> import type { VNodeRef } from '@vue/runtime-core' import { ActiveCellInj, EditColumnInj, EditModeInj, IsExpandedFormOpenInj, ReadonlyInj, RowHeightInj, iconMap, inject, useVModel, } from '#imports' const props = defineProps<{ modelValue?: string | number isFocus?: boolean virtual?: boolean }>() const emits = defineEmits(['update:modelValue']) const column = inject(ColumnInj) const editEnabled = inject(EditModeInj, ref(false)) const isEditColumn = inject(EditColumnInj, ref(false)) const rowHeight = inject(RowHeightInj, ref(1 as const)) const isForm = inject(IsFormInj, ref(false)) const { showNull } = useGlobal() const vModel = useVModel(props, 'modelValue', emits, { defaultValue: '' }) const isExpandedFormOpen = inject(IsExpandedFormOpenInj, ref(false))! const focus: VNodeRef = (el) => !isExpandedFormOpen.value && !isEditColumn.value && (el as HTMLTextAreaElement)?.focus() const height = computed(() => { if (!rowHeight.value || rowHeight.value === 1) return 36 return rowHeight.value * 36 }) const isVisible = ref(false) const inputWrapperRef = ref<HTMLElement | null>(null) const inputRef = ref<HTMLTextAreaElement | null>(null) const active = inject(ActiveCellInj, ref(false)) const readOnly = inject(ReadonlyInj) watch(isVisible, () => { if (isVisible.value) { setTimeout(() => { inputRef.value?.focus() }, 100) } }) onClickOutside(inputWrapperRef, (e) => { if ((e.target as HTMLElement)?.className.includes('nc-long-text-toggle-expand')) return isVisible.value = false }) const onTextClick = () => { if (!props.virtual) return isVisible.value = true editEnabled.value = true } const isRichMode = computed(() => { let meta: any = {} if (typeof column?.value?.meta === 'string') { meta = JSON.parse(column?.value?.meta) } else { meta = column?.value?.meta ?? {} } return meta?.richMode }) watch(editEnabled, () => { if (editEnabled.value && isRichMode.value) { isVisible.value = true } }) </script> <template> <NcDropdown v-model:visible="isVisible" class="overflow-visible" :trigger="[]" placement="bottomLeft"> <div class="flex flex-row pt-0.5 w-full" :class="{ 'min-h-10': rowHeight !== 1, 'min-h-6.5': rowHeight === 1, 'h-full': isForm, }" > <div v-if="isRichMode" class="w-full" :style="{ maxHeight: `${height}px !important`, minHeight: `${height}px !important`, }" > <CellRichText v-model:value="vModel" sync-value-change readonly class="!pointer-events-none" /> </div> <textarea v-else-if="editEnabled && !isVisible" :ref="focus" v-model="vModel" rows="4" class="h-full w-full outline-none border-none" :class="{ 'p-2': editEnabled, 'py-1 h-full': isForm, 'px-1': isExpandedFormOpen, }" :style="{ minHeight: `${height}px`, }" :placeholder="isEditColumn ? $t('labels.optional') : ''" @blur="editEnabled = false" @keydown.alt.enter.stop @keydown.shift.enter.stop @keydown.down.stop @keydown.left.stop @keydown.right.stop @keydown.up.stop @keydown.delete.stop @selectstart.capture.stop @mousedown.stop /> <span v-else-if="vModel === null && showNull" class="nc-null uppercase">{{ $t('general.null') }}</span> <LazyCellClampedText v-else-if="rowHeight" :value="vModel" :lines="rowHeight" class="mr-7 nc-text-area-clamped-text" :style="{ 'word-break': 'break-word', 'white-space': 'pre-line', }" @click="onTextClick" /> <span v-else>{{ vModel }}</span> <div v-if="active && !isExpandedFormOpen" class="!absolute right-0 bottom-0 h-6 w-5 group cursor-pointer flex justify-end gap-1 items-center active:(ring ring-accent ring-opacity-100) rounded border-none p-1 hover:(bg-primary bg-opacity-10) dark:(!bg-slate-500)" :class="{ 'right-2 bottom-2': editEnabled }" data-testid="attachment-cell-file-picker-button" @click.stop="isVisible = !isVisible" > <NcTooltip placement="bottom"> <template #title>{{ $t('title.expand') }}</template> <component :is="iconMap.expand" class="transform dark:(!text-white) group-hover:(!text-grey-800 scale-120) text-gray-500 text-xs" /> </NcTooltip> </div> </div> <template #overlay> <div ref="inputWrapperRef" class="flex flex-col min-w-200 min-h-70 py-3 pl-3 pr-1 expanded-cell-input relative"> <div v-if="column" class="flex flex-row gap-x-1 items-center font-medium pb-2.5 mb-1 py-1 mr-3 ml-1 border-b-1 border-gray-100" > <SmartsheetHeaderCellIcon class="flex" /> <div class="flex max-w-38"> <span class="truncate"> {{ column.title }} </span> </div> </div> <a-textarea v-if="!isRichMode" ref="inputRef" v-model:value="vModel" class="p-1 !pt-1 !pr-3 !border-0 !border-r-0 !focus:outline-transparent nc-scrollbar-md !text-black !cursor-text" :placeholder="$t('activity.enterText')" :bordered="false" :auto-size="{ minRows: 20, maxRows: 20 }" :disabled="readOnly" @keydown.stop @keydown.escape="isVisible = false" /> <CellRichText v-else :key="String(isVisible)" v-model:value="vModel" class="ml-2 mt-2 nc-scrollbar-md" :style="{ 'max-height': 'calc(min(60vh, 100rem))', }" show-menu /> </div> </template> </NcDropdown> </template> <style lang="scss"> textarea:focus { box-shadow: none; } </style>
packages/nc-gui/components/cell/TextArea.vue
1
https://github.com/nocodb/nocodb/commit/f69391c0943d577049a8b484d88d0d94df137245
[ 0.9571048617362976, 0.04395557940006256, 0.00016348839562851936, 0.000170643295859918, 0.1992672234773636 ]
{ "id": 4, "code_window": [ " class=\"ml-2 mt-2 nc-scrollbar-md\"\n", " :style=\"{\n", " 'max-height': 'calc(min(60vh, 100rem))',\n", " }\"\n", " show-menu\n", " />\n", " </div>\n", " </template>\n", " </NcDropdown>\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " full-mode\n" ], "file_path": "packages/nc-gui/components/cell/TextArea.vue", "type": "add", "edit_start_line_idx": 208 }
files: - source: /packages/nc-gui/lang/en.json translation: /packages/nc-gui/lang/%osx_locale%.json
crowdin.yml
0
https://github.com/nocodb/nocodb/commit/f69391c0943d577049a8b484d88d0d94df137245
[ 0.00016680856060702354, 0.00016680856060702354, 0.00016680856060702354, 0.00016680856060702354, 0 ]
{ "id": 4, "code_window": [ " class=\"ml-2 mt-2 nc-scrollbar-md\"\n", " :style=\"{\n", " 'max-height': 'calc(min(60vh, 100rem))',\n", " }\"\n", " show-menu\n", " />\n", " </div>\n", " </template>\n", " </NcDropdown>\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " full-mode\n" ], "file_path": "packages/nc-gui/components/cell/TextArea.vue", "type": "add", "edit_start_line_idx": 208 }
#!/bin/sh FILE="/usr/src/app/package.json" if [ ! -z "${NC_TOOL_DIR}" ]; then mkdir -p $NC_TOOL_DIR fi if [ ! -f "$FILE" ] then tar -xzf /usr/src/appEntry/app.tar.gz -C /usr/src/app/ fi node docker/index.js
packages/nocodb/docker/start-local.sh
0
https://github.com/nocodb/nocodb/commit/f69391c0943d577049a8b484d88d0d94df137245
[ 0.00017092295456677675, 0.00017015627236105502, 0.00016938957560341805, 0.00017015627236105502, 7.666894816793501e-7 ]
{ "id": 4, "code_window": [ " class=\"ml-2 mt-2 nc-scrollbar-md\"\n", " :style=\"{\n", " 'max-height': 'calc(min(60vh, 100rem))',\n", " }\"\n", " show-menu\n", " />\n", " </div>\n", " </template>\n", " </NcDropdown>\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " full-mode\n" ], "file_path": "packages/nc-gui/components/cell/TextArea.vue", "type": "add", "edit_start_line_idx": 208 }
import { Body, Controller, Delete, Get, HttpCode, Param, Patch, Post, Req, UseGuards, } from '@nestjs/common'; import { Request } from 'express'; import { ColumnReqType } from 'nocodb-sdk'; import type { Column } from '~/models'; import { GlobalGuard } from '~/guards/global/global.guard'; import { ColumnsService } from '~/services/columns.service'; import { Acl } from '~/middlewares/extract-ids/extract-ids.middleware'; import { MetaApiLimiterGuard } from '~/guards/meta-api-limiter.guard'; @Controller() @UseGuards(MetaApiLimiterGuard, GlobalGuard) export class ColumnsController { constructor(private readonly columnsService: ColumnsService) {} @Post([ '/api/v1/db/meta/tables/:tableId/columns/', '/api/v2/meta/tables/:tableId/columns/', ]) @HttpCode(200) @Acl('columnAdd') async columnAdd( @Param('tableId') tableId: string, @Body() body: ColumnReqType, @Req() req: Request, ) { return await this.columnsService.columnAdd({ tableId, column: body, req, user: req.user, }); } @Patch([ '/api/v1/db/meta/columns/:columnId', '/api/v2/meta/columns/:columnId', ]) @Acl('columnUpdate') async columnUpdate( @Param('columnId') columnId: string, @Body() body: ColumnReqType, @Req() req: Request, ) { return await this.columnsService.columnUpdate({ columnId: columnId, column: body, req, user: req.user, }); } @Delete([ '/api/v1/db/meta/columns/:columnId', '/api/v2/meta/columns/:columnId', ]) @Acl('columnDelete') async columnDelete(@Param('columnId') columnId: string, @Req() req: Request) { return await this.columnsService.columnDelete({ columnId, req, user: req.user, }); } @Get(['/api/v1/db/meta/columns/:columnId', '/api/v2/meta/columns/:columnId']) @Acl('columnGet') async columnGet(@Param('columnId') columnId: string) { return await this.columnsService.columnGet({ columnId }); } @Post([ '/api/v1/db/meta/columns/:columnId/primary', '/api/v2/meta/columns/:columnId/primary', ]) @HttpCode(200) @Acl('columnSetAsPrimary') async columnSetAsPrimary(@Param('columnId') columnId: string) { return await this.columnsService.columnSetAsPrimary({ columnId }); } @Get([ '/api/v1/db/meta/tables/:tableId/columns/hash', '/api/v2/meta/tables/:tableId/columns/hash', ]) @Acl('columnsHash') async columnsHash(@Param('tableId') tableId: string) { return await this.columnsService.columnsHash(tableId); } @Post([ '/api/v1/db/meta/tables/:tableId/columns/bulk', '/api/v2/meta/tables/:tableId/columns/bulk', ]) @HttpCode(200) @Acl('columnBulk') async columnBulk( @Param('tableId') tableId: string, @Body() body: { hash: string; ops: { op: 'add' | 'update' | 'delete'; column: Partial<Column>; }[]; }, @Req() req: Request, ) { return await this.columnsService.columnBulk(tableId, body, req); } }
packages/nocodb/src/controllers/columns.controller.ts
0
https://github.com/nocodb/nocodb/commit/f69391c0943d577049a8b484d88d0d94df137245
[ 0.00017565242887940258, 0.00017274211859330535, 0.00017072961782105267, 0.0001726447808323428, 0.0000012559683000290534 ]
{ "id": 0, "code_window": [ "- [Issue #394](https://github.com/grafana/grafana/issues/394). InfluxDB: Annotation support\n", "- [Issue #633](https://github.com/grafana/grafana/issues/633). InfluxDB: InfluxDB can now act as a datastore for dashboards\n", "- [Issue #610](https://github.com/grafana/grafana/issues/610). InfluxDB: Support for InfluxdB v0.8 list series response schemea (series typeahead)\n", "- [Issue #525](https://github.com/grafana/grafana/issues/525). InfluxDB: Enhanced series aliasing (legend names) with pattern replacements\n", "- [Issue #266](https://github.com/grafana/grafana/issues/266). Graphite: New option cacheTimeout to override graphite default memcache timeout\n", "- [Issue #344](https://github.com/grafana/grafana/issues/344). Graphite: Annotations can now be fetched from non default datasources\n", "- [Issue #606](https://github.com/grafana/grafana/issues/606). General: New global option in config.js to specify admin password (useful to hinder users from accidentally make changes)\n", "- [Issue #201](https://github.com/grafana/grafana/issues/201). Annotations: Elasticsearch datasource support for events\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "CHANGELOG.md", "type": "replace", "edit_start_line_idx": 10 }
define([ 'angular', 'jquery', 'kbn', 'moment', 'underscore' ], function (angular, $, kbn, moment, _) { 'use strict'; var module = angular.module('grafana.directives'); module.directive('grafanaGraph', function($rootScope) { return { restrict: 'A', template: '<div> </div>', link: function(scope, elem) { var data, plot, annotations; var hiddenData = {}; var dashboard = scope.dashboard; var legendSideLastValue = null; scope.$on('refresh',function() { if (scope.otherPanelInFullscreenMode()) { return; } scope.get_data(); }); scope.$on('toggleLegend', function(e, series) { _.each(series, function(serie) { if (hiddenData[serie.alias]) { data.push(hiddenData[serie.alias]); delete hiddenData[serie.alias]; } }); render_panel(); }); // Receive render events scope.$on('render',function(event, renderData) { data = renderData || data; annotations = data.annotations; render_panel(); }); // Re-render if the window is resized angular.element(window).bind('resize', function() { render_panel(); }); function setElementHeight() { try { var height = scope.height || scope.panel.height || scope.row.height; if (_.isString(height)) { height = parseInt(height.replace('px', ''), 10); } height = height - 32; // subtract panel title bar if (scope.panel.legend.show && !scope.panel.legend.rightSide) { height = height - 21; // subtract one line legend } elem.css('height', height + 'px'); return true; } catch(e) { // IE throws errors sometimes return false; } } function shouldAbortRender() { if (!data) { return true; } if ($rootScope.fullscreen && !scope.fullscreen) { return true; } if (!setElementHeight()) { return true; } if (_.isString(data)) { render_panel_as_graphite_png(data); return true; } } // Function for rendering panel function render_panel() { if (shouldAbortRender()) { return; } var panel = scope.panel; _.each(_.keys(scope.hiddenSeries), function(seriesAlias) { var dataSeries = _.find(data, function(series) { return series.info.alias === seriesAlias; }); if (dataSeries) { hiddenData[dataSeries.info.alias] = dataSeries; data = _.without(data, dataSeries); } }); var stack = panel.stack ? true : null; // Populate element var options = { legend: { show: false }, series: { stackpercent: panel.stack ? panel.percentage : false, stack: panel.percentage ? null : stack, lines: { show: panel.lines, zero: false, fill: panel.fill === 0 ? 0.001 : panel.fill/10, lineWidth: panel.linewidth, steps: panel.steppedLine }, bars: { show: panel.bars, fill: 1, barWidth: 1, zero: false, lineWidth: 0 }, points: { show: panel.points, fill: 1, fillColor: false, radius: panel.pointradius }, shadowSize: 1 }, yaxes: [], xaxis: {}, grid: { minBorderMargin: 0, markings: [], backgroundColor: null, borderWidth: 0, hoverable: true, color: '#c8c8c8' }, selection: { mode: "x", color: '#666' } }; for (var i = 0; i < data.length; i++) { var _d = data[i].getFlotPairs(panel.nullPointMode, panel.y_formats); data[i].data = _d; } if (panel.bars && data.length && data[0].info.timeStep) { options.series.bars.barWidth = data[0].info.timeStep / 1.5; } addTimeAxis(options); addGridThresholds(options, panel); addAnnotations(options); configureAxisOptions(data, options); // if legend is to the right delay plot draw a few milliseconds // so the legend width calculation can be done if (shouldDelayDraw(panel)) { legendSideLastValue = panel.legend.rightSide; setTimeout(function() { plot = $.plot(elem, data, options); addAxisLabels(); }, 50); } else { plot = $.plot(elem, data, options); addAxisLabels(); } } function shouldDelayDraw(panel) { if (panel.legend.rightSide) { return true; } if (legendSideLastValue !== null && panel.legend.rightSide !== legendSideLastValue) { return true; } return false; } function addTimeAxis(options) { var ticks = elem.width() / 100; var min = _.isUndefined(scope.range.from) ? null : scope.range.from.getTime(); var max = _.isUndefined(scope.range.to) ? null : scope.range.to.getTime(); options.xaxis = { timezone: dashboard.timezone, show: scope.panel['x-axis'], mode: "time", min: min, max: max, label: "Datetime", ticks: ticks, timeformat: time_format(scope.interval, ticks, min, max), }; } function addGridThresholds(options, panel) { if (panel.grid.threshold1) { var limit1 = panel.grid.thresholdLine ? panel.grid.threshold1 : (panel.grid.threshold2 || null); options.grid.markings.push({ yaxis: { from: panel.grid.threshold1, to: limit1 }, color: panel.grid.threshold1Color }); if (panel.grid.threshold2) { var limit2; if (panel.grid.thresholdLine) { limit2 = panel.grid.threshold2; } else { limit2 = panel.grid.threshold1 > panel.grid.threshold2 ? -Infinity : +Infinity; } options.grid.markings.push({ yaxis: { from: panel.grid.threshold2, to: limit2 }, color: panel.grid.threshold2Color }); } } } function addAnnotations(options) { if(!annotations || annotations.length === 0) { return; } var types = {}; _.each(annotations, function(event) { if (!types[event.annotation.name]) { types[event.annotation.name] = { level: _.keys(types).length + 1, icon: { icon: "icon-chevron-down", size: event.annotation.iconSize, color: event.annotation.iconColor, } }; } if (event.annotation.showLine) { options.grid.markings.push({ color: event.annotation.lineColor, lineWidth: 1, xaxis: { from: event.min, to: event.max } }); } }); options.events = { levels: _.keys(types).length + 1, data: annotations, types: types }; } function addAxisLabels() { if (scope.panel.leftYAxisLabel) { elem.css('margin-left', '10px'); var yaxisLabel = $("<div class='axisLabel yaxisLabel'></div>") .text(scope.panel.leftYAxisLabel) .appendTo(elem); yaxisLabel.css("margin-top", yaxisLabel.width() / 2 - 20); } else if (elem.css('margin-left')) { elem.css('margin-left', ''); } } function configureAxisOptions(data, options) { var defaults = { position: 'left', show: scope.panel['y-axis'], min: scope.panel.grid.leftMin, max: scope.panel.percentage && scope.panel.stack ? 100 : scope.panel.grid.leftMax, }; options.yaxes.push(defaults); if (_.findWhere(data, {yaxis: 2})) { var secondY = _.clone(defaults); secondY.position = 'right'; secondY.min = scope.panel.grid.rightMin; secondY.max = scope.panel.percentage && scope.panel.stack ? 100 : scope.panel.grid.rightMax; options.yaxes.push(secondY); configureAxisMode(options.yaxes[1], scope.panel.y_formats[1]); } configureAxisMode(options.yaxes[0], scope.panel.y_formats[0]); } function configureAxisMode(axis, format) { if (format !== 'none') { axis.tickFormatter = kbn.getFormatFunction(format, 1); } } function time_format(interval, ticks, min, max) { if (min && max && ticks) { var secPerTick = ((max - min) / ticks) / 1000; if (secPerTick <= 45) { return "%H:%M:%S"; } if (secPerTick <= 3600) { return "%H:%M"; } if (secPerTick <= 80000) { return "%m/%d %H:%M"; } if (secPerTick <= 2419200) { return "%m/%d"; } return "%Y-%m"; } return "%H:%M"; } var $tooltip = $('<div>'); elem.bind("plothover", function (event, pos, item) { var group, value, timestamp, seriesInfo, format; if (item) { seriesInfo = item.series.info; format = scope.panel.y_formats[seriesInfo.yaxis - 1]; if (seriesInfo.alias) { group = '<small style="font-size:0.9em;">' + '<i class="icon-circle" style="color:'+item.series.color+';"></i>' + ' ' + seriesInfo.alias + '</small><br>'; } else { group = kbn.query_color_dot(item.series.color, 15) + ' '; } if (scope.panel.stack && scope.panel.tooltip.value_type === 'individual') { value = item.datapoint[1] - item.datapoint[2]; } else { value = item.datapoint[1]; } value = kbn.getFormatFunction(format, 2)(value); timestamp = dashboard.timezone === 'browser' ? moment(item.datapoint[0]).format('YYYY-MM-DD HH:mm:ss') : moment.utc(item.datapoint[0]).format('YYYY-MM-DD HH:mm:ss'); $tooltip .html( group + value + " @ " + timestamp ) .place_tt(pos.pageX, pos.pageY); } else { $tooltip.detach(); } }); function render_panel_as_graphite_png(url) { url += '&width=' + elem.width(); url += '&height=' + elem.css('height').replace('px', ''); url += '&bgcolor=1f1f1f'; // @grayDarker & @grafanaPanelBackground url += '&fgcolor=BBBFC2'; // @textColor & @grayLighter url += scope.panel.stack ? '&areaMode=stacked' : ''; url += scope.panel.fill !== 0 ? ('&areaAlpha=' + (scope.panel.fill/10).toFixed(1)) : ''; url += scope.panel.linewidth !== 0 ? '&lineWidth=' + scope.panel.linewidth : ''; url += scope.panel.legend.show ? '&hideLegend=false' : '&hideLegend=true'; url += scope.panel.grid.leftMin !== null ? '&yMin=' + scope.panel.grid.leftMin : ''; url += scope.panel.grid.leftMax !== null ? '&yMax=' + scope.panel.grid.leftMax : ''; url += scope.panel.grid.rightMin !== null ? '&yMin=' + scope.panel.grid.rightMin : ''; url += scope.panel.grid.rightMax !== null ? '&yMax=' + scope.panel.grid.rightMax : ''; url += scope.panel['x-axis'] ? '' : '&hideAxes=true'; url += scope.panel['y-axis'] ? '' : '&hideYAxis=true'; switch(scope.panel.y_formats[0]) { case 'bytes': url += '&yUnitSystem=binary'; break; case 'bits': url += '&yUnitSystem=binary'; break; case 'bps': url += '&yUnitSystem=si'; break; case 'short': url += '&yUnitSystem=si'; break; case 'none': url += '&yUnitSystem=none'; break; } switch(scope.panel.nullPointMode) { case 'connected': url += '&lineMode=connected'; break; case 'null': break; // graphite default lineMode case 'null as zero': url += "&drawNullAsZero=true"; break; } url += scope.panel.steppedLine ? '&lineMode=staircase' : ''; elem.html('<img src="' + url + '"></img>'); } elem.bind("plotselected", function (event, ranges) { scope.$apply(function() { scope.filter.setTime({ from : moment.utc(ranges.xaxis.from).toDate(), to : moment.utc(ranges.xaxis.to).toDate(), }); }); }); } }; }); });
src/app/directives/grafanaGraph.js
1
https://github.com/grafana/grafana/commit/e9a046e74d86b43b41c92bab5a8ac8beacb61441
[ 0.0024505031760782003, 0.0002884879941120744, 0.0001654581428738311, 0.00017625855980440974, 0.00037060261820442975 ]
{ "id": 0, "code_window": [ "- [Issue #394](https://github.com/grafana/grafana/issues/394). InfluxDB: Annotation support\n", "- [Issue #633](https://github.com/grafana/grafana/issues/633). InfluxDB: InfluxDB can now act as a datastore for dashboards\n", "- [Issue #610](https://github.com/grafana/grafana/issues/610). InfluxDB: Support for InfluxdB v0.8 list series response schemea (series typeahead)\n", "- [Issue #525](https://github.com/grafana/grafana/issues/525). InfluxDB: Enhanced series aliasing (legend names) with pattern replacements\n", "- [Issue #266](https://github.com/grafana/grafana/issues/266). Graphite: New option cacheTimeout to override graphite default memcache timeout\n", "- [Issue #344](https://github.com/grafana/grafana/issues/344). Graphite: Annotations can now be fetched from non default datasources\n", "- [Issue #606](https://github.com/grafana/grafana/issues/606). General: New global option in config.js to specify admin password (useful to hinder users from accidentally make changes)\n", "- [Issue #201](https://github.com/grafana/grafana/issues/201). Annotations: Elasticsearch datasource support for events\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "CHANGELOG.md", "type": "replace", "edit_start_line_idx": 10 }
// // Close icons // -------------------------------------------------- .close { float: right; font-size: 20px; font-weight: bold; line-height: @baseLineHeight; color: @black; text-shadow: 0 1px 0 rgba(255,255,255,1); .opacity(20); &:hover, &:focus { color: @black; text-decoration: none; cursor: pointer; .opacity(40); } } // Additional properties for button version // iOS requires the button element instead of an anchor tag. // If you want the anchor version, it requires `href="#"`. button.close { padding: 0; cursor: pointer; background: transparent; border: 0; -webkit-appearance: none; }
src/vendor/bootstrap/less/close.less
0
https://github.com/grafana/grafana/commit/e9a046e74d86b43b41c92bab5a8ac8beacb61441
[ 0.00017715022841002792, 0.00016966566909104586, 0.00016653411148581654, 0.00016748915368225425, 0.0000043655268200382125 ]
{ "id": 0, "code_window": [ "- [Issue #394](https://github.com/grafana/grafana/issues/394). InfluxDB: Annotation support\n", "- [Issue #633](https://github.com/grafana/grafana/issues/633). InfluxDB: InfluxDB can now act as a datastore for dashboards\n", "- [Issue #610](https://github.com/grafana/grafana/issues/610). InfluxDB: Support for InfluxdB v0.8 list series response schemea (series typeahead)\n", "- [Issue #525](https://github.com/grafana/grafana/issues/525). InfluxDB: Enhanced series aliasing (legend names) with pattern replacements\n", "- [Issue #266](https://github.com/grafana/grafana/issues/266). Graphite: New option cacheTimeout to override graphite default memcache timeout\n", "- [Issue #344](https://github.com/grafana/grafana/issues/344). Graphite: Annotations can now be fetched from non default datasources\n", "- [Issue #606](https://github.com/grafana/grafana/issues/606). General: New global option in config.js to specify admin password (useful to hinder users from accidentally make changes)\n", "- [Issue #201](https://github.com/grafana/grafana/issues/201). Annotations: Elasticsearch datasource support for events\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "CHANGELOG.md", "type": "replace", "edit_start_line_idx": 10 }
define(['angular'], function (angular) { 'use strict'; angular .module('grafana.directives') .directive('ngModelOnblur', function() { return { restrict: 'A', require: 'ngModel', link: function(scope, elm, attr, ngModelCtrl) { if (attr.type === 'radio' || attr.type === 'checkbox') { return; } elm.unbind('input').unbind('keydown').unbind('change'); elm.bind('blur', function() { scope.$apply(function() { ngModelCtrl.$setViewValue(elm.val()); }); }); } }; }); });
src/app/directives/ngModelOnBlur.js
0
https://github.com/grafana/grafana/commit/e9a046e74d86b43b41c92bab5a8ac8beacb61441
[ 0.00019162562966812402, 0.00018109912343788892, 0.00017543650756124407, 0.00017623523308429867, 0.0000074505032898741774 ]
{ "id": 0, "code_window": [ "- [Issue #394](https://github.com/grafana/grafana/issues/394). InfluxDB: Annotation support\n", "- [Issue #633](https://github.com/grafana/grafana/issues/633). InfluxDB: InfluxDB can now act as a datastore for dashboards\n", "- [Issue #610](https://github.com/grafana/grafana/issues/610). InfluxDB: Support for InfluxdB v0.8 list series response schemea (series typeahead)\n", "- [Issue #525](https://github.com/grafana/grafana/issues/525). InfluxDB: Enhanced series aliasing (legend names) with pattern replacements\n", "- [Issue #266](https://github.com/grafana/grafana/issues/266). Graphite: New option cacheTimeout to override graphite default memcache timeout\n", "- [Issue #344](https://github.com/grafana/grafana/issues/344). Graphite: Annotations can now be fetched from non default datasources\n", "- [Issue #606](https://github.com/grafana/grafana/issues/606). General: New global option in config.js to specify admin password (useful to hinder users from accidentally make changes)\n", "- [Issue #201](https://github.com/grafana/grafana/issues/201). Annotations: Elasticsearch datasource support for events\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "CHANGELOG.md", "type": "replace", "edit_start_line_idx": 10 }
node_modules .aws-config.json dist # locally required config files web.config config.js # Editor junk *.sublime-workspace *.swp .idea/
.gitignore
0
https://github.com/grafana/grafana/commit/e9a046e74d86b43b41c92bab5a8ac8beacb61441
[ 0.00020792294526472688, 0.00018675817409530282, 0.00016559338837396353, 0.00018675817409530282, 0.00002116477844538167 ]
{ "id": 1, "code_window": [ "- [Issue #606](https://github.com/grafana/grafana/issues/606). General: New global option in config.js to specify admin password (useful to hinder users from accidentally make changes)\n", "- [Issue #201](https://github.com/grafana/grafana/issues/201). Annotations: Elasticsearch datasource support for events\n", "- [Issue #631](https://github.com/grafana/grafana/issues/631). Search: max_results config.js option & scroll in search results (To show more or all dashboards)\n", "- [Issue #511](https://github.com/grafana/grafana/issues/511). Text panel: Allow [[..]] filter notation in all text panels (markdown/html/text)\n", "- [Issue #136](https://github.com/grafana/grafana/issues/136). Chart: New legend display option \"Align as table\"\n", "- [Issue #556](https://github.com/grafana/grafana/issues/556). Chart: New legend display option \"Right side\", will show legend to the right of the graph\n", "- [Issue #604](https://github.com/grafana/grafana/issues/604). Chart: New axis format, 'bps' (SI unit in steps of 1000) useful for network gear metics\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "- [Issue #344](https://github.com/grafana/grafana/issues/344). Annotations: Annotations can now be fetched from non default datasources\n" ], "file_path": "CHANGELOG.md", "type": "add", "edit_start_line_idx": 13 }
define([ 'angular', 'jquery', 'kbn', 'moment', 'underscore' ], function (angular, $, kbn, moment, _) { 'use strict'; var module = angular.module('grafana.directives'); module.directive('grafanaGraph', function($rootScope) { return { restrict: 'A', template: '<div> </div>', link: function(scope, elem) { var data, plot, annotations; var hiddenData = {}; var dashboard = scope.dashboard; var legendSideLastValue = null; scope.$on('refresh',function() { if (scope.otherPanelInFullscreenMode()) { return; } scope.get_data(); }); scope.$on('toggleLegend', function(e, series) { _.each(series, function(serie) { if (hiddenData[serie.alias]) { data.push(hiddenData[serie.alias]); delete hiddenData[serie.alias]; } }); render_panel(); }); // Receive render events scope.$on('render',function(event, renderData) { data = renderData || data; annotations = data.annotations; render_panel(); }); // Re-render if the window is resized angular.element(window).bind('resize', function() { render_panel(); }); function setElementHeight() { try { var height = scope.height || scope.panel.height || scope.row.height; if (_.isString(height)) { height = parseInt(height.replace('px', ''), 10); } height = height - 32; // subtract panel title bar if (scope.panel.legend.show && !scope.panel.legend.rightSide) { height = height - 21; // subtract one line legend } elem.css('height', height + 'px'); return true; } catch(e) { // IE throws errors sometimes return false; } } function shouldAbortRender() { if (!data) { return true; } if ($rootScope.fullscreen && !scope.fullscreen) { return true; } if (!setElementHeight()) { return true; } if (_.isString(data)) { render_panel_as_graphite_png(data); return true; } } // Function for rendering panel function render_panel() { if (shouldAbortRender()) { return; } var panel = scope.panel; _.each(_.keys(scope.hiddenSeries), function(seriesAlias) { var dataSeries = _.find(data, function(series) { return series.info.alias === seriesAlias; }); if (dataSeries) { hiddenData[dataSeries.info.alias] = dataSeries; data = _.without(data, dataSeries); } }); var stack = panel.stack ? true : null; // Populate element var options = { legend: { show: false }, series: { stackpercent: panel.stack ? panel.percentage : false, stack: panel.percentage ? null : stack, lines: { show: panel.lines, zero: false, fill: panel.fill === 0 ? 0.001 : panel.fill/10, lineWidth: panel.linewidth, steps: panel.steppedLine }, bars: { show: panel.bars, fill: 1, barWidth: 1, zero: false, lineWidth: 0 }, points: { show: panel.points, fill: 1, fillColor: false, radius: panel.pointradius }, shadowSize: 1 }, yaxes: [], xaxis: {}, grid: { minBorderMargin: 0, markings: [], backgroundColor: null, borderWidth: 0, hoverable: true, color: '#c8c8c8' }, selection: { mode: "x", color: '#666' } }; for (var i = 0; i < data.length; i++) { var _d = data[i].getFlotPairs(panel.nullPointMode, panel.y_formats); data[i].data = _d; } if (panel.bars && data.length && data[0].info.timeStep) { options.series.bars.barWidth = data[0].info.timeStep / 1.5; } addTimeAxis(options); addGridThresholds(options, panel); addAnnotations(options); configureAxisOptions(data, options); // if legend is to the right delay plot draw a few milliseconds // so the legend width calculation can be done if (shouldDelayDraw(panel)) { legendSideLastValue = panel.legend.rightSide; setTimeout(function() { plot = $.plot(elem, data, options); addAxisLabels(); }, 50); } else { plot = $.plot(elem, data, options); addAxisLabels(); } } function shouldDelayDraw(panel) { if (panel.legend.rightSide) { return true; } if (legendSideLastValue !== null && panel.legend.rightSide !== legendSideLastValue) { return true; } return false; } function addTimeAxis(options) { var ticks = elem.width() / 100; var min = _.isUndefined(scope.range.from) ? null : scope.range.from.getTime(); var max = _.isUndefined(scope.range.to) ? null : scope.range.to.getTime(); options.xaxis = { timezone: dashboard.timezone, show: scope.panel['x-axis'], mode: "time", min: min, max: max, label: "Datetime", ticks: ticks, timeformat: time_format(scope.interval, ticks, min, max), }; } function addGridThresholds(options, panel) { if (panel.grid.threshold1) { var limit1 = panel.grid.thresholdLine ? panel.grid.threshold1 : (panel.grid.threshold2 || null); options.grid.markings.push({ yaxis: { from: panel.grid.threshold1, to: limit1 }, color: panel.grid.threshold1Color }); if (panel.grid.threshold2) { var limit2; if (panel.grid.thresholdLine) { limit2 = panel.grid.threshold2; } else { limit2 = panel.grid.threshold1 > panel.grid.threshold2 ? -Infinity : +Infinity; } options.grid.markings.push({ yaxis: { from: panel.grid.threshold2, to: limit2 }, color: panel.grid.threshold2Color }); } } } function addAnnotations(options) { if(!annotations || annotations.length === 0) { return; } var types = {}; _.each(annotations, function(event) { if (!types[event.annotation.name]) { types[event.annotation.name] = { level: _.keys(types).length + 1, icon: { icon: "icon-chevron-down", size: event.annotation.iconSize, color: event.annotation.iconColor, } }; } if (event.annotation.showLine) { options.grid.markings.push({ color: event.annotation.lineColor, lineWidth: 1, xaxis: { from: event.min, to: event.max } }); } }); options.events = { levels: _.keys(types).length + 1, data: annotations, types: types }; } function addAxisLabels() { if (scope.panel.leftYAxisLabel) { elem.css('margin-left', '10px'); var yaxisLabel = $("<div class='axisLabel yaxisLabel'></div>") .text(scope.panel.leftYAxisLabel) .appendTo(elem); yaxisLabel.css("margin-top", yaxisLabel.width() / 2 - 20); } else if (elem.css('margin-left')) { elem.css('margin-left', ''); } } function configureAxisOptions(data, options) { var defaults = { position: 'left', show: scope.panel['y-axis'], min: scope.panel.grid.leftMin, max: scope.panel.percentage && scope.panel.stack ? 100 : scope.panel.grid.leftMax, }; options.yaxes.push(defaults); if (_.findWhere(data, {yaxis: 2})) { var secondY = _.clone(defaults); secondY.position = 'right'; secondY.min = scope.panel.grid.rightMin; secondY.max = scope.panel.percentage && scope.panel.stack ? 100 : scope.panel.grid.rightMax; options.yaxes.push(secondY); configureAxisMode(options.yaxes[1], scope.panel.y_formats[1]); } configureAxisMode(options.yaxes[0], scope.panel.y_formats[0]); } function configureAxisMode(axis, format) { if (format !== 'none') { axis.tickFormatter = kbn.getFormatFunction(format, 1); } } function time_format(interval, ticks, min, max) { if (min && max && ticks) { var secPerTick = ((max - min) / ticks) / 1000; if (secPerTick <= 45) { return "%H:%M:%S"; } if (secPerTick <= 3600) { return "%H:%M"; } if (secPerTick <= 80000) { return "%m/%d %H:%M"; } if (secPerTick <= 2419200) { return "%m/%d"; } return "%Y-%m"; } return "%H:%M"; } var $tooltip = $('<div>'); elem.bind("plothover", function (event, pos, item) { var group, value, timestamp, seriesInfo, format; if (item) { seriesInfo = item.series.info; format = scope.panel.y_formats[seriesInfo.yaxis - 1]; if (seriesInfo.alias) { group = '<small style="font-size:0.9em;">' + '<i class="icon-circle" style="color:'+item.series.color+';"></i>' + ' ' + seriesInfo.alias + '</small><br>'; } else { group = kbn.query_color_dot(item.series.color, 15) + ' '; } if (scope.panel.stack && scope.panel.tooltip.value_type === 'individual') { value = item.datapoint[1] - item.datapoint[2]; } else { value = item.datapoint[1]; } value = kbn.getFormatFunction(format, 2)(value); timestamp = dashboard.timezone === 'browser' ? moment(item.datapoint[0]).format('YYYY-MM-DD HH:mm:ss') : moment.utc(item.datapoint[0]).format('YYYY-MM-DD HH:mm:ss'); $tooltip .html( group + value + " @ " + timestamp ) .place_tt(pos.pageX, pos.pageY); } else { $tooltip.detach(); } }); function render_panel_as_graphite_png(url) { url += '&width=' + elem.width(); url += '&height=' + elem.css('height').replace('px', ''); url += '&bgcolor=1f1f1f'; // @grayDarker & @grafanaPanelBackground url += '&fgcolor=BBBFC2'; // @textColor & @grayLighter url += scope.panel.stack ? '&areaMode=stacked' : ''; url += scope.panel.fill !== 0 ? ('&areaAlpha=' + (scope.panel.fill/10).toFixed(1)) : ''; url += scope.panel.linewidth !== 0 ? '&lineWidth=' + scope.panel.linewidth : ''; url += scope.panel.legend.show ? '&hideLegend=false' : '&hideLegend=true'; url += scope.panel.grid.leftMin !== null ? '&yMin=' + scope.panel.grid.leftMin : ''; url += scope.panel.grid.leftMax !== null ? '&yMax=' + scope.panel.grid.leftMax : ''; url += scope.panel.grid.rightMin !== null ? '&yMin=' + scope.panel.grid.rightMin : ''; url += scope.panel.grid.rightMax !== null ? '&yMax=' + scope.panel.grid.rightMax : ''; url += scope.panel['x-axis'] ? '' : '&hideAxes=true'; url += scope.panel['y-axis'] ? '' : '&hideYAxis=true'; switch(scope.panel.y_formats[0]) { case 'bytes': url += '&yUnitSystem=binary'; break; case 'bits': url += '&yUnitSystem=binary'; break; case 'bps': url += '&yUnitSystem=si'; break; case 'short': url += '&yUnitSystem=si'; break; case 'none': url += '&yUnitSystem=none'; break; } switch(scope.panel.nullPointMode) { case 'connected': url += '&lineMode=connected'; break; case 'null': break; // graphite default lineMode case 'null as zero': url += "&drawNullAsZero=true"; break; } url += scope.panel.steppedLine ? '&lineMode=staircase' : ''; elem.html('<img src="' + url + '"></img>'); } elem.bind("plotselected", function (event, ranges) { scope.$apply(function() { scope.filter.setTime({ from : moment.utc(ranges.xaxis.from).toDate(), to : moment.utc(ranges.xaxis.to).toDate(), }); }); }); } }; }); });
src/app/directives/grafanaGraph.js
1
https://github.com/grafana/grafana/commit/e9a046e74d86b43b41c92bab5a8ac8beacb61441
[ 0.001463135122321546, 0.00033869213075377047, 0.00016553387104067951, 0.00022115674801170826, 0.00028179038781672716 ]
{ "id": 1, "code_window": [ "- [Issue #606](https://github.com/grafana/grafana/issues/606). General: New global option in config.js to specify admin password (useful to hinder users from accidentally make changes)\n", "- [Issue #201](https://github.com/grafana/grafana/issues/201). Annotations: Elasticsearch datasource support for events\n", "- [Issue #631](https://github.com/grafana/grafana/issues/631). Search: max_results config.js option & scroll in search results (To show more or all dashboards)\n", "- [Issue #511](https://github.com/grafana/grafana/issues/511). Text panel: Allow [[..]] filter notation in all text panels (markdown/html/text)\n", "- [Issue #136](https://github.com/grafana/grafana/issues/136). Chart: New legend display option \"Align as table\"\n", "- [Issue #556](https://github.com/grafana/grafana/issues/556). Chart: New legend display option \"Right side\", will show legend to the right of the graph\n", "- [Issue #604](https://github.com/grafana/grafana/issues/604). Chart: New axis format, 'bps' (SI unit in steps of 1000) useful for network gear metics\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "- [Issue #344](https://github.com/grafana/grafana/issues/344). Annotations: Annotations can now be fetched from non default datasources\n" ], "file_path": "CHANGELOG.md", "type": "add", "edit_start_line_idx": 13 }
<div class="editor-row" style="margin-top: 10px;"> <div ng-repeat="target in panel.targets" class="grafana-target" ng-class="{'grafana-target-hidden': target.hide}" ng-controller="GraphiteTargetCtrl" ng-init="init()"> <div class="grafana-target-inner"> <ul class="grafana-target-controls"> <li ng-show="parserError"> <a bs-tooltip="parserError" style="color: rgb(229, 189, 28)" role="menuitem"> <i class="icon-warning-sign"></i> </a> </li> <li> <a class="pointer" tabindex="1" ng-click="showTextEditor = !showTextEditor"> <i class="icon-pencil"></i> </a> </li> <li class="dropdown"> <a class="pointer dropdown-toggle" data-toggle="dropdown" tabindex="1"> <i class="icon-cog"></i> </a> <ul class="dropdown-menu pull-right" role="menu"> <li role="menuitem"> <a tabindex="1" ng-click="duplicate()"> Duplicate </a> </li> <li role="menuitem"> <a tabindex="1" ng-click="toggleMetricOptions()"> Toggle request options </a> </li> </ul> </li> <li> <a class="pointer" tabindex="1" ng-click="removeTarget(target)"> <i class="icon-remove"></i> </a> </li> </ul> <ul class="grafana-target-controls-left"> <li> <a class="grafana-target-segment" ng-click="target.hide = !target.hide; get_data();" role="menuitem"> <i class="icon-eye-open"></i> </a> </li> </ul> <input type="text" class="grafana-target-text-input span10" ng-model="target.target" focus-me="showTextEditor" spellcheck='false' ng-model-onblur ng-change="targetTextChanged()" ng-show="showTextEditor" /> <ul class="grafana-segment-list" role="menu" ng-hide="showTextEditor"> <li class="dropdown" ng-repeat="segment in segments" role="menuitem"> <a tabindex="1" class="grafana-target-segment dropdown-toggle" data-toggle="dropdown" ng-click="getAltSegments($index)" focus-me="segment.focus" ng-bind-html-unsafe="segment.html"> </a> <ul class="dropdown-menu scrollable grafana-segment-dropdown-menu" role="menu"> <li ng-repeat="altSegment in altSegments" role="menuitem"> <a href="javascript:void(0)" tabindex="1" ng-click="setSegment($index, $parent.$index)" ng-bind-html-unsafe="altSegment.html"></a> </li> </ul> </li> <li ng-repeat="func in functions"> <span graphite-func-editor class="grafana-target-segment grafana-target-function"> </span> </li> <li class="dropdown" graphite-add-func> </li> </ul> <div class="clearfix"></div> </div> </div> <div class="grafana-target grafana-metric-options" ng-if="panel.metricOptionsEnabled"> <div class="grafana-target-inner"> <ul class="grafana-segment-list"> <li class="grafana-target-segment"> cacheTimeout <tip>Graphite parameter to overwride memcache default timeout (unit is seconds)</tip> </li> <li> <input type="text" class="input-large grafana-target-segment-input" ng-model="panel.cacheTimeout" spellcheck='false' placeholder="60"> </li> </ul> <div class="clearfix"></div> </div> </div> </div>
src/app/partials/graphite/editor.html
0
https://github.com/grafana/grafana/commit/e9a046e74d86b43b41c92bab5a8ac8beacb61441
[ 0.0006511385436169803, 0.00029229462961666286, 0.00016728912305552512, 0.0002748321567196399, 0.00012161306949565187 ]
{ "id": 1, "code_window": [ "- [Issue #606](https://github.com/grafana/grafana/issues/606). General: New global option in config.js to specify admin password (useful to hinder users from accidentally make changes)\n", "- [Issue #201](https://github.com/grafana/grafana/issues/201). Annotations: Elasticsearch datasource support for events\n", "- [Issue #631](https://github.com/grafana/grafana/issues/631). Search: max_results config.js option & scroll in search results (To show more or all dashboards)\n", "- [Issue #511](https://github.com/grafana/grafana/issues/511). Text panel: Allow [[..]] filter notation in all text panels (markdown/html/text)\n", "- [Issue #136](https://github.com/grafana/grafana/issues/136). Chart: New legend display option \"Align as table\"\n", "- [Issue #556](https://github.com/grafana/grafana/issues/556). Chart: New legend display option \"Right side\", will show legend to the right of the graph\n", "- [Issue #604](https://github.com/grafana/grafana/issues/604). Chart: New axis format, 'bps' (SI unit in steps of 1000) useful for network gear metics\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "- [Issue #344](https://github.com/grafana/grafana/issues/344). Annotations: Annotations can now be fetched from non default datasources\n" ], "file_path": "CHANGELOG.md", "type": "add", "edit_start_line_idx": 13 }
/** * AngularStrap - Twitter Bootstrap directives for AngularJS * @version v0.7.5 - 2013-07-21 * @link http://mgcrea.github.com/angular-strap * @author Olivier Louvignes <[email protected]> * @license MIT License, http://www.opensource.org/licenses/MIT */ angular.module('$strap.config', []).value('$strapConfig', {}); angular.module('$strap.filters', ['$strap.config']); angular.module('$strap.directives', ['$strap.config']); angular.module('$strap', [ '$strap.filters', '$strap.directives', '$strap.config' ]); 'use strict'; angular.module('$strap.directives').directive('bsAlert', [ '$parse', '$timeout', '$compile', function ($parse, $timeout, $compile) { return { restrict: 'A', link: function postLink(scope, element, attrs) { var getter = $parse(attrs.bsAlert), setter = getter.assign, value = getter(scope); var closeAlert = function closeAlertFn(delay) { $timeout(function () { element.alert('close'); }, delay * 1); }; if (!attrs.bsAlert) { if (angular.isUndefined(attrs.closeButton) || attrs.closeButton !== '0' && attrs.closeButton !== 'false') { element.prepend('<button type="button" class="close" data-dismiss="alert">&times;</button>'); } if (attrs.closeAfter) closeAlert(attrs.closeAfter); } else { scope.$watch(attrs.bsAlert, function (newValue, oldValue) { value = newValue; element.html((newValue.title ? '<strong>' + newValue.title + '</strong>&nbsp;' : '') + newValue.content || ''); if (!!newValue.closed) { element.hide(); } $compile(element.contents())(scope); if (newValue.type || oldValue.type) { oldValue.type && element.removeClass('alert-' + oldValue.type); newValue.type && element.addClass('alert-' + newValue.type); } if (angular.isDefined(newValue.closeAfter)) closeAlert(newValue.closeAfter); else if (attrs.closeAfter) closeAlert(attrs.closeAfter); if (angular.isUndefined(attrs.closeButton) || attrs.closeButton !== '0' && attrs.closeButton !== 'false') { element.prepend('<button type="button" class="close" data-dismiss="alert">&times;</button>'); } }, true); } element.addClass('alert').alert(); if (element.hasClass('fade')) { element.removeClass('in'); setTimeout(function () { element.addClass('in'); }); } var parentArray = attrs.ngRepeat && attrs.ngRepeat.split(' in ').pop(); element.on('close', function (ev) { var removeElement; if (parentArray) { ev.preventDefault(); element.removeClass('in'); removeElement = function () { element.trigger('closed'); if (scope.$parent) { scope.$parent.$apply(function () { var path = parentArray.split('.'); var curr = scope.$parent; for (var i = 0; i < path.length; ++i) { if (curr) { curr = curr[path[i]]; } } if (curr) { curr.splice(scope.$index, 1); } }); } }; $.support.transition && element.hasClass('fade') ? element.on($.support.transition.end, removeElement) : removeElement(); } else if (value) { ev.preventDefault(); element.removeClass('in'); removeElement = function () { element.trigger('closed'); scope.$apply(function () { value.closed = true; }); }; $.support.transition && element.hasClass('fade') ? element.on($.support.transition.end, removeElement) : removeElement(); } else { } }); } }; } ]); 'use strict'; angular.module('$strap.directives').directive('bsButton', [ '$parse', '$timeout', function ($parse, $timeout) { return { restrict: 'A', require: '?ngModel', link: function postLink(scope, element, attrs, controller) { if (controller) { if (!element.parent('[data-toggle="buttons-checkbox"], [data-toggle="buttons-radio"]').length) { element.attr('data-toggle', 'button'); } var startValue = !!scope.$eval(attrs.ngModel); if (startValue) { element.addClass('active'); } scope.$watch(attrs.ngModel, function (newValue, oldValue) { var bNew = !!newValue, bOld = !!oldValue; if (bNew !== bOld) { $.fn.button.Constructor.prototype.toggle.call(button); } else if (bNew && !startValue) { element.addClass('active'); } }); } if (!element.hasClass('btn')) { element.on('click.button.data-api', function (ev) { element.button('toggle'); }); } element.button(); var button = element.data('button'); button.toggle = function () { if (!controller) { return $.fn.button.Constructor.prototype.toggle.call(this); } var $parent = element.parent('[data-toggle="buttons-radio"]'); if ($parent.length) { element.siblings('[ng-model]').each(function (k, v) { $parse($(v).attr('ng-model')).assign(scope, false); }); scope.$digest(); if (!controller.$modelValue) { controller.$setViewValue(!controller.$modelValue); scope.$digest(); } } else { scope.$apply(function () { controller.$setViewValue(!controller.$modelValue); }); } }; } }; } ]).directive('bsButtonsCheckbox', [ '$parse', function ($parse) { return { restrict: 'A', require: '?ngModel', compile: function compile(tElement, tAttrs, transclude) { tElement.attr('data-toggle', 'buttons-checkbox').find('a, button').each(function (k, v) { $(v).attr('bs-button', ''); }); } }; } ]).directive('bsButtonsRadio', [ '$timeout', function ($timeout) { return { restrict: 'A', require: '?ngModel', compile: function compile(tElement, tAttrs, transclude) { tElement.attr('data-toggle', 'buttons-radio'); if (!tAttrs.ngModel) { tElement.find('a, button').each(function (k, v) { $(v).attr('bs-button', ''); }); } return function postLink(scope, iElement, iAttrs, controller) { if (controller) { $timeout(function () { iElement.find('[value]').button().filter('[value="' + controller.$viewValue + '"]').addClass('active'); }); iElement.on('click.button.data-api', function (ev) { scope.$apply(function () { controller.$setViewValue($(ev.target).closest('button').attr('value')); }); }); scope.$watch(iAttrs.ngModel, function (newValue, oldValue) { if (newValue !== oldValue) { var $btn = iElement.find('[value="' + scope.$eval(iAttrs.ngModel) + '"]'); if ($btn.length) { $btn.button('toggle'); } } }); } }; } }; } ]); 'use strict'; angular.module('$strap.directives').directive('bsButtonSelect', [ '$parse', '$timeout', function ($parse, $timeout) { return { restrict: 'A', require: '?ngModel', link: function postLink(scope, element, attrs, ctrl) { var getter = $parse(attrs.bsButtonSelect), setter = getter.assign; if (ctrl) { element.text(scope.$eval(attrs.ngModel)); scope.$watch(attrs.ngModel, function (newValue, oldValue) { element.text(newValue); }); } var values, value, index, newValue; element.bind('click', function (ev) { values = getter(scope); value = ctrl ? scope.$eval(attrs.ngModel) : element.text(); index = values.indexOf(value); newValue = index > values.length - 2 ? values[0] : values[index + 1]; scope.$apply(function () { element.text(newValue); if (ctrl) { ctrl.$setViewValue(newValue); } }); }); } }; } ]); 'use strict'; angular.module('$strap.directives').directive('bsDatepicker', [ '$timeout', '$strapConfig', function ($timeout, $strapConfig) { var isAppleTouch = /(iP(a|o)d|iPhone)/g.test(navigator.userAgent); var regexpMap = function regexpMap(language) { language = language || 'en'; return { '/': '[\\/]', '-': '[-]', '.': '[.]', ' ': '[\\s]', 'dd': '(?:(?:[0-2]?[0-9]{1})|(?:[3][01]{1}))', 'd': '(?:(?:[0-2]?[0-9]{1})|(?:[3][01]{1}))', 'mm': '(?:[0]?[1-9]|[1][012])', 'm': '(?:[0]?[1-9]|[1][012])', 'DD': '(?:' + $.fn.datepicker.dates[language].days.join('|') + ')', 'D': '(?:' + $.fn.datepicker.dates[language].daysShort.join('|') + ')', 'MM': '(?:' + $.fn.datepicker.dates[language].months.join('|') + ')', 'M': '(?:' + $.fn.datepicker.dates[language].monthsShort.join('|') + ')', 'yyyy': '(?:(?:[1]{1}[0-9]{1}[0-9]{1}[0-9]{1})|(?:[2]{1}[0-9]{3}))(?![[0-9]])', 'yy': '(?:(?:[0-9]{1}[0-9]{1}))(?![[0-9]])' }; }; var regexpForDateFormat = function regexpForDateFormat(format, language) { var re = format, map = regexpMap(language), i; i = 0; angular.forEach(map, function (v, k) { re = re.split(k).join('${' + i + '}'); i++; }); i = 0; angular.forEach(map, function (v, k) { re = re.split('${' + i + '}').join(v); i++; }); return new RegExp('^' + re + '$', ['i']); }; return { restrict: 'A', require: '?ngModel', link: function postLink(scope, element, attrs, controller) { var options = angular.extend({ autoclose: true }, $strapConfig.datepicker || {}), type = attrs.dateType || options.type || 'date'; angular.forEach([ 'format', 'weekStart', 'calendarWeeks', 'startDate', 'endDate', 'daysOfWeekDisabled', 'autoclose', 'startView', 'minViewMode', 'todayBtn', 'todayHighlight', 'keyboardNavigation', 'language', 'forceParse' ], function (key) { if (angular.isDefined(attrs[key])) options[key] = attrs[key]; }); var language = options.language || 'en', readFormat = attrs.dateFormat || options.format || $.fn.datepicker.dates[language] && $.fn.datepicker.dates[language].format || 'mm/dd/yyyy', format = isAppleTouch ? 'yyyy-mm-dd' : readFormat, dateFormatRegexp = regexpForDateFormat(format, language); if (controller) { controller.$formatters.unshift(function (modelValue) { return type === 'date' && angular.isString(modelValue) && modelValue ? $.fn.datepicker.DPGlobal.parseDate(modelValue, $.fn.datepicker.DPGlobal.parseFormat(readFormat), language) : modelValue; }); controller.$parsers.unshift(function (viewValue) { if (!viewValue) { controller.$setValidity('date', true); return null; } else if (type === 'date' && angular.isDate(viewValue)) { controller.$setValidity('date', true); return viewValue; } else if (angular.isString(viewValue) && dateFormatRegexp.test(viewValue)) { controller.$setValidity('date', true); if (isAppleTouch) return new Date(viewValue); return type === 'string' ? viewValue : $.fn.datepicker.DPGlobal.parseDate(viewValue, $.fn.datepicker.DPGlobal.parseFormat(format), language); } else { controller.$setValidity('date', false); return undefined; } }); controller.$render = function ngModelRender() { if (isAppleTouch) { var date = controller.$viewValue ? $.fn.datepicker.DPGlobal.formatDate(controller.$viewValue, $.fn.datepicker.DPGlobal.parseFormat(format), language) : ''; element.val(date); return date; } if (!controller.$viewValue) element.val(''); return element.datepicker('update', controller.$viewValue); }; } if (isAppleTouch) { element.prop('type', 'date').css('-webkit-appearance', 'textfield'); } else { if (controller) { element.on('changeDate', function (ev) { scope.$apply(function () { controller.$setViewValue(type === 'string' ? element.val() : ev.date); }); }); } element.datepicker(angular.extend(options, { format: format, language: language })); scope.$on('$destroy', function () { var datepicker = element.data('datepicker'); if (datepicker) { datepicker.picker.remove(); element.data('datepicker', null); } }); attrs.$observe('startDate', function (value) { element.datepicker('setStartDate', value); }); attrs.$observe('endDate', function (value) { element.datepicker('setEndDate', value); }); } var component = element.siblings('[data-toggle="datepicker"]'); if (component.length) { component.on('click', function () { if (!element.prop('disabled')) { element.trigger('focus'); } }); } } }; } ]); 'use strict'; angular.module('$strap.directives').directive('bsDropdown', [ '$parse', '$compile', '$timeout', function ($parse, $compile, $timeout) { var buildTemplate = function (items, ul) { if (!ul) ul = [ '<ul class="dropdown-menu" role="menu" aria-labelledby="drop1">', '</ul>' ]; angular.forEach(items, function (item, index) { if (item.divider) return ul.splice(index + 1, 0, '<li class="divider"></li>'); var li = '<li' + (item.submenu && item.submenu.length ? ' class="dropdown-submenu"' : '') + '>' + '<a tabindex="1" ng-href="' + (item.href || '') + '"' + (item.click ? '" ng-click="' + item.click + '"' : '') + (item.target ? '" target="' + item.target + '"' : '') + (item.method ? ' data-method="' + item.method + '"' : '') + '>' + (item.text || '') + '</a>'; if (item.submenu && item.submenu.length) li += buildTemplate(item.submenu).join('\n'); li += '</li>'; ul.splice(index + 1, 0, li); }); return ul; }; return { restrict: 'EA', scope: true, link: function postLink(scope, iElement, iAttrs) { var getter = $parse(iAttrs.bsDropdown), items = getter(scope); $timeout(function () { if (!angular.isArray(items)) { } var dropdown = angular.element(buildTemplate(items).join('')); dropdown.insertAfter(iElement); $compile(iElement.next('ul.dropdown-menu'))(scope); }); iElement.addClass('dropdown-toggle').attr('data-toggle', 'dropdown'); } }; } ]); 'use strict'; angular.module('$strap.directives').factory('$modal', [ '$rootScope', '$compile', '$http', '$timeout', '$q', '$templateCache', '$strapConfig', function ($rootScope, $compile, $http, $timeout, $q, $templateCache, $strapConfig) { var ModalFactory = function ModalFactory(config) { function Modal(config) { var options = angular.extend({ show: true }, $strapConfig.modal, config), scope = options.scope ? options.scope : $rootScope.$new(), templateUrl = options.template; return $q.when($templateCache.get(templateUrl) || $http.get(templateUrl, { cache: true }).then(function (res) { return res.data; })).then(function onSuccess(template) { var id = templateUrl.replace('.html', '').replace(/[\/|\.|:]/g, '-') + '-' + scope.$id; var $modal = $('<div class="modal hide" tabindex="-1"></div>').attr('id', id).addClass('fade').html(template); if (options.modalClass) $modal.addClass(options.modalClass); $('body').append($modal); $timeout(function () { $compile($modal)(scope); }); scope.$modal = function (name) { $modal.modal(name); }; angular.forEach([ 'show', 'hide' ], function (name) { scope[name] = function () { $modal.modal(name); }; }); scope.dismiss = scope.hide; angular.forEach([ 'show', 'shown', 'hide', 'hidden' ], function (name) { $modal.on(name, function (ev) { scope.$emit('modal-' + name, ev); }); }); $modal.on('shown', function (ev) { $('input[autofocus], textarea[autofocus]', $modal).first().trigger('focus'); }); $modal.on('hidden', function (ev) { if (!options.persist) scope.$destroy(); }); scope.$on('$destroy', function () { $modal.remove(); }); $modal.modal(options); return $modal; }); } return new Modal(config); }; return ModalFactory; } ]).directive('bsModal', [ '$q', '$modal', function ($q, $modal) { return { restrict: 'A', scope: true, link: function postLink(scope, iElement, iAttrs, controller) { var options = { template: scope.$eval(iAttrs.bsModal), persist: true, show: false, scope: scope }; angular.forEach([ 'modalClass', 'backdrop', 'keyboard' ], function (key) { if (angular.isDefined(iAttrs[key])) options[key] = iAttrs[key]; }); $q.when($modal(options)).then(function onSuccess(modal) { iElement.attr('data-target', '#' + modal.attr('id')).attr('data-toggle', 'modal'); }); } }; } ]); 'use strict'; angular.module('$strap.directives').directive('bsNavbar', [ '$location', function ($location) { return { restrict: 'A', link: function postLink(scope, element, attrs, controller) { scope.$watch(function () { return $location.path(); }, function (newValue, oldValue) { $('li[data-match-route]', element).each(function (k, li) { var $li = angular.element(li), pattern = $li.attr('data-match-route'), regexp = new RegExp('^' + pattern + '$', ['i']); if (regexp.test(newValue)) { $li.addClass('active').find('.collapse.in').collapse('hide'); } else { $li.removeClass('active'); } }); }); } }; } ]); 'use strict'; angular.module('$strap.directives').directive('bsPopover', [ '$parse', '$compile', '$http', '$timeout', '$q', '$templateCache', function ($parse, $compile, $http, $timeout, $q, $templateCache) { $('body').on('keyup', function (ev) { if (ev.keyCode === 27) { $('.popover.in').each(function () { $(this).popover('hide'); }); } }); return { restrict: 'A', scope: true, link: function postLink(scope, element, attr, ctrl) { var getter = $parse(attr.bsPopover), setter = getter.assign, value = getter(scope), options = {}; if (angular.isObject(value)) { options = value; } $q.when(options.content || $templateCache.get(value) || $http.get(value, { cache: true })).then(function onSuccess(template) { if (angular.isObject(template)) { template = template.data; } if (!!attr.unique) { element.on('show', function (ev) { $('.popover.in').each(function () { var $this = $(this), popover = $this.data('popover'); if (popover && !popover.$element.is(element)) { $this.popover('hide'); } }); }); } if (!!attr.hide) { scope.$watch(attr.hide, function (newValue, oldValue) { if (!!newValue) { popover.hide(); } else if (newValue !== oldValue) { popover.show(); } }); } if (!!attr.show) { scope.$watch(attr.show, function (newValue, oldValue) { if (!!newValue) { $timeout(function () { popover.show(); }); } else if (newValue !== oldValue) { popover.hide(); } }); } element.popover(angular.extend({}, options, { content: template, html: true })); var popover = element.data('popover'); popover.hasContent = function () { return this.getTitle() || template; }; popover.getPosition = function () { var r = $.fn.popover.Constructor.prototype.getPosition.apply(this, arguments); $compile(this.$tip)(scope); scope.$digest(); this.$tip.data('popover', this); return r; }; scope.$popover = function (name) { popover(name); }; angular.forEach([ 'show', 'hide' ], function (name) { scope[name] = function () { popover[name](); }; }); scope.dismiss = scope.hide; angular.forEach([ 'show', 'shown', 'hide', 'hidden' ], function (name) { element.on(name, function (ev) { scope.$emit('popover-' + name, ev); }); }); }); } }; } ]); 'use strict'; angular.module('$strap.directives').directive('bsSelect', [ '$timeout', function ($timeout) { var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/; return { restrict: 'A', require: '?ngModel', link: function postLink(scope, element, attrs, controller) { var options = scope.$eval(attrs.bsSelect) || {}; $timeout(function () { element.selectpicker(options); element.next().removeClass('ng-scope'); }); if (controller) { scope.$watch(attrs.ngModel, function (newValue, oldValue) { if (!angular.equals(newValue, oldValue)) { element.selectpicker('refresh'); } }); } } }; } ]); 'use strict'; angular.module('$strap.directives').directive('bsTabs', [ '$parse', '$compile', '$timeout', function ($parse, $compile, $timeout) { var template = '<div class="tabs">' + '<ul class="nav nav-tabs">' + '<li ng-repeat="pane in panes" ng-class="{active:pane.active}">' + '<a data-target="#{{pane.id}}" data-index="{{$index}}" data-toggle="tab">{{pane.title}}</a>' + '</li>' + '</ul>' + '<div class="tab-content" ng-transclude>' + '</div>'; return { restrict: 'A', require: '?ngModel', priority: 0, scope: true, template: template, replace: true, transclude: true, compile: function compile(tElement, tAttrs, transclude) { return function postLink(scope, iElement, iAttrs, controller) { var getter = $parse(iAttrs.bsTabs), setter = getter.assign, value = getter(scope); scope.panes = []; var $tabs = iElement.find('ul.nav-tabs'); var $panes = iElement.find('div.tab-content'); var activeTab = 0, id, title, active; $timeout(function () { $panes.find('[data-title], [data-tab]').each(function (index) { var $this = angular.element(this); id = 'tab-' + scope.$id + '-' + index; title = $this.data('title') || $this.data('tab'); active = !active && $this.hasClass('active'); $this.attr('id', id).addClass('tab-pane'); if (iAttrs.fade) $this.addClass('fade'); scope.panes.push({ id: id, title: title, content: this.innerHTML, active: active }); }); if (scope.panes.length && !active) { $panes.find('.tab-pane:first-child').addClass('active' + (iAttrs.fade ? ' in' : '')); scope.panes[0].active = true; } }); if (controller) { iElement.on('show', function (ev) { var $target = $(ev.target); scope.$apply(function () { controller.$setViewValue($target.data('index')); }); }); scope.$watch(iAttrs.ngModel, function (newValue, oldValue) { if (angular.isUndefined(newValue)) return; activeTab = newValue; setTimeout(function () { // Check if we're still on the same tab before making the switch if(activeTab === newValue) { var $next = $($tabs[0].querySelectorAll('li')[newValue * 1]); if (!$next.hasClass('active')) { $next.children('a').tab('show'); } } }); }); } }; } }; } ]); 'use strict'; angular.module('$strap.directives').directive('bsTimepicker', [ '$timeout', '$strapConfig', function ($timeout, $strapConfig) { var TIME_REGEXP = '((?:(?:[0-1][0-9])|(?:[2][0-3])|(?:[0-9])):(?:[0-5][0-9])(?::[0-5][0-9])?(?:\\s?(?:am|AM|pm|PM))?)'; return { restrict: 'A', require: '?ngModel', link: function postLink(scope, element, attrs, controller) { if (controller) { element.on('changeTime.timepicker', function (ev) { $timeout(function () { controller.$setViewValue(element.val()); }); }); var timeRegExp = new RegExp('^' + TIME_REGEXP + '$', ['i']); controller.$parsers.unshift(function (viewValue) { if (!viewValue || timeRegExp.test(viewValue)) { controller.$setValidity('time', true); return viewValue; } else { controller.$setValidity('time', false); return; } }); } element.attr('data-toggle', 'timepicker'); element.parent().addClass('bootstrap-timepicker'); element.timepicker($strapConfig.timepicker || {}); var timepicker = element.data('timepicker'); var component = element.siblings('[data-toggle="timepicker"]'); if (component.length) { component.on('click', $.proxy(timepicker.showWidget, timepicker)); } } }; } ]); 'use strict'; angular.module('$strap.directives').directive('bsTooltip', [ '$parse', '$compile', function ($parse, $compile) { return { restrict: 'A', scope: true, link: function postLink(scope, element, attrs, ctrl) { var getter = $parse(attrs.bsTooltip), setter = getter.assign, value = getter(scope); scope.$watch(attrs.bsTooltip, function (newValue, oldValue) { if (newValue !== oldValue) { value = newValue; } }); if (!!attrs.unique) { element.on('show', function (ev) { $('.tooltip.in').each(function () { var $this = $(this), tooltip = $this.data('tooltip'); if (tooltip && !tooltip.$element.is(element)) { $this.tooltip('hide'); } }); }); } element.tooltip({ title: function () { return angular.isFunction(value) ? value.apply(null, arguments) : value; }, html: true }); var tooltip = element.data('tooltip'); tooltip.show = function () { var r = $.fn.tooltip.Constructor.prototype.show.apply(this, arguments); this.tip().data('tooltip', this); return r; }; scope._tooltip = function (event) { element.tooltip(event); }; scope.hide = function () { element.tooltip('hide'); }; scope.show = function () { element.tooltip('show'); }; scope.dismiss = scope.hide; } }; } ]); 'use strict'; angular.module('$strap.directives').directive('bsTypeahead', [ '$parse', function ($parse) { return { restrict: 'A', require: '?ngModel', link: function postLink(scope, element, attrs, controller) { var getter = $parse(attrs.bsTypeahead), setter = getter.assign, value = getter(scope); scope.$watch(attrs.bsTypeahead, function (newValue, oldValue) { if (newValue !== oldValue) { value = newValue; } }); element.attr('data-provide', 'typeahead'); element.typeahead({ source: function (query) { return angular.isFunction(value) ? value.apply(null, arguments) : value; }, minLength: attrs.minLength || 1, items: attrs.items, updater: function (value) { if (controller) { scope.$apply(function () { controller.$setViewValue(value); }); } scope.$emit('typeahead-updated', value); return value; } }); var typeahead = element.data('typeahead'); typeahead.lookup = function (ev) { var items; this.query = this.$element.val() || ''; if (this.query.length < this.options.minLength) { return this.shown ? this.hide() : this; } items = $.isFunction(this.source) ? this.source(this.query, $.proxy(this.process, this)) : this.source; return items ? this.process(items) : this; }; if (!!attrs.matchAll) { typeahead.matcher = function (item) { return true; }; } if (attrs.minLength === '0') { setTimeout(function () { element.on('focus', function () { element.val().length === 0 && setTimeout(element.typeahead.bind(element, 'lookup'), 200); }); }); } } }; } ]);
src/vendor/angular/angular-strap.js
0
https://github.com/grafana/grafana/commit/e9a046e74d86b43b41c92bab5a8ac8beacb61441
[ 0.0002692790876608342, 0.00017991531058214605, 0.0001661016431171447, 0.0001745456684147939, 0.00001714566496957559 ]
{ "id": 1, "code_window": [ "- [Issue #606](https://github.com/grafana/grafana/issues/606). General: New global option in config.js to specify admin password (useful to hinder users from accidentally make changes)\n", "- [Issue #201](https://github.com/grafana/grafana/issues/201). Annotations: Elasticsearch datasource support for events\n", "- [Issue #631](https://github.com/grafana/grafana/issues/631). Search: max_results config.js option & scroll in search results (To show more or all dashboards)\n", "- [Issue #511](https://github.com/grafana/grafana/issues/511). Text panel: Allow [[..]] filter notation in all text panels (markdown/html/text)\n", "- [Issue #136](https://github.com/grafana/grafana/issues/136). Chart: New legend display option \"Align as table\"\n", "- [Issue #556](https://github.com/grafana/grafana/issues/556). Chart: New legend display option \"Right side\", will show legend to the right of the graph\n", "- [Issue #604](https://github.com/grafana/grafana/issues/604). Chart: New axis format, 'bps' (SI unit in steps of 1000) useful for network gear metics\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "- [Issue #344](https://github.com/grafana/grafana/issues/344). Annotations: Annotations can now be fetched from non default datasources\n" ], "file_path": "CHANGELOG.md", "type": "add", "edit_start_line_idx": 13 }
define([ 'angular', 'app', 'underscore' ], function (angular, app, _) { 'use strict'; angular .module('grafana.directives') .directive('bodyClass', function() { return { link: function($scope, elem) { var lastPulldownVal; var lastHideControlsVal; $scope.$watch('dashboard.pulldowns', function() { if (!$scope.dashboard) { return; } var panel = _.find($scope.dashboard.pulldowns, function(pulldown) { return pulldown.enable; }); var panelEnabled = panel ? panel.enable : false; if (lastPulldownVal !== panelEnabled) { elem.toggleClass('submenu-controls-visible', panelEnabled); lastPulldownVal = panelEnabled; } }, true); $scope.$watch('dashboard.hideControls', function() { if (!$scope.dashboard) { return; } var hideControls = $scope.dashboard.hideControls || $scope.playlist_active; if (lastHideControlsVal !== hideControls) { elem.toggleClass('hide-controls', hideControls); lastHideControlsVal = hideControls; } }); $scope.$watch('playlist_active', function() { elem.toggleClass('hide-controls', $scope.playlist_active === true); elem.toggleClass('playlist-active', $scope.playlist_active === true); }); } }; }); });
src/app/directives/bodyClass.js
0
https://github.com/grafana/grafana/commit/e9a046e74d86b43b41c92bab5a8ac8beacb61441
[ 0.006122671067714691, 0.001239071600139141, 0.00016553387104067951, 0.00026980257825925946, 0.0021859444677829742 ]
{ "id": 2, "code_window": [ " // Receive render events\n", " scope.$on('render',function(event, renderData) {\n", " data = renderData || data;\n", " annotations = data.annotations;\n", " render_panel();\n", " });\n", "\n", " // Re-render if the window is resized\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " annotations = data.annotations || annotations;\n" ], "file_path": "src/app/directives/grafanaGraph.js", "type": "replace", "edit_start_line_idx": 41 }
# 1.7.0 (unreleased) **New features or improvements** - [Issue #581](https://github.com/grafana/grafana/issues/581). InfluxDB: Add continuous query in series results (series typeahead). - [Issue #584](https://github.com/grafana/grafana/issues/584). InfluxDB: Support for alias & alias patterns when using raw query mode - [Issue #394](https://github.com/grafana/grafana/issues/394). InfluxDB: Annotation support - [Issue #633](https://github.com/grafana/grafana/issues/633). InfluxDB: InfluxDB can now act as a datastore for dashboards - [Issue #610](https://github.com/grafana/grafana/issues/610). InfluxDB: Support for InfluxdB v0.8 list series response schemea (series typeahead) - [Issue #525](https://github.com/grafana/grafana/issues/525). InfluxDB: Enhanced series aliasing (legend names) with pattern replacements - [Issue #266](https://github.com/grafana/grafana/issues/266). Graphite: New option cacheTimeout to override graphite default memcache timeout - [Issue #344](https://github.com/grafana/grafana/issues/344). Graphite: Annotations can now be fetched from non default datasources - [Issue #606](https://github.com/grafana/grafana/issues/606). General: New global option in config.js to specify admin password (useful to hinder users from accidentally make changes) - [Issue #201](https://github.com/grafana/grafana/issues/201). Annotations: Elasticsearch datasource support for events - [Issue #631](https://github.com/grafana/grafana/issues/631). Search: max_results config.js option & scroll in search results (To show more or all dashboards) - [Issue #511](https://github.com/grafana/grafana/issues/511). Text panel: Allow [[..]] filter notation in all text panels (markdown/html/text) - [Issue #136](https://github.com/grafana/grafana/issues/136). Chart: New legend display option "Align as table" - [Issue #556](https://github.com/grafana/grafana/issues/556). Chart: New legend display option "Right side", will show legend to the right of the graph - [Issue #604](https://github.com/grafana/grafana/issues/604). Chart: New axis format, 'bps' (SI unit in steps of 1000) useful for network gear metics - [Issue #626](https://github.com/grafana/grafana/issues/626). Chart: Downscale y axis to more precise unit, value of 0.1 for seconds format will be formated as 100 ms. Thanks @kamaradclimber - [Issue #618](https://github.com/grafana/grafana/issues/618). OpenTSDB: Series alias option to override metric name returned from opentsdb. Thanks @heldr **Changes** - [Issue #536](https://github.com/grafana/grafana/issues/536). Graphite: Use unix epoch for Graphite from/to for absolute time ranges - [Issue #641](https://github.com/grafana/grafana/issues/536). General: Dashboard save temp copy feature settings moved from dashboard to config.js, default is enabled, and ttl to 30 days **Fixes** - [Issue #545](https://github.com/grafana/grafana/issues/545). Chart: Fix formatting negative values (axis formats, legend values) - [Issue #460](https://github.com/grafana/grafana/issues/460). Chart: fix for max legend value when max value is zero - [Issue #628](https://github.com/grafana/grafana/issues/628). Filtering: Fix for nested filters, changing a child filter could result in infinite recursion in some cases - [Issue #528](https://github.com/grafana/grafana/issues/528). Graphite: Fix for graphite expressions parser failure when metric expressions starts with curly brace segment # 1.6.1 (2014-06-24) **New features or improvements** - [Issue #360](https://github.com/grafana/grafana/issues/360). Ability to set y min/max for right y-axis (RR #519) **Fixes** - [Issue #500](https://github.com/grafana/grafana/issues/360). Fixes regex InfluxDB queries intoduced in 1.6.0 - [Issue #506](https://github.com/grafana/grafana/issues/506). Bug in when using % sign in legends (aliases), fixed by removing url decoding of metric names - [Issue #522](https://github.com/grafana/grafana/issues/522). Series names and column name typeahead cache fix - [Issue #504](https://github.com/grafana/grafana/issues/504). Fixed influxdb issue with raw query that caused wrong value column detection - [Issue #526](https://github.com/grafana/grafana/issues/526). Default property that marks which datasource is default in config.js is now optional - [Issue #342](https://github.com/grafana/grafana/issues/342). Auto-refresh caused 2 refreshes (and hence mulitple queries) each time (at least in firefox) # 1.6.0 (2014-06-16) #### New features or improvements - [Issue #427](https://github.com/grafana/grafana/issues/427). New Y-axis formater for metric values that represent seconds, Thanks @jippi - [Issue #390](https://github.com/grafana/grafana/issues/390). Allow special characters in serie names (influxdb datasource), Thanks @majst01 - [Issue #428](https://github.com/grafana/grafana/issues/428). Refactoring of filterSrv, Thanks @Tetha - [Issue #445](https://github.com/grafana/grafana/issues/445). New config for playlist feature. Set playlist_timespan to set default playlist interval, Thanks @rmca - [Issue #461](https://github.com/grafana/grafana/issues/461). New graphite function definition added isNonNull, Thanks @tmonk42 - [Issue #455](https://github.com/grafana/grafana/issues/455). New InfluxDB function difference add to function dropdown - [Issue #459](https://github.com/grafana/grafana/issues/459). Added parameter to keepLastValue graphite function definition (default 100) [Issue #418](https://github.com/grafana/grafana/issues/418). to the browser cache when upgrading grafana and improve load performance - [Issue #327](https://github.com/grafana/grafana/issues/327). Partial support for url encoded metrics when using Graphite datasource. Thanks @axe-felix - [Issue #473](https://github.com/grafana/grafana/issues/473). Improvement to InfluxDB query editor and function/value column selection - [Issue #375](https://github.com/grafana/grafana/issues/375). Initial support for filtering (templated queries) for InfluxDB. Thanks @mavimo - [Issue #475](https://github.com/grafana/grafana/issues/475). Row editing and adding new panel is now a lot quicker and easier with the new row menu - [Issue #211](https://github.com/grafana/grafana/issues/211). New datasource! Initial support for OpenTSDB, Thanks @mpage - [Issue #492](https://github.com/grafana/grafana/issues/492). Improvement and polish to the OpenTSDB query editor - [Issue #441](https://github.com/grafana/grafana/issues/441). Influxdb group by support, Thanks @piis3 - improved asset (css/js) build pipeline, added revision to css and js. Will remove issues related #### Changes - [Issue #475](https://github.com/grafana/grafana/issues/475). Add panel icon and Row edit button is replaced by the Row edit menu - New graphs now have a default empty query - Add Row button now creates a row with default height of 250px (no longer opens dashboard settings modal) - Clean up of config.sample.js, graphiteUrl removed (still works, but depricated, removed in future) Use datasources config instead. panel_names removed from config.js. Use plugins.panels to add custom panels - Graphite panel is now renamed graph (Existing dashboards will still work) #### Fixes - [Issue #126](https://github.com/grafana/grafana/issues/126). Graphite query lexer change, can now handle regex parameters for aliasSub function - [Issue #447](https://github.com/grafana/grafana/issues/447). Filter option loading when having muliple nested filters now works better. Options are now reloaded correctly and there are no multiple renders/refresh inbetween. - [Issue #412](https://github.com/grafana/grafana/issues/412). After a filter option is changed and a nested template param is reloaded, if the current value exists after the options are reloaded the current selected value is kept. - [Issue #460](https://github.com/grafana/grafana/issues/460). Legend Current value did not display when value was zero - [Issue #328](https://github.com/grafana/grafana/issues/328). Fix to series toggling bug that caused annotations to be hidden when toggling/hiding series. - [Issue #293](https://github.com/grafana/grafana/issues/293). Fix for graphite function selection menu that some times draws outside screen. It now displays upward - [Issue #350](https://github.com/grafana/grafana/issues/350). Fix for exclusive series toggling (hold down CTRL, SHIFT or META key) and left click a series for exclusive toggling - [Issue #472](https://github.com/grafana/grafana/issues/472). CTRL does not work on MAC OSX but SHIFT or META should (depending on browser) # 1.5.4 (2014-05-13) ### New features and improvements - InfluxDB enhancement: support for multiple hosts (with retries) and raw queries ([Issue #318](https://github.com/grafana/grafana/issues/318), thx @toddboom) - Added rounding for graphites from and to time range filters for very short absolute ranges ([Issue #320](https://github.com/grafana/grafana/issues/320)) - Increased resolution for graphite datapoints (maxDataPoints), now equal to panel pixel width. ([Issue #5](https://github.com/grafana/grafana/issues/5)) - Improvement to influxdb query editor, can now add where clause and alias ([Issue #331](https://github.com/grafana/grafana/issues/331), thanks @mavimo) - New config setting for graphite datasource to control if json render request is POST or GET ([Issue #345](https://github.com/grafana/grafana/issues/345)) - Unsaved changes warning feature ([Issue #324](https://github.com/grafana/grafana/issues/324)) - Improvement to series toggling, CTRL+MouseClick on series name will now hide all others ([Issue #350](https://github.com/grafana/grafana/issues/350)) ### Changes - Graph default setting for Y-Min changed from zero to auto scalling (will not effect existing dashboards). ([Issue #386](https://github.com/grafana/grafana/issues/386)) - thx @kamaradclimber ### Fixes - Fixes to filters and "All" option. It now never uses "*" as value, but all options in a {node1, node2, node3} expression ([Issue #228](https://github.com/grafana/grafana/issues/228), #359) - Fix for InfluxDB query generation with columns containing dots or dashes ([Issue #369](https://github.com/grafana/grafana/issues/369), #348) - Thanks to @jbripley # 1.5.3 (2014-04-17) - Add support for async scripted dashboards ([Issue #274](https://github.com/grafana/grafana/issues/274)) - Text panel now accepts html (for links to other dashboards, etc) ([Issue #236](https://github.com/grafana/grafana/issues/236)) - Fix for Text panel, now changes take effect directly ([Issue #251](https://github.com/grafana/grafana/issues/251)) - Fix when adding functions without params that did not cause graph to update ([Issue #267](https://github.com/grafana/grafana/issues/267)) - Graphite errors are now much easier to see and troubleshoot with the new inspector ([Issue #265](https://github.com/grafana/grafana/issues/265)) - Use influxdb aliases to distinguish between multiple columns ([Issue #283](https://github.com/grafana/grafana/issues/283)) - Correction to ms axis formater, now formats days correctly. ([Issue #189](https://github.com/grafana/grafana/issues/189)) - Css fix for Firefox and using top menu dropdowns in panel fullscren / edit mode ([Issue #106](https://github.com/grafana/grafana/issues/106)) - Browser page title is now Grafana - {{dashboard title}} ([Issue #294](https://github.com/grafana/grafana/issues/294)) - Disable auto refresh zooming in (every time you change to an absolute time range), refresh will be restored when you change time range back to relative ([Issue #282](https://github.com/grafana/grafana/issues/282)) - More graphite functions # 1.5.2 (2014-03-24) ### New Features and improvements - Support for second optional params for functions like aliasByNode ([Issue #167](https://github.com/grafana/grafana/issues/167)). Read the wiki on the [Function Editor](https://github.com/torkelo/grafana/wiki/Graphite-Function-Editor) for more info. - More functions added to InfluxDB query editor ([Issue #218](https://github.com/grafana/grafana/issues/218)) - Filters can now be used inside other filters (templated segments) ([Issue #128](https://github.com/grafana/grafana/issues/128)) - More graphite functions added ### Fixes - Float arguments now work for functions like scale ([Issue #223](https://github.com/grafana/grafana/issues/223)) - Fix for graphite function editor, the graph & target was not updated after adding a function and leaving default params as is #191 The zip files now contains a sub folder with project name and version prefix. ([Issue #209](https://github.com/grafana/grafana/issues/209)) # 1.5.1 (2014-03-10) ### Fixes - maxDataPoints must be an integer #184 (thanks @frejsoya for fixing this) For people who are find Grafana slow for large time spans or high resolution metrics. This is most likely due to graphite returning a large number of datapoints. The maxDataPoints parameter solves this issue. For maxDataPoints to work you need to run the latest graphite-web (some builds of 0.9.12 does not include this feature). Read this for more info: [Performance for large time spans](https://github.com/torkelo/grafana/wiki/Performance-for-large-time-spans) # 1.5.0 (2014-03-09) ### New Features and improvements - New function editor [video demo](http://youtu.be/I90WHRwE1ZM) ([Issue #178](https://github.com/grafana/grafana/issues/178)) - Links to function documentation from function editor ([Issue #3](https://github.com/grafana/grafana/issues/3)) - Reorder functions ([Issue #130](https://github.com/grafana/grafana/issues/130)) - [Initial support for InfluxDB](https://github.com/torkelo/grafana/wiki/InfluxDB) as metric datasource (#103), need feedback! - [Dashboard playlist](https://github.com/torkelo/grafana/wiki/Dashboard-playlist) ([Issue #36](https://github.com/grafana/grafana/issues/36)) - When adding aliasByNode smartly set node number ([Issue #175](https://github.com/grafana/grafana/issues/175)) - Support graphite identifiers with embedded colons ([Issue #173](https://github.com/grafana/grafana/issues/173)) - Typeahead & autocomplete when adding new function ([Issue #164](https://github.com/grafana/grafana/issues/164)) - More graphite function definitions - Make "ms" axis format include hour, day, weeks, month and year ([Issue #149](https://github.com/grafana/grafana/issues/149)) - Microsecond axis format ([Issue #146](https://github.com/grafana/grafana/issues/146)) - Specify template paramaters in URL ([Issue #123](https://github.com/grafana/grafana/issues/123)) ### Fixes - Basic Auth fix ([Issue #152](https://github.com/grafana/grafana/issues/152)) - Fix to annotations with graphite source & null values ([Issue #138](https://github.com/grafana/grafana/issues/138)) # 1.4.0 (2014-02-21) ### New Features - #44 Annotations! Required a lot of work to get right. Read wiki article for more info. Supported annotations data sources are graphite metrics and graphite events. Support for more will be added in the future! - #35 Support for multiple graphite servers! (Read wiki article for more) - #116 Back to dashboard link in top menu to easily exist full screen / edit mode. - #114, #97 Legend values now use the same y axes formatter - #77 Improvements and polish to the light theme ### Changes - #98 Stack is no longer by default turned on in graph display settings. - Hide controls (Ctrl+h) now hides the sub menu row (where filtering, and annotations are). So if you had filtering enabled and hide controls enabled you will not see the filtering sub menu. ### Fixes: - #94 Fix for bug that caused dashboard settings to sometimes not contain timepicker tab. - #110 Graph with many many metrics caused legend to push down graph editor below screen. You can now scroll in edit mode & full screen mode for graphs with lots of series & legends. - #104 Improvement to graphite target editor, select wildcard now gives you a "select metric" link for the next node. - #105 Added zero as a possible node value in groupByAlias function # 1.3.0 (2014-02-13) ### New features or improvements - #86 Dashboard tags and search (see wiki article for details) - #54 Enhancement to filter / template. "Include All" improvement - #82 Dashboard search result sorted in alphabetical order ### Fixes - #91 Custom date selector is one day behind - #89 Filter / template does not work after switching dashboard - #88 Closed / Minimized row css bug - #85 Added all parameters to summarize function - #83 Stack as percent should now work a lot better! # 1.2.0 (2014-02-10) ### New features - #70 Grid Thresholds (warning and error regions or lines in graph) - #72 Added an example of a scripted dashboard and a short wiki article documenting scripted dashboards. ### Fixes - #81 Grid min/max values are ignored bug - #80 "stacked as percent" graphs should always use "max" value of 100 bug - #73 Left Y format change did not work - #42 Fixes to grid min/max auto scaling - #69 Fixes to lexer/parser for metrics segments like "10-20". - #67 Allow decimal input for scale function - #68 Bug when trying to open dashboard while in edit mode # 1.1.0 (2014-02-06) ### New features: - #22 Support for native graphite png renderer, does not support click and select zoom yet - #60 Support for legend values (cactiStyle, min, max, current, total, avg). The options for these are found in the new "Axes & Grid" tab for now. - #62 There is now a "New" button in the search/open dashboard view to quickly open a clean empty dashboard. - #55 Basic auth is now supported for elastic search as well - some new function definitions added (will focus more on this for next release). ### Fixes - #45 zero values from graphite was handled as null. - #63 Kibana / Grafana on same host would use same localStorage keys, now fixed - #46 Impossible to edit graph without a name fixed. - #24 fix for dashboard search when elastic search is configured to disable _all field. - #38 Improvement to lexer / parser to support pure numeric literals in metric segments Thanks to everyone who contributed fixes and provided feedback :+1: # 1.0.4 (2014-01-24) - [Issue #28](https://github.com/grafana/grafana/issues/28) - Relative time range caused 500 graphite error in some cases (thx rsommer for the fix) # 1.0.3 (2014-01-23) - #9 Add Y-axis format for milliseconds - #16 Add support for Basic Auth (use http://username:[email protected]) - #13 Relative time ranges now uses relative time ranges when issuing graphite query # 1.0.2 (2014-01-21) - [Issue #12](https://github.com/grafana/grafana/issues/12), should now work ok without ElasticSearch # 1.0.1 (2014-01-21) - Resize fix - Improvements to drag & drop - Added a few graphite function definitions - Fixed duplicate panel bug - Updated default dashboard with welcome message and randomWalk graph # 1.0.0 (2014-01-19) First public release
CHANGELOG.md
1
https://github.com/grafana/grafana/commit/e9a046e74d86b43b41c92bab5a8ac8beacb61441
[ 0.0002750915300566703, 0.00017504832067061216, 0.00016346735355909914, 0.00017126718012150377, 0.000020730456526507623 ]
{ "id": 2, "code_window": [ " // Receive render events\n", " scope.$on('render',function(event, renderData) {\n", " data = renderData || data;\n", " annotations = data.annotations;\n", " render_panel();\n", " });\n", "\n", " // Re-render if the window is resized\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " annotations = data.annotations || annotations;\n" ], "file_path": "src/app/directives/grafanaGraph.js", "type": "replace", "edit_start_line_idx": 41 }
# Courtesy of https://github.com/sgzijl # config.js includes elasticsearch: "https://"+window.location.hostname+":443", <VirtualHost 1.2.3.4:80> ServerName your.domain.tld RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} </VirtualHost> <VirtualHost 1.2.3.4:443> ServerName your.domain.tld SSLEngine on SSLCertificateFile /path/to/public.crt SSLCertificateKeyFile /path/to/private.key DocumentRoot /path/to/kibana3 <Directory /path/to/kibana3> Allow from all Options -Multiviews </Directory> LogLevel debug ErrorLog /path/to/logs/error_log CustomLog /path/to/logs/access_log combined # Set global proxy timeouts <Proxy http://127.0.0.1:9200> ProxySet connectiontimeout=5 timeout=90 </Proxy> # Proxy for _aliases and .*/_search <LocationMatch "^/(_nodes|_aliases|_search|.*/_search|_mapping|.*/_mapping)$"> ProxyPassMatch http://127.0.0.1:9200/$1 ProxyPassReverse http://127.0.0.1:9200/$1 </LocationMatch> # Proxy for kibana-int/{dashboard,temp} stuff (if you don't want auth on /, then you will want these to be protected) <LocationMatch "^/(kibana-int/dashboard/|kibana-int/temp)(.*)$"> ProxyPassMatch http://127.0.0.1:9200/$1$2 ProxyPassReverse http://127.0.0.1:9200/$1$2 </LocationMatch> # Optional disable auth for a src IP (eg: your monitoring host or subnet) <Location /> Allow from 5.6.7.8 Deny from all Satisfy any AuthLDAPBindDN "CN=_ldapbinduser,OU=Users,DC=example,DC=com" AuthLDAPBindPassword "ldapbindpass" AuthLDAPURL "ldaps://ldap01.example.com ldap02.example.com/OU=Users,DC=example,DC=com?sAMAccountName?sub?(objectClass=*)" AuthType Basic AuthBasicProvider ldap AuthName "Please authenticate for Example dot com" AuthLDAPGroupAttributeIsDN on require valid-user </Location> </VirtualHost>
sample/apache_ldap.conf
0
https://github.com/grafana/grafana/commit/e9a046e74d86b43b41c92bab5a8ac8beacb61441
[ 0.00017390407447237521, 0.00017104540893342346, 0.00016418169252574444, 0.0001729171199258417, 0.00000368888390767097 ]